diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..48f900f --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: thomchantra diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4207d9a..24b4f3c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,7 +3,8 @@ name: build on: push: branches: [main] - tags: ["v*"] + # v* = SatComp (and the whole-suite bundle release); -v* = one sibling plug-in on its own release page + tags: ["v*", "satxcomp-v*", "satlim-v*", "sateq-v*"] pull_request: workflow_dispatch: @@ -22,18 +23,51 @@ jobs: working-directory: rust run: cargo test --locked + # which plug-ins this run bundles: a plain v* tag (and branch / PR builds) = every plug-in that exists in the workspace, + # a -v* tag = just that plug-in + plan: + runs-on: ubuntu-latest + outputs: + plugins: ${{ steps.p.outputs.plugins }} + steps: + - uses: actions/checkout@v4 + - id: p + shell: bash + run: | + ref="${GITHUB_REF_NAME}" + case "$ref" in + satxcomp-v*) list='["satxcomp"]' ;; + satlim-v*) list='["satlim"]' ;; + sateq-v*) list='["sateq"]' ;; + *) + list='["satcomp"' + [ -d rust/satxcomp-plugin ] && list="$list,\"satxcomp\"" + [ -d rust/satlim-plugin ] && list="$list,\"satlim\"" + [ -d rust/sateq-plugin ] && list="$list,\"sateq\"" + list="$list]" + ;; + esac + echo "plugins=$list" >> "$GITHUB_OUTPUT" + echo "bundling: $list" + bundle: - needs: test + needs: [test, plan] strategy: fail-fast: false matrix: + plugin: ${{ fromJson(needs.plan.outputs.plugins) }} + os: [macos-latest, windows-latest, ubuntu-22.04] include: - os: macos-latest name: macOS-universal - cmd: cargo xtask bundle-universal satcomp --release + sub: bundle-universal - os: windows-latest name: Windows-x64 - cmd: cargo xtask bundle satcomp --release + sub: bundle + # built on 22.04 so it also runs on older distributions (glibc 2.35); experimental until someone confirms it + - os: ubuntu-22.04 + name: Linux-x64 + sub: bundle runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 @@ -43,23 +77,45 @@ jobs: - uses: Swatinem/rust-cache@v2 with: workspaces: rust + - name: Linux build deps (baseview / egui) + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y libx11-xcb-dev libxcb-icccm4-dev libxcb-dri2-0-dev libgl1-mesa-dev libx11-dev libxcursor-dev libasound2-dev - name: Bundle working-directory: rust - run: ${{ matrix.cmd }} + run: cargo xtask ${{ matrix.sub }} ${{ matrix.plugin }} --release - name: Package shell: bash run: | - mkdir -p dist + # zip name = --; the plug-in's own version, not the tag + plugin="${{ matrix.plugin }}" + case "$plugin" in satcomp) disp=SatComp ;; satxcomp) disp=SatXComp ;; satlim) disp=SatLim ;; sateq) disp=SatEQ ;; esac + ver=$(grep -m1 '^version' "rust/${plugin}-plugin/Cargo.toml" | sed 's/.*"\(.*\)".*/\1/') + # zip layout mirrors the install folders: VST3/.vst3, CLAP/.clap, INSTALL.txt, LICENSE (+ the manual on the macOS job) + mkdir -p dist/VST3 dist/CLAP cp LICENSE dist/ - cp -R rust/target/bundled/satcomp.vst3 rust/target/bundled/satcomp.clap dist/ - cd dist && 7z a -tzip ../SatComp-${{ github.ref_name }}-${{ matrix.name }}.zip . || zip -r ../SatComp-${{ github.ref_name }}-${{ matrix.name }}.zip . + cp -R "rust/target/bundled/${plugin}.vst3" dist/VST3/ + cp -R "rust/target/bundled/${plugin}.clap" dist/CLAP/ + case "${{ matrix.name }}" in macOS*) os=macOS ;; Linux*) os=Linux ;; *) os=Windows ;; esac + sed -e "s/@PLUGIN@/${plugin}/g" -e "s/@NAME@/${disp}/g" -e "s/@VER@/v${ver}/g" "docs/install/INSTALL-${os}.txt" > dist/INSTALL.txt + if [ "$os" = Linux ]; then + sed -e "s/@PLUGIN@/${plugin}/g" -e "s/@NAME@/${disp}/g" -e "s/@VER@/v${ver}/g" docs/install/install-linux.sh > dist/install.sh + chmod +x dist/install.sh + fi + manual="docs/manual/${disp}-Manual-v${ver}.pdf" + if [ -f "$manual" ]; then + cp "$manual" dist/ + if [ "$os" = macOS ]; then cp "$manual" .; fi + fi + cd dist && 7z a -tzip "../${disp}-v${ver}-${{ matrix.name }}.zip" . || zip -r "../${disp}-v${ver}-${{ matrix.name }}.zip" . - uses: actions/upload-artifact@v4 with: - name: SatComp-${{ matrix.name }} - path: SatComp-*.zip + name: ${{ matrix.plugin }}-${{ matrix.name }} + path: | + *.zip + *.pdf release: - if: startsWith(github.ref, 'refs/tags/v') + if: startsWith(github.ref, 'refs/tags/') needs: bundle runs-on: ubuntu-latest permissions: @@ -72,7 +128,9 @@ jobs: merge-multiple: true - uses: softprops/action-gh-release@v2 with: - files: artifacts/*.zip + files: | + artifacts/*.zip + artifacts/*.pdf # notes come from docs/releases/.md (falls back to generated notes when there is no file) body_path: ${{ hashFiles(format('docs/releases/{0}.md', github.ref_name)) != '' && format('docs/releases/{0}.md', github.ref_name) || '' }} generate_release_notes: ${{ !hashFiles(format('docs/releases/{0}.md', github.ref_name)) }} diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml index 72a231f..b885880 100644 --- a/.github/workflows/release-notes.yml +++ b/.github/workflows/release-notes.yml @@ -1,6 +1,7 @@ name: release-notes # Applies docs/releases/.md as the description of the matching GitHub release (when that release exists). +# Tags: vX.Y.Z (SatComp / the whole-suite bundle), satxcomp-vX.Y.Z, satlim-vX.Y.Z, sateq-vX.Y.Z. on: push: branches: [main] @@ -18,7 +19,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: | - for f in docs/releases/v*.md; do + for f in docs/releases/*.md; do tag=$(basename "$f" .md) if gh release view "$tag" >/dev/null 2>&1; then gh release edit "$tag" --notes-file "$f" diff --git a/.gitignore b/.gitignore index bc22440..b307c7e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,10 @@ __pycache__/ *.png docs/referenceJSFX/ +docs/crashlogs/ +docs/internal/ /Presets/ !docs/screenshot.png +docs/feedbacknotes/ +wavtest/ +screencaps/ \ No newline at end of file diff --git a/Fonts/Anonymous_Pro/OFL.txt b/Fonts/Anonymous_Pro/OFL.txt new file mode 100755 index 0000000..d89cf45 --- /dev/null +++ b/Fonts/Anonymous_Pro/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2009, Mark Simonson (http://www.ms-studio.com, mark@marksimonson.com), +with Reserved Font Name Anonymous Pro. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/Fonts/Courier_Prime/OFL.txt b/Fonts/Courier_Prime/OFL.txt new file mode 100755 index 0000000..7072510 --- /dev/null +++ b/Fonts/Courier_Prime/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2015 The Courier Prime Project Authors (https://github.com/quoteunquoteapps/CourierPrime). + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/Fonts/DM_Mono/OFL.txt b/Fonts/DM_Mono/OFL.txt new file mode 100755 index 0000000..14fde1b --- /dev/null +++ b/Fonts/DM_Mono/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/Fonts/Victor_Mono/OFL.txt b/Fonts/Victor_Mono/OFL.txt new file mode 100755 index 0000000..d14bfcd --- /dev/null +++ b/Fonts/Victor_Mono/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2023 The Victor Mono Project Authors (https://github.com/rubjo/victor-mono-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/Fonts/Victor_Mono/README.txt b/Fonts/Victor_Mono/README.txt new file mode 100755 index 0000000..debb767 --- /dev/null +++ b/Fonts/Victor_Mono/README.txt @@ -0,0 +1,77 @@ +Victor Mono Variable Font +========================= + +This download contains Victor Mono as both variable fonts and static fonts. + +Victor Mono is a variable font with this axis: + wght + +This means all the styles are contained in these files: + Victor_Mono/VictorMono-VariableFont_wght.ttf + Victor_Mono/VictorMono-Italic-VariableFont_wght.ttf + +If your app fully supports variable fonts, you can now pick intermediate styles +that aren’t available as static fonts. Not all apps support variable fonts, and +in those cases you can use the static font files for Victor Mono: + Victor_Mono/static/VictorMono-Thin.ttf + Victor_Mono/static/VictorMono-ExtraLight.ttf + Victor_Mono/static/VictorMono-Light.ttf + Victor_Mono/static/VictorMono-Regular.ttf + Victor_Mono/static/VictorMono-Medium.ttf + Victor_Mono/static/VictorMono-SemiBold.ttf + Victor_Mono/static/VictorMono-Bold.ttf + Victor_Mono/static/VictorMono-ThinItalic.ttf + Victor_Mono/static/VictorMono-ExtraLightItalic.ttf + Victor_Mono/static/VictorMono-LightItalic.ttf + Victor_Mono/static/VictorMono-Italic.ttf + Victor_Mono/static/VictorMono-MediumItalic.ttf + Victor_Mono/static/VictorMono-SemiBoldItalic.ttf + Victor_Mono/static/VictorMono-BoldItalic.ttf + +Get started +----------- + +1. Install the font files you want to use + +2. Use your app's font picker to view the font family and all the +available styles + +Learn more about variable fonts +------------------------------- + + https://developers.google.com/web/fundamentals/design-and-ux/typography/variable-fonts + https://variablefonts.typenetwork.com + https://medium.com/variable-fonts + +In desktop apps + + https://theblog.adobe.com/can-variable-fonts-illustrator-cc + https://helpx.adobe.com/nz/photoshop/using/fonts.html#variable_fonts + +Online + + https://developers.google.com/fonts/docs/getting_started + https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide + https://developer.microsoft.com/en-us/microsoft-edge/testdrive/demos/variable-fonts + +Installing fonts + + MacOS: https://support.apple.com/en-us/HT201749 + Linux: https://www.google.com/search?q=how+to+install+a+font+on+gnu%2Blinux + Windows: https://support.microsoft.com/en-us/help/314960/how-to-install-or-remove-a-font-in-windows + +Android Apps + + https://developers.google.com/fonts/docs/android + https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts + +License +------- +Please read the full license text (OFL.txt) to understand the permissions, +restrictions and requirements for usage, redistribution, and modification. + +You can use them in your products & projects – print or digital, +commercial or otherwise. + +This isn't legal advice, please consider consulting a lawyer and see the full +license for all details. diff --git a/README.md b/README.md index a0dfaba..10e38e5 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,76 @@ # SatComp -A waveshaping saturator with a compressor and a 2-stage 3-band EQ, in a black-and-white monospace UI. Made with bricking intentions. +Three saturator-based dynamics plug-ins in one black-and-white (or any colour you like) monospace UI. Made with bricking intentions. -![SatComp](docs/screenshot.png) +| Plug-in | Version | What | +|---|---|---| +| [**SatComp**](#satcomp) | 0.5.2 | waveshaping saturator, compressor and a 2-stage 3-band EQ | +| [**SatXComp**](#satxcomp) | 0.1.0 | 4-band multiband compressor with a saturator per band and a 5-band EQ | +| [**SatLim**](#satlim) | 0.1.0 | saturator into an oversampled clipper and a true-peak brickwall limiter | + +VST3 and CLAP for macOS (Apple silicon and Intel), Windows and Linux (experimental: see Install). Free, GPL-3.0-or-later. + +## SatComp -VST3 and CLAP for macOS (Apple silicon and Intel) and Windows. Current version: **0.5.1**. +A waveshaping saturator with a compressor and a 2-stage 3-band EQ. Give the compressor more spice to squash. -## Features -- **Saturator:** 15 shapers including a **Custom** one you draw yourself (pencil icon, up to 10 points), drive, bias, HP/LP split, tone, sat mix, output gain, 1x/2x/4x oversampling. +![SatComp](docs/screenshot.png) + +- **Saturator:** 15 shapers including a **Custom** one you draw yourself (pencil icon), drive, bias, ASYM (how much of the even-order part each shaper keeps, so lopsided curves do not drag DC into the signal), HP/LP split, tone, sat mix, SAT GAIN with auto-match, 1x/2x/4x oversampling. - **Sidechain:** external key from a second stereo input, with gain, HP and LP on the key and a SOLO to listen to it. - **Compressor:** threshold, ratio, attack, release, knee and knee shape, peak/RMS detector, low cut, lookahead, feed-forward/feedback blend, GR distortion, makeup and mix. - **EQ:** two stages (pre and post compressor), three bands each plus tilt, with a live spectrum. -- **Metering and tools:** output meter, gain-reduction meter, GAIN MATCH, DELTA monitor, loudness-matched BYPASS. -- **Waveform scope:** click the icon in the corner of the compressor plot for a half or full wave view of the output with the gain reduction stacked on top (transient meter). Drag it to change the time window and the ceiling (+2 dB to -14 dB, so inter-sample overshoots stay visible). +- **Output limiter:** a true-peak brickwall at -0.2 dBTP, on by default (LIM), with about 2 ms of latency that is always reported to the host. +- **Metering and tools:** output meter, gain-reduction meter, post-saturator level meter, GAIN MATCH, DELTA monitor, plain BYPASS. +- **Waveform scope:** click the icon in the corner of the compressor plot for a half or full wave view of the output with the gain reduction stacked on top (transient meter). - **Presets:** save and load your own, step through them, six Drums factory presets included. A name wrapped in asterisks (`*NAME*`) means the preset has been modified. -- **20 colour schemes, each with a light mode, plus your own:** click the icon for the next scheme, double-click it for light/dark, right-click for the list. The **Appearance** tab (About page) has the mode switch, a scheme list with swatches, six fonts and a theme editor with a colour picker; user themes are saved in `~/Library/Application Support/SatComp/themes.json` (`%APPDATA%\SatComp\themes.json` on Windows). -- Resizable window. Double-click any slider to reset it. -Click the title for an About page with the signal flow, the Appearance tab and the changelog. +## SatXComp + +A 4-band compressor with a waveshaping saturator on every band and a 5-band EQ. For surgical baking: split the signal, then drive each band to taste. + +![SatXComp](docs/screenshot-satxcomp.png) + +- **Four bands** (LO, ML, MH, HI) split by three Linkwitz-Riley crossovers, each with a 12, 24, 48 or 96 dB slope. Drag the crossover lines in the spectrum or use the XOV sliders. The bands sum flat. +- **Per band:** a saturator (same 15 shapers, custom curves with a symmetry tool, band-limited so it only adds harmonics inside the band), a compressor, SOLO and DELTA, and its own SAT GAIN auto-match. +- **Compressor modes per band:** DWNWARD (the plain compressor), UPWARD (lifts what is below the threshold, up to RANGE) or UP/DWN (both). +- **Sidechain:** the external key is split across the bands, so it ducks like a dynamic EQ; KEY MIX blends it with the band's own level. +- **Spectrum viewport:** the output over the dry signal. The accent colour shows where the compressor took gain away, its inverse where gain was added. Each band handle sits at the threshold with a bar for the gain reduction below it, the gain increase above it, and the in/out difference on top. +- **EQ:** a 5-band post EQ with notch, bandpass and allpass types, tilt, and a mix control for blending with the dry signal. +- **Output limiter** (true-peak, on by default), waveform scope, delta, plain bypass and four factory presets. + +## SatLim + +A 2-stage clipper/limiter with a waveshaping saturator. When you need to nuke it from orbit. + +![SatLim](docs/screenshot-satlim.png) + +- **Chain:** saturator (x1 to x8 oversampling) into a hard **CLIP** at the ceiling, then a true-peak brickwall limiter, then OUT GAIN. The output gain is after the limiter on purpose. +- **THRESHOLD** is the input level that lands on the ceiling: lowering it chews the signal deeper. **CLIP** exposes and bricks more transients, **RELEASE** trades density against distortion. +- **L.AHEAD** on gives a lookahead true-peak limiter; off gives a zero-latency one that follows sample peaks. The **TRU.PK** readout is an 8x true peak either way. +- **Transient scope** shows the output with what the limiter removed (solid) and what the clipper removed (hatched) stacked on top; the GR meter splits the same way. +- Auto-matched SAT GAIN, DELTA (what the clipper and limiter removed), plain BYPASS and six factory presets. + +## Shared + +- **27 colour schemes, each with a light mode, plus your own:** click the logo for the next scheme, double-click it for light/dark, right-click for the list. The **Preferences** tab (About page) has the mode switch, a scheme list with swatches, 11 fonts, a custom theme editor with a colour picker, and SET AS DEFAULT for new instances. User themes are saved in `~/Library/Application Support/SatComp/themes.json` (`%APPDATA%\SatComp\themes.json` on Windows). +- Resizable window (100% to 250%). Double-click any slider to reset it. Click the title for an About page with the signal flow, Preferences and the changelog. ## Install -Download the zip for your system from the [Releases](../../releases) page and copy the bundles: +Download the zip for your plug-in and system from the [Releases](../../releases) page. Inside are `VST3/` and `CLAP/` folders that mirror the install locations, an `INSTALL.txt` and the plug-in's manual (PDF; the manuals are also in `docs/manual/`). Copy the bundle (`satcomp`, `satxcomp` or `satlim`) to: | | macOS | Windows | |---|---|---| | VST3 | `~/Library/Audio/Plug-Ins/VST3/` | `C:\Program Files\Common Files\VST3\` | | CLAP | `~/Library/Audio/Plug-Ins/CLAP/` | `C:\Program Files\Common Files\CLAP\` | +**Linux (experimental):** unzip and run `bash install.sh`, which copies both formats into the hidden `~/.vst3` and `~/.clap` folders (`--system` for all users). It needs an X11 session. Known issue: the meters and the scope can stutter on some systems. Bug reports are welcome. + Then rescan plug-ins in your DAW. -**macOS:** the build is not notarized. If Gatekeeper blocks it, run `xattr -dr com.apple.quarantine ~/Library/Audio/Plug-Ins/VST3/satcomp.vst3` (and the same for the CLAP bundle). +**macOS:** the builds are not notarized. If Gatekeeper blocks one, run `xattr -dr com.apple.quarantine ~/Library/Audio/Plug-Ins/VST3/satcomp.vst3` (and the same for the other bundles and the CLAP ones). -User presets are saved to `~/Library/Application Support/SatComp/Presets` (macOS) or `%APPDATA%\SatComp\Presets` (Windows). +User presets are saved to `~/Library/Application Support//Presets` (macOS) or `%APPDATA%\\Presets` (Windows). ## Build Requires [Rust](https://rustup.rs). @@ -39,16 +78,16 @@ Requires [Rust](https://rustup.rs). ```bash cd rust cargo test -cargo xtask bundle satcomp --release # this machine's architecture +cargo xtask bundle satcomp --release # or satxcomp, satlim; this machine's architecture cargo xtask bundle-universal satcomp --release # macOS: arm64 + x86_64 ``` -Bundles land in `rust/target/bundled/`. GitHub Actions builds the macOS universal and Windows bundles on every push (see `.github/workflows/build.yml`) and attaches them to a release when a `v*` tag is pushed. +Bundles land in `rust/target/bundled/`. GitHub Actions builds the macOS universal and Windows bundles on every push (see `.github/workflows/build.yml`). A `v*` tag releases all the plug-ins together; `satxcomp-v*` and `satlim-v*` tags release one plug-in on its own. ## Repository -- `rust/`: the production plug-in (`satcomp-dsp` engine, `satcomp-plugin` nih-plug shell and egui UI, factory presets in `satcomp-plugin/presets/`). +- `rust/`: the production plug-ins. Shared crates: `satcomp-dsp` (saturator, compressor, EQ and limiter blocks) and `satcomp-ui` (egui toolkit, colour schemes, fonts). One DSP crate plus one nih-plug shell per plug-in (`satcomp-*`, `satxcomp-*`, `satlim-*`); factory presets are in each `*-plugin/presets/`. - `SatComp.jsfx`: the original REAPER JSFX prototype. Archival, frozen at v0.3. -- `docs/`: `FOUNDATION.md` (workflow and gotchas), `PARAMETERS.md` (parameter reference), `HANDOFF.md` (JSFX-era design decisions), `TEST_CHECKLIST.md`. +- `docs/`: `FOUNDATION.md` (workflow and gotchas), `INVENTORY.md` (versions and milestones), `PARAMETERS.md` (parameter reference), `SATLIM.md`, `HANDOFF.md` (JSFX-era design decisions), `TEST_CHECKLIST.md`, and the release notes in `docs/releases/`. ## Credits and license -GPL-3.0-or-later, see `LICENSE`. Built with [nih-plug](https://github.com/robbert-vdh/nih-plug) and [egui](https://github.com/emilk/egui). Typefaces (all SIL OFL 1.1, embedded): [Fira Code](https://github.com/tonsky/FiraCode), JetBrains Mono, Geist Mono, Roboto Mono, Oxygen Mono and Doto; licences are in `Fonts/`. +GPL-3.0-or-later, see `LICENSE`. Built with [nih-plug](https://github.com/robbert-vdh/nih-plug) and [egui](https://github.com/emilk/egui). Typefaces (all SIL OFL 1.1, embedded): [Fira Code](https://github.com/tonsky/FiraCode), JetBrains Mono, Geist Mono, Roboto Mono, Oxygen Mono, Doto, DM Mono, Victor Mono, Anonymous Pro, Inconsolata and Courier Prime; licences are in `Fonts/`. diff --git a/SatComp.jsfx b/SatComp.jsfx index 058687e..1e02094 100644 --- a/SatComp.jsfx +++ b/SatComp.jsfx @@ -1561,7 +1561,7 @@ cell(3, 78, 196, 62, 38, "BIAS"); cell2(4, 5, 10, 240, 62, 38, "HP", "LP"); cell(6, 78, 240, 62, 38, "TONE"); cell(25, 10, 284, 62, 38, "SAT MIX"); -cell_o(27, 78, 284, 62, 38, "OUT GAIN"); // sat module out gain (also draggable on the plot); inverted = a gain stage +cell_o(27, 78, 284, 62, 38, "SAT GAIN"); // sat module out gain (also draggable on the plot); inverted = a gain stage // ---------- COMP cells (or the EQ page's cells). 152,284 = lookahead (replaces the retired stereo link) eq_page ? ( diff --git a/docs/FOUNDATION.md b/docs/FOUNDATION.md index 3431b0d..6464a3e 100644 --- a/docs/FOUNDATION.md +++ b/docs/FOUNDATION.md @@ -28,7 +28,7 @@ scale exist only in the plug-in; the **Custom waveshaper** (shaper 14, pencil dr ## Colour schemes `docs/colorthemesV2.svg` (+ `.png`) is the design source (dark swatches on the left, light on the right, 20 rows); `docs/colorscheme.md` -is its text export, now **edited by hand by the owner** (e.g. Sonar BG #000000) and the source of truth; `PALETTES` in `gui/canvas.rs` is `(name, dark, light)` generated from it by `tools/gen_palettes.py`. Row names came from the owner's layer list; the second +is its text export, now **edited by hand by the owner** (e.g. Sonar BG #000000) and the source of truth; `PALETTES` in `satcomp-ui/src/canvas.rs` is `(name, dark, light)` generated from it by `tools/gen_palettes.py`. Row names came from the owner's layer list; the second "Magenta" row (purple #240132) is called **Midnight** here (its pre-0.5 name) to keep names unique. **Check with the owner.** Persisted as `palette-v2` (index into this table, default -1) + `light-mode` (bool). The legacy `palette` index (pre-0.5 table order) is migrated once in `ui::initial_palette` (old White = Mono light; old Bananas/Apricot/Berry/Matcha were light-BG schemes). Only append new schemes. @@ -49,18 +49,75 @@ scheme menu (right-click the icon). Not verified in REAPER (clicks go through th | Path | What | |---|---| | `SatComp.jsfx` | prototype, v0.3 | -| `docs/` | this file, HANDOFF, PARAMETERS, TEST_CHECKLIST, colorscheme, SatComp_spec | +| `docs/` | this file, HANDOFF, PARAMETERS, TEST_CHECKLIST, colorscheme (`docs/internal/`, `docs/crashlogs/` and `docs/feedbacknotes/` are the owner's working files, not tracked) | | `proto/` | numpy reference scripts | -| `rust/satcomp-dsp` | DSP engine + tests. `Engine::begin_block(n)` = JSFX `@block`, `tick` = `@sample` | -| `rust/satcomp-plugin` | nih-plug shell (`lib.rs`), generated `params.rs`, `presets.rs`, `gui/{canvas,ui,mod}.rs`, `presets/*.json` (factory bank) | +| `rust/satcomp-dsp` | DSP blocks + the SatComp engine + tests. `Engine::begin_block(n)` = JSFX `@block`, `tick` = `@sample` (see Architecture) | +| `rust/satcomp-ui` | shared egui toolkit: `canvas` (drawing, 20 palettes, font list), `kit` (`Kit` interaction state + `Widgets` trait), `fft`, `init_ctx` + the embedded fonts in `assets/fonts/` | +| `rust/satcomp-plugin` | nih-plug shell (`lib.rs`), generated `params.rs`, `presets.rs`, `gui/{ui,mod,golden}.rs` + `gui/ui/{scope,theme}.rs` (the SatComp pages), `presets/*.json` (factory bank) | +| `rust/satxcomp-dsp` / `rust/satxcomp-plugin` | SatXComp (4-band multiband): `XEngine`, crossover, strips; shell + generated `params.rs` (`tools/gen_xparams.py`) + editor | +| `rust/satlim-dsp` / `rust/satlim-plugin` | SatLim: `LimEngine` (sat -> clip -> true-peak limiter -> out gain); shell + generated `params.rs` (`tools/gen_lparams.py`); presets `*.satlim` | | `rust/vendor/nih_plug_egui` | patched copy (see below) | | `rust/xtask` | `cargo xtask bundle satcomp --release` | | `rust/tools/gen_params.py` | generates `params.rs` | +| `rust/tools/gen_xparams.py` / `gen_lparams.py` | generate the SatXComp / SatLim `params.rs` | +| `rust/tools/wavdiff.py` | null-test two WAV renders (peak/RMS of the difference); see Regression nets | +| `rust/tools/gen_palettes.py` | rewrites `PALETTES` in `satcomp-ui/src/canvas.rs` from `docs/colorscheme.md` | + +## Architecture (0.5.2): blocks, then products + +The engine is built from reusable blocks in `satcomp-dsp`; `Engine` (the SatComp product) only wires them and owns the output +stage, the two level-match state machines and the meters the UI reads. Blocks are stereo, f64, allocation-free in the audio path. + +| Block | File | Does | +|---|---|---| +| `Saturator` | `saturator.rs` | HP/LP split, shaper LUT + 1x/2x/4x oversampling, DC block, tone, mix, SAT OUT; reports latency and its output level | +| `Compressor` | `compressor.rs` | detector (peak/RMS, low cut, FF>FB, external key + KEY MIX), `GainComputer`, ballistics, auto release, GR distortion; the detector listens to one signal and the gain is applied to another (lookahead is the caller's) | +| `KeyInput` | `keyinput.rs` | external key gain > HP > LP > delay aligned with the saturator latency | +| `EqSection` | `eq.rs` | one 5-filter stage (`EqBank`) with a smoothed enable crossfade and output gain | +| `Delay` / `StereoDelay` | `delay.rs` | const-generic power-of-two ring; `advance()` every sample, `put()` optionally, `tap(d)` | +| helpers | `level.rs` | `one_pole`, `ms_step`, `Matcher` (3 s average), dB constants | + +Parameter slices: `Params` stays the flat SatComp parameter set (the UI and plug-in use it); `Params::sat()` / `Params::comp()` give +the per-block `SatParams` / `CompParams`. A new product builds its own block params directly. `Engine` keeps its public fields +(meters, match, scope, tap) as a facade and mirrors a few block meters (`sms`, `sat_blk`) per tick. +SatXComp = a crossover + 3 x (Saturator -> Compressor) + `EqSection`s; SatEQ = EQ bands with `Saturator` in series or parallel +(dynamic EQ would use `Compressor`'s detector and `GainComputer` without its gain stage). Plan: all three live in this repo. + +UI: `satcomp-ui::kit::Widgets` provides `cell`, `cell2`, `cell_o`, `btn`, `sqind`, `sq_tog` and slot addressing; the plug-in's per-frame +`Gui` implements it (slot -> `ParamPtr`, value text, host context, edit mask) and `State` derefs to `Kit`, so page code reads +`self.mx` / `self.press` as before. **Not yet shared** (still in `satcomp-plugin/src/gui/`): menus, About/Appearance pages, theme editor, +preset bar and `presets.rs`, scope, resize grip. They only need the param table, `Shared` and the persisted settings, so they move +the same way when SatXComp needs them. + +## Regression nets (added 0.5.2), run before and after any refactor + +- **Audio golden** (`satcomp-dsp/tests/golden.rs`, scenarios in `tests/golden/scen.rs`, fixture `golden.txt`): 101 scenarios (all shapers x + oversampling, comp/EQ/sidechain/bypass/delta/match variants, ragged blocks, `tick` API, automation, other sample rates), audio and + meter telemetry hashed bit-exactly (tolerance 1e-9 on rms/peak where the platform libm differs). The fixture was recorded from the + **v0.5.1 tag**. `cargo run --release -p satcomp-dsp --example golden -- render ` writes the audio (.f32) and telemetry per scenario; + `-- diff ` reports max |diff| and differing samples. To compare against a release: `git archive rust/satcomp-dsp | tar -x -C `, + copy `tests/golden/scen.rs` and `examples/golden.rs` in (they only use the public `Engine`/`Params` API), render both, diff. + Re-record (`-- record`) only when the sound is *meant* to change, and say so in the commit. + **Limiter note (0.5.2):** the fixture was re-recorded when the output limiter arrived, because it adds a constant delay (reported PDC) + even when off. The change was verified first: baseline renders from HEAD~ vs the new build, `-- diff ` with the shift = + that rate's limiter latency (104 samples at 48 kHz, 98 at 44.1 kHz, 176 at 96 kHz, 65 at 22.05 kHz). Everything is bit-identical except + the first ~120 ms of delta / sidechain-solo and the bypass level tracking, whose *control* timing now runs 2 ms ahead of the audio. + `Params::default()` has `lim_on: false` (the plug-in's own default is on), so bare-engine scenarios do not limit. +- **UI golden** (`satcomp-plugin/src/gui/golden.rs`, fixture `golden.txt`): runs the real frame function headless against a fake host, + scripts 460 frames of mouse input and hashes each frame's draw commands plus the host parameter writes. Meters and the spectrum tap + get deterministic fake telemetry. Limits: nih-plug keeps parameter setters crate-private, so values are not echoed back (params stay at + defaults) and the scope ring is not fed. The header version is fixed under `cfg(test)`. `UI_GOLDEN_OUT= cargo test --release -p satcomp ui_` + writes the hashes instead of comparing (use it to record, or to diff a baseline checkout against the working tree). + An intended UI change (text, layout) legitimately changes frames: diff the label lists, check only the expected frames moved, then re-record. +- **In-host null test between releases** (what the owner does in REAPER): render a loop with the old version installed (offline render, 32-bit float, + no dither, same project/preset), install the new bundle, render again, then `python3 rust/tools/wavdiff.py old.wav new.wav` (expect IDENTICAL, + or at most about -140 dBFS of rounding noise). A refactor-only release should pass; anything louder means the sound changed. +- Both nets: do the baseline in a separate `CARGO_TARGET_DIR` (Dropbox syncs `rust/target`). ## Commands (from `rust/`) ``` -cargo test # DSP + preset tests +cargo test # DSP unit tests, audio golden, UI golden, preset tests cargo run --release -p satcomp-dsp --example bench # DSP CPU per config (0.5.1: all under 1% of one core at 48 kHz) cargo xtask bundle satcomp --release # target/bundled/satcomp.vst3 + .clap cargo xtask bundle-universal satcomp --release # macOS arm64 + x86_64 (needs both rustup targets) @@ -78,6 +135,17 @@ Install for REAPER: copy the bundles to `~/Library/Audio/Plug-Ins/VST3/` and `.. - Windows: cannot be built here. `.github/workflows/build.yml` builds macOS universal + Windows x64 on push, and on a `v*` tag zips both and attaches them to a GitHub release. **The Windows build and the first CI run are untested**; check them (and load the DLL bundle in a Windows DAW) before announcing it. +- **Release convention (from 0.5.1):** write `docs/releases/.md` first (fixed / new / notes / compare link), update the in-plugin + `CHANGELOG`, README, this file and `docs/screenshot.png`, bump the crate versions, push `main`, then push the annotated tag. + The release job uses that file as the release body; `.github/workflows/release-notes.yml` re-applies the files to existing + releases when they change (or via manual dispatch). Verify the release page (assets and description) afterwards. +- **Several plug-ins, one repo (decided 2026-11-11):** each plug-in has its own version in its `rust/-plugin/Cargo.toml` + (SatComp 0.5.x, SatXComp and SatEQ start at 0.1.0). Tags: `vX.Y.Z` = SatComp and the **whole-suite bundle** (builds every plug-in that + exists; the release page lists all zips, which are named with each plug-in's own version, e.g. `SatXComp-v0.1.0-macOS-universal.zip`); + `satxcomp-vX.Y.Z` / `sateq-vX.Y.Z` = just that plug-in on its own release page, so a sibling fix never forces a SatComp version bump. + The first release (`v0.5.2`) is the bundle of all three. Notes for a plug-in tag live in `docs/releases/.md`; a bundle's notes + carry a table (plug-in, version, changed or unchanged). The `plan` job in `build.yml` maps tag -> plug-ins; matrix = plug-in x (macOS universal, Windows x64). + A framework change (`satcomp-dsp`, `satcomp-ui`) only needs a release of the plug-ins whose audio/UI golden moved. - Docs for users: `README.md`. `LICENSE` is GPL-3.0 (copied from the nih-plug checkout, the standard FSF text). ## Identity (never change after release) @@ -106,7 +174,7 @@ The JSFX `desc:` is also identity (still `SatComp`; ask before changing). - Meters: audio thread `fetch_max`, UI `swap(0)`. - **Vendored `nih_plug_egui`** has two patches: `EguiState::set_requested_size` is `pub` (aspect-locked resize), and `queue.resize` gets physical pixels (Retina resize bug). Re-apply if the crate is ever updated (`vendor/README.md`). -- egui draws text lower than REAPER does: `TEXT_LIFT_EM` (0.28) and `FONT_SCALE` (0.86) in `canvas.rs` were measured +- egui draws text lower than REAPER does: `TEXT_LIFT_EM` (0.28) and `FONT_SCALE` (0.86) in `satcomp-ui/src/canvas.rs` were measured from side-by-side screenshots. Re-check them if the font or the JSFX sizes change. - Layout is the JSFX grid (560x336 logical units, 25% scale steps); text and lines snap to device pixels. Default window 700x420 (125%), min 100%, max 250%, corner grip + scale button. @@ -115,7 +183,7 @@ The JSFX `desc:` is also identity (still `SatComp`; ask before changing). File dialogs (`rfd`) block the UI and are untested inside REAPER (macOS) and on Windows. - Dropbox syncs `rust/target/`: move it out (`CARGO_TARGET_DIR`) or mark it ignored. - **Windows builds must come from a Windows machine** (GitHub Actions `windows-latest`); no cross-compile. Not set up yet. -- GPL is fine for this project; `nih_plug_egui` is ISC, the six UI fonts are OFL (keep the licences with any distribution; sources and licences in `Fonts/`, only the embedded TTFs under `satcomp-plugin/assets/fonts/` are built in). +- GPL is fine for this project; `nih_plug_egui` is ISC, the six UI fonts are OFL (keep the licences with any distribution; sources and licences in `Fonts/`, only the embedded TTFs under `satcomp-ui/assets/fonts/` are built in). ## Custom waveshaper (v0.4) - Shaper 14 = a user curve: <=10 points (x=-1 and x=+1 fixed in x, y editable, up to 8 interior), monotone cubic @@ -130,7 +198,7 @@ The JSFX `desc:` is also identity (still `SatComp`; ask before changing). ## Header, About page, preset marker (v0.4) - Version: the header and About page read `CARGO_PKG_VERSION` (`version_short()` in `gui/ui.rs`), so bumping the crate - version is the only edit. Both crates are 0.5.1. + version is the only edit. All three crates (`satcomp-dsp`, `satcomp-ui`, `satcomp-plugin`) are 0.5.2. - Clicking the title toggles the About page (`State.about`: 0 closed, 1 about, 2 changelog, 3 appearance). It replaces the tab row, viz row and cells; the header, meter and right column stay live. Copy lives in `ABOUT_TEXT` / `CHANGELOG` (source text: `docs/abouttextcopy.md`). Changelog entries: newest first, one short sentence per bullet, no em dashes. About and Changelog text live in a row-based scroll box (`scroll_rows`: wheel = 3 rows, draggable thumb on the right, rows culled whole since the canvas has no clipping); scroll position resets on tab change. @@ -159,7 +227,7 @@ The JSFX `desc:` is also identity (still `SatComp`; ask before changing). is ~2% and the GL buffer swap is most of the rest. Many open editors at once are untested (see Open / next). ## Sidechain (v0.5) -- Spec in `PARAMETERS.md` (SIDECHAIN). Params 63-66 (`sc_on` is excluded from presets); layouts = stereo + aux "Sidechain", +- Spec in `PARAMETERS.md` (SIDECHAIN). Params 63-66 (`sc_on` is an OPTIONAL preset value: saved, applied only if the preset carries it); layouts = stereo + aux "Sidechain", then plain stereo (`lib.rs`). Engine: `process_sc(l, r, Option<(&[f32], &[f32])>)`; `None` = no bus = internal detector. `tick_sc` / `sc_solo` / `mn_lv` in `satcomp-dsp/src/engine.rs`; tests `sidechain_*`. - Solo (`Shared.sc_solo`) and the red-button hint (`Shared.sc_bus`, optimistic true until the first block) are UI atomics. @@ -168,12 +236,11 @@ The JSFX `desc:` is also identity (still `SatComp`; ask before changing). ## Open / next - **Multi-instance GUI load (deferred from 0.5.1):** with several editors open the GL swaps at 60 fps add up. Test in a real session first; likely fix = repaint ~20 fps when idle (no signal, no mouse) and 60 fps otherwise, possibly pause when the - window is not visible. Also unmeasured: Windows, AU (clap-wrapper, idea for 0.5.2). + window is not visible. Also unmeasured: Windows. - ~~Next session, idea 1: sidechain.~~ Done in 0.5 (see above); original brief: Add a second stereo input (nih-plug aux input) that feeds the detector, whole band, with HP/LP filters to taper it. Needs: audio layout change (main 2in/2out + aux 2in), an engine detector source switch, params (sidechain on, SC HP, SC LP) appended to `gen_params.py`, a UI home for them, and a listen/monitor option. -- **Next session, idea 2: SatXComp**, a 3-band multiband compressor with the saturator. Likely a separate repo that forks - the `satcomp-dsp` crate, the egui canvas/UI toolkit, preset system and CI from here. +- **SatXComp** (3-band multiband, UI draft `docs/satxcompdraft1.png`) and **SatEQ** (5-band EQ with the waveshaper, series/parallel, later dynamic EQ) are planned as sibling plug-ins **in this repo/workspace** (decided 2026-11-10): new `satxcomp-plugin` / `sateq-plugin` crates on the shared blocks and `satcomp-ui`, own VST3/CLAP ids and preset folders, per-product tag prefixes. See Architecture for what is already shared. - Owner heard a click while drawing/switching shapers and when the plug-in window regains focus. Fixed what is identifiable (table morph on shape/curve change, no allocation in `Curve::from_points` on the audio thread); **the focus-regain click is unconfirmed**: retest, and if it persists look at the UI/host param traffic on focus. @@ -181,4 +248,4 @@ The JSFX `desc:` is also identity (still `SatComp`; ask before changing). `smoothing = false`). - Owner supplies hand-tuned presets for `rust/satcomp-plugin/presets/`. - **Resize grip is still broken** (drag causes a stutter/scaling loop; two fix attempts, last = `80cd756`). Use the size dropdown (right-click grip). Revisit: commit-on-release with a ghost outline is the fallback design. File dialogs still need an owner test in REAPER. `clap-validator`, GitHub repo + CI (mac + Windows), signing/notarization. -- Not done: preset rename/delete, AU via clap-wrapper. +- Not done: preset rename/delete. AU (clap-wrapper) is shelved indefinitely (owner decision 2026-11-10, no demand). diff --git a/docs/INVENTORY.md b/docs/INVENTORY.md new file mode 100644 index 0000000..ab0bf8a --- /dev/null +++ b/docs/INVENTORY.md @@ -0,0 +1,78 @@ +# Inventory + +Internal record of what exists, at which version, and when it got there. Update it with every release (the checklist is at the bottom). Dates are commit dates; tags are on `main`. + +## Plug-ins + +| | SatComp | SatXComp | SatLim | +|---|---|---|---| +| Version | 0.5.2 | 0.1.0 | 0.1.0 | +| Crates | `satcomp-dsp` (shared blocks), `satcomp-plugin` | `satxcomp-dsp`, `satxcomp-plugin` | `satlim-dsp`, `satlim-plugin` | +| Chain | saturator, compressor, two 3-band EQ stages (pre / post compressor) + tilt, sidechain, output limiter | 4-band split > per band sat > comp > comp mix/gain, 5-band post EQ, limiter, sidechain | sat (x1-x8) > clip > true-peak limiter > out gain | +| VST3 class id | `TrtSatCompPlugin` | `thomchantraSatXC` | `thomchantraSatLm` | +| CLAP id | `com.trirat.satcomp` | `com.thomchantra.satxcomp` | `com.thomchantra.satlim` | +| Bundle names | `satcomp.vst3` / `.clap` | `satxcomp.vst3` / `.clap` | `satlim.vst3` / `.clap` | +| Preset extension / folder | `.satcomp`, `SatComp/Presets` | `.satxcomp`, `SatXComp/Presets` | `.satlim`, `SatLim/Presets` | +| Factory presets | 6 (Drums_*) | 4 | 6 | +| Window (logical, base) | 560 x 336 | 664 x 400 | 340 x 496 | +| Latency | constant ~2.2 ms at 48 kHz, reported | constant, reported | saturator + clipper oversamplers + lookahead, reported; changes with x1-x8 and L.AHEAD | +| Docs | `PARAMETERS.md` (JSFX era), `FOUNDATION.md` | `FOUNDATION.md` | `SATLIM.md` | + +Shared: `satcomp-ui` (canvas, 27 palettes, 11 embedded fonts, FFT, widget kit, About / Preferences / Changelog pages), `themes.json` and `defaults*.json` under `SatComp/` in the user's application-support folder. Parameter ids never change once released (presets, projects and automation depend on them). + +**Platforms:** macOS (universal), Windows x64 and Linux x64 (experimental from 0.5.2: X11 only, built on ubuntu-22.04; known issue: the meters and the scope stutter on some systems, probably frame pacing under X11; `SATCOMP_FPS=1` and `SATCOMP_VSYNC=0|1` help diagnose it). + +**Not built:** SatEQ (5-band EQ with a waveshaper per band) exists only as a pitch, `docs/internal/SATEQ_PITCH.md`. The CI matrix knows the `sateq-v*` tag but there is no crate. AU is shelved (no demand yet). + +## Release and tag convention +- `v*` tag: bundle release of everything that changed (0.5.2 is the first bundle). `satxcomp-v*`, `satlim-v*`, `sateq-v*`: a single plug-in on its own. +- Zip name = `-v-.zip`, not the tag's version. +- Manuals: `docs/manual/.md` is the source, `python3 docs/manual/build.py` writes `-Manual-v.pdf` (committed; CI attaches it to the release and puts it in the zips). Rebuild it whenever the plug-in version changes. +- Zip layout: `VST3/.vst3`, `CLAP/.clap`, `INSTALL.txt` (from `docs/install/`), `LICENSE`, the manual. +- Notes file `docs/releases/.md` before tagging (the release workflow uses it as the body); verify the release through the API afterwards. See `FOUNDATION.md`. + +## Version history + +### SatComp +| Version | Date | Milestone | +|---|---|---| +| JSFX v0.1 | 2026-11-08 | first prototype: saturator + compressor + gain diff, custom monospace UI (`SatComp.jsfx`) | +| JSFX v0.2 | 2026-11-08/09 | grid UI, bypass, meters, delta monitor, Sat Mix, Sat Out, 14 shapers | +| JSFX v0.3 | 2026-11-09 | two 3-band EQ stages + tilt, lookahead, GAIN MATCH. Last JSFX; archival | +| v0.4 / v0.4.1 | 2026-11-09 | rebuilt in Rust as VST3 + CLAP, presets, resize, custom waveshaper, 20 schemes; CI for macOS universal + Windows; v0.4.1 fixes the PK readout | +| v0.5.0 | 2026-11-09 | sidechain input, light mode for every scheme, scrolling About | +| v0.5.1 | 2026-11-10 | fixed the enable/refocus thump; Appearance tab, custom themes, waveform scope | +| v0.5.2 | 2026-11-13 | engine rebuilt from blocks (bit-identical audio), shared UI crate, true-peak output limiter, post-sat meter, ASYM, SAT GAIN, plain bypass, 27 schemes, 11 fonts, per-plug-in defaults | + +### SatXComp +| Version | Date | Milestone | +|---|---|---| +| (design) | 2026-11-10 | started as a 3-band multiband version of SatComp; `satxcomp-dsp` crossover | +| 0.1.0 | 2026-11-13 | frozen with 0.5.2: four bands, 12/24/48/96 dB crossovers, band-limited saturator, DWNWARD / UPWARD / UP/DWN compressor, per-band sidechain key, 5-band EQ, limiter, scope, gain-reduction and gain-increase view in the spectrum, 4 factory presets | + +### SatLim +| Version | Date | Milestone | +|---|---|---| +| 0.1.0 | 2026-11-13 | frozen with 0.5.2: the SatComp saturator into an oversampled clipper and true-peak limiter with transient scope, 8x TRU.PK readout, 6 factory presets | + +## Key milestones (project timeline) +| Date | Event | +|---|---| +| 2026-11-08 | repository starts with the SatComp JSFX prototype | +| 2026-11-09 | Rust rebuild (v0.4), first GitHub releases v0.4.1 and v0.5.0 | +| 2026-11-10 | v0.5.1 released; the two regression nets recorded (101-scenario audio golden, 460-frame UI golden); engine split into blocks | +| 2026-11-11 | output limiter; one-bundle release scheme and per-plug-in tags | +| 2026-11-12 | ASYM saturator; SatLim built (8x detector, scope, presets) | +| 2026-11-13 | feature freeze for 0.5.2: SatXComp upward compression and lift bars, plain bypass, theme gain colours, About and changelog copy, README and screenshots | + +## Regression nets +- **DSP golden** (`satcomp-dsp`): 101 scenarios rendered bit-exact against the v0.5.1 recording, audio and meter values. Re-recorded for the limiter latency and for the plain bypass in 0.5.2; the bypass scenario is the only audio change. +- **UI golden** (`satcomp-plugin/src/gui/golden.txt`): scripted frames hashed. Re-record only when a screen deliberately changes, and check that only those frames moved. +- Other tests live beside the code; `cargo test --workspace` runs all of them (pluginval strictness 5 passes for the bundles). + +## Release checklist +1. Version bump in the `Cargo.toml` of each plug-in that changed (the header, About and the zip name follow it); changelog entry in the plug-in's `CHANGELOG`. +2. `cargo test --workspace`; re-record goldens only for intended changes. +3. About copy (`docs/abouttextcopy.md`) and README updated; screenshots re-shot if the UI changed. +4. `docs/releases/.md` written; this file updated (versions, history, milestones). +5. Tag on `main`, let CI build, verify the release assets and body through the API. diff --git a/docs/PARAMETERS.md b/docs/PARAMETERS.md index 9f46fac..01d5f2d 100644 --- a/docs/PARAMETERS.md +++ b/docs/PARAMETERS.md @@ -13,7 +13,7 @@ in ──┬────────────────────── │ ├─ SAT MIX ─ + residual ─ cL └─ residual (outside HP/LP band) ───────────────── delayed ───────────┘ (clean band leg ↗) cL ─ SAT OUT (sat module master, always applied) ─ [EQ PRE] ─ [detector: FF/FB → DET HP → PEAK/RMS → LINK] ─ gain computer ─ attack/release ─ gain ─ GR DIST ─ MAKEUP - ─ MIX (vs dry) ─ [EQ POST] ─ OUT GAIN (+ auto/match trim) ─ BYPASS (equal-loudness dry) ─ out + ─ MIX (vs dry) ─ [EQ POST] ─ OUT GAIN (+ auto/match trim) ─ BYPASS (plain dry) ─ out ``` Everything between "SAT" and "MAKEUP" is skipped for sat when `Drive = 0 && Bias = 0` (see Drive). @@ -27,6 +27,7 @@ Everything between "SAT" and "MAKEUP" is skipped for sat when `Drive = 0 && Bias | **Shape** | 14 shapers, Tube | Selects the waveshaper (LUT over ±8, rebuilt on change). **Classic:** Tube = asymmetric tanh (even+odd), Soft = tanh, Rational/Atan = softer knees, Hard = clip with rounded knee at 0.9, Crossover = dead-zone, Cheby = T1+T2+T3. **Folds:** Tri Fold, Sine Fold, Asym Fold (sine fold with an offset, so it folds harder on one side → even+odd harmonics). **Aggressive:** Wrap (modulo wraparound into ±1, hard discontinuities, very aliasy — use OS x4), Rectify (positive half unchanged, negative half flipped at ½ gain → octave-up/even harmonics, DC blocked), Bitcrush (8 steps per unit ≈ 4-bit staircase, clipped ±1), Diode (exponential knee, +1/−0.6 asymmetric). All have unity small-signal slope except Crossover (unity large-signal), Rectify (mixed: 1 on the positive half, ½ flipped on the negative) and Bitcrush (stepped). **Periodic shapers** (Tri/Sine/Asym Fold, Wrap) are range-reduced instead of clamped, so they keep folding at any Drive. UI: arrows step (wrap), click name = dropdown, wheel steps. | | **Drive** | 0–100 %, 25 | Pre-shaper gain, `10^(0.018·drive)` → 0…+36 dB (25 % = +4.5 dB). It is *gain into the shaper*, not a wet/dry amount. **AUDIT:** `sat_on = Drive > 0 \|\| Bias ≠ 0`; at Drive 0 and Bias 0 the whole sat stage is bypassed (not a unity-gain shaper), so the Drive 0 null test passes by construction. | | **Bias** | −100…+100 %, 0 | DC offset added to the signal *after* drive, before the shaper (`x·pre + bias/100`). Skews the curve → even harmonics. A 5 Hz one-pole DC blocker follows the shaper so no DC leaks out. | +| **ASYM** *(0.5.2, under BIAS in the saturator column; not a host parameter)* | 0–100 %, **100**, stored per shaper | Splits the shaper into its odd and even parts, `f(x) = odd + even`. Output = odd + ASYM × (even **high-passed at 25 Hz**, 2nd order). The even part is the only source of DC and of slow envelope-following pulses (kick-shaped sub-audio wobble) when a curve is lopsided; those are removed at any ASYM, and the audible even-order colour above 25 Hz scales with ASYM (0 % = odd only). The even part runs through the same oversampling filters as the shaper, so it is sample-aligned. **Stored in the project and in presets** (15 values, absent = all 100 %); the transfer plot shows the curve as heard. The 5 Hz DC blocker after the shaper stays (bias offset). | | **HP / LP** (Sat HP/LP) | 20 Hz–2 kHz / 200 Hz–20 kHz (was 1 kHz until v0.5), OFF at extremes | Band-limit what feeds the shaper (2nd-order Butterworth, 12 dB/oct). The part *outside* the band (`in − band`) skips the shaper and is added back clean (delay-matched), so HP 200 Hz = distort only above 200 Hz, lows stay clean. Not a filter on the output. | | **Tone** | 1–20 kHz, OFF | 2nd-order LP on the **shaped band only** (after the shaper + DC block, before Sat Mix). Tames the harmonics; the clean residual is unaffected. | | **OS** | Off / x2 / x4 | Halfband oversampling around the shaper only (comp/filters run at base rate). Reports PDC latency 0 / 24 / 28 samples; the dry path, residual and sat-mix dry leg are delayed by the same amount. | @@ -80,7 +81,7 @@ GR meter (right of the plot): shows max(L,R) GR, with peak-hold line (1 s hold, | **DELTA** | toggle (red when on) | Compressor delta monitor: the output is replaced by what the compressor is removing — comp input minus comp output, taken **before** Makeup (so it includes GR Dist's effect). Silence = no gain reduction. Overrides Bypass, ignores Mix and Out Gain. UI-only (not a saved/automatable parameter) so a project can never reload silent-by-accident; it resets to off when the plug-in is reloaded. 10 ms crossfade. Output meters/PK/RMS read the delta signal while it is on. | | **IN>OUT** | readout | Net loudness change of the whole chain: RMS (0.5 s) of the processed output vs the input, in dB, measured **after** Sat, Comp, Makeup, Mix, Out Gain and Auto/Match trim (and before Bypass/Delta). Holds its last value when the input is below −60 dBFS RMS. Centre-tap bar: grows right = output louder, left = quieter, ±12 dB full scale, tick = 0. **Note:** Auto/Match deliberately use a *separate* pre-Out-Gain measurement (`diff_db` in code); if they used this display value they would chase their own correction. So in Auto the display settles at ≈ your Out Gain setting, in Match at ≈ Out Gain once locked. | | **TRIM** | readout | Match state (`MEAS` / `LOCK`), or `---` when off. | -| **BYPASS** | toggle | Equal-loudness bypass: crossfades (10 ms) from the processed signal to the latency-aligned dry input **scaled to the processed output's RMS** (post Out Gain). The scale (`BYP ±x dB`, clamped ±24 dB, 200 ms smoothing) is held while the input is silent. The effect keeps running while bypassed, so meters/GR stay live and unbypassing is click-free. **AUDIT:** loudness matching is RMS over 0.5 s, so it is a steady-state match; it will not be right instant-to-instant on transient material. | +| **BYPASS** | toggle | Plain bypass: crossfades (10 ms) from the processed signal to the latency-aligned dry input, at the input's own level (v0.5.2: the v0.3-0.5.1 equal-loudness scaling is gone; with a hot saturator and the limiter bypassed too, the matched copy peaked up to +10 dB). The effect keeps running while bypassed, so meters/GR stay live and unbypassing is click-free. | ### Output metering (header + info area) @@ -96,8 +97,8 @@ GR meter (right of the plot): shows max(L,R) GR, with peak-hold line (1 s hold, - **Colour schemes (v0.3):** 10 palettes from `docs/colorscheme.md` (Black, White, Teal, Cadmium, Ultramarine, Azure, Magenta, Sulfur, Uranium, Midnight; each = BG / UI / ACCENT). **Left-click the header logo** = next scheme, **right-click** = dropdown with the current one ticked. Stored with the project as the scheme index (old files stored 0/1 = Black/White, same indices). Sulfur's accent equals its UI colour, so red-style highlights/fills do not stand out there by design of the palette. - **EQ bypass dimming (v0.3):** a bypassed stage dims the 4x3 EQ grid while that stage is viewed; module bypass dims the whole EQ page (viewport + grid). Combines with the global Bypass dim. - **Bypass dimming (v0.3):** while Bypass is on, the shape selector, OS buttons, EQ button, sat plot, comp/EQ viewport and the SAT / COMP / EQ cells draw at 50 % (colours blended toward the background); header, meters, DELTA/BYPASS and the OUT column stay at full strength. Display only. -- **Readouts (v0.3):** the comp viewport metrics (`LVL +00.0 OUT +00.0 GR 00.0dB`) and the OUT info lines (GR, TRIM/LOCK, PK, RMS, BYP: label left, value right-aligned, zero padded, placeholders `-----`) are **snapshotted ~8x/s** (`rd_*`, 0.12 s) so they are readable; meters, bars and the sat-plot SAT figure use the same snapshot cadence for numbers only. IN>OUT, MAKEUP, MIX and OUT GAIN cells are not zero padded. OUT column order: MAKEUP, MIX, OUT GAIN (bottom, inverted). -- **SAT block layout (v0.3):** DRIVE/BIAS, then `HP|LP` stacked in one cell + TONE, then SAT MIX + **OUT GAIN** (= Sat Out, slider 27, same parameter as dragging the plot). The three gain-stage cells (sat OUT GAIN, EQ OUT GAIN, output OUT GAIN) are drawn **inverted** (lit block) so they read as master levels. (black on white / white on black); red accents are unchanged. The choice is stored with the project/preset (`@serialize`), not as an automatable parameter. +- **Readouts (v0.3):** the comp viewport metrics (`LVL +00.0 OUT +00.0 GR 00.0dB`) and the OUT info lines (GR, TRIM/LOCK, PK, RMS: label left, value right-aligned, zero padded, placeholders `-----`) are **snapshotted ~8x/s** (`rd_*`, 0.12 s) so they are readable; meters, bars and the sat-plot SAT figure use the same snapshot cadence for numbers only. IN>OUT, MAKEUP, MIX and OUT GAIN cells are not zero padded. OUT column order: MAKEUP, MIX, OUT GAIN (bottom, inverted). +- **SAT block layout (v0.3):** DRIVE/BIAS, then `HP|LP` stacked in one cell + TONE, then SAT MIX + **SAT GAIN** (= Sat Out, slider 27, same parameter as dragging the plot). The three gain-stage cells (SAT GAIN, EQ OUT GAIN, output OUT GAIN) are drawn **inverted** (lit block) so they read as master levels. (black on white / white on black); red accents are unchanged. The choice is stored with the project/preset (`@serialize`), not as an automatable parameter. - Hidden params (automatable, no on-screen widget): *Match Trim* (slider 24), *Link* (17, reserved) and all EQ sliders (29–58). - **Header (v0.3):** logo (palette), `SATCOMP 0.3`, full-width output meter; tab row: shape selector, `[OFF|x2|x4]` (the OVERSAMPLING label was retired in v0.5), `SIDECHAIN` (v0.5), `EQ` page toggle, `DELTA | BYPASS`. The GR meter opens on its 3 dB range. Preset bar / save icon are deferred to the VST port. - **Comp viewport (v0.3):** drag the **dot** at the threshold knee (x and y both map to Thresh), drag the **square** at the right edge (y → Ratio; hard-knee formula, so with a wide knee the handle can sit slightly off the cursor). Double-click a handle = default. The label shows live `LVL` (detector level), `OUT` (static-curve output at that level) and `GR`. @@ -113,6 +114,7 @@ plug-in; hosts without sidechain support get the plain stereo layout. | **SC HP** *(65)* | 20…2000 Hz, OFF | 2nd-order Butterworth high-pass on the key. | | **SC LP** *(66)* | 200…20k Hz, OFF | 2nd-order Butterworth low-pass on the key. | | **Key Mix** *(67, cell `KEY MIX`)* | 0–100 %, 100 | Stands in for FF>FB while Sidechain is on (same cell). Detector level = (1−m)·main + m·key, blended as **levels** (each source has its own low-cut and peak/RMS state), so 0 % = the normal internal detector, 100 % = key only, in between ducks from both. FF>FB is not applied while Sidechain is on, whatever its value. Stored in presets. | +| **Limiter** *(68, `LIM` button in the output meter row)* | off/on, **on** | True-peak brickwall at a fixed **-0.2 dBTP**, the last stage of the processed path (after Out Gain; Bypass, Delta and Sidechain solo are not limited). Detection is 4x polyphase (2x at 96 kHz-class rates, plain sample peak above 100 kHz) with a 1.5 ms lookahead; release is program dependent (about 30 ms for isolated peaks, up to 300 ms under sustained reduction). Its gain reduction is the `LIM` readout in the output column (the compressor GR number is at the top of the GR meter). **Stored in presets**; a preset without it loads as on. The limiter's delay (1.5 ms + the detector's, about 2.2 ms at 48 kHz) is **always reported to the host, on or off**, so toggling never changes PDC. Gain Match measures before the limiter. | | **SOLO** *(UI only, not a parameter)* | off | Replaces the output with the key as the detector hears it (after gain/HP/LP, before Low Cut and the peak/RMS blend). Clears itself when Sidechain is switched off. | Key path: aux in > SC Gain > SC HP > SC LP > (solo tap) > detector (Low Cut, peak/RMS blend, gain computer). The key is @@ -145,6 +147,7 @@ into COMP. The tab row no longer carries the OVERSAMPLING label (OFF / x2 / x4 s | | | 44–58 | EQ Post (see EQ) | | 59 | Lookahead | 60–62 | EQ Pre / Post / Module bypass | | 63 | Sidechain *(v0.5)* | 64–67 | SC Gain / SC HP / SC LP / Key Mix *(v0.5)* | +| | | 68 | Limiter *(0.5.2, default on)* | New sliders were appended (25–27, 29–58) so existing sessions/automation keep their mapping. Old sessions should sound identical (Sat Mix 100 %, Bypass off, Sat Out 0 dB, Auto off); if REAPER restores missing sliders as 0, re-set Sat Mix to 100 % once. diff --git a/docs/SATLIM.md b/docs/SATLIM.md new file mode 100644 index 0000000..263a55e --- /dev/null +++ b/docs/SATLIM.md @@ -0,0 +1,59 @@ +# SatLim 0.1 + +The SatComp saturator into an oversampled clipper and a true-peak brickwall limiter. Crates: `rust/satlim-dsp` (`LimEngine`), +`rust/satlim-plugin` (nih-plug shell, params from `tools/gen_lparams.py`, editor). VST3 `thomchantraSatLm`, CLAP `com.thomchantra.satlim`, +presets `*.satlim` in `~/Library/Application Support/SatLim/Presets`. + +## Signal chain +`IN > SAT (shared Saturator, x1/x2/x4/x8) > lift by (CEILING - THRESHOLD) > CLIP (oversampled hard clip at the ceiling) > LIMITER > OUT GAIN > OUT` + +- **OUT GAIN is after the limiter, on purpose.** The ceiling is what the limiter holds; the output gain is free (a clipped -0.4 dBTP + can still have inter-sample peaks a downstream converter sees, so the owner pulls the output back). +- **THRESHOLD** is the input level that lands on the ceiling: the signal is lifted by `CEILING - THRESHOLD` dB. Lowering it pushes harder. +- **CLIP** 0-100 %: 0 = off. Otherwise a hard clamp at the ceiling, run at the oversampled rate, driven up to +6 dB into it. With the + clip on the limiter mostly handles inter-sample excess. +- **L.AHEAD** on: 1.5 ms lookahead + 8x interpolated true-peak detection (4x at 96 kHz-class rates, 2x above; the SatComp / SatXComp output limiter runs the same detector at half those) (constant latency, reported). Off: zero limiter latency, the gain + follows the *sample* peak instantly (attack 0), so inter-sample overs can pass. The readout is **TRU.PK** either way (8x true peak of the output, so with L.AHD off it shows the overs that got past; accent only when it clips; GR stays in the UI colour). +- **RELEASE** 15-80 ms: the slow end of the program-dependent release (fast end stays at 15 ms or below). +- **x1..x8** (OVERSAMPL, top of the limiter column) oversample the saturator and the clipper (latency 0 / 24 / 28 / 30 samples each). The limiter's own detection is always + true-peak (L.AHD on). +- **Latency** = saturator oversampler + clipper oversampler + limiter lookahead, always reported; it changes with x1..x8 and L.AHD. +- **Cells** top to bottom: CEILING, THRESHOLD, CLIP, RELEASE, OUT GAIN (SAT GAIN in the sat module). +- **Meters:** segmented sat out (clip block at the top, held 1 s), GR with its value on top, stereo out VU (click the bars to cycle 48 / 24 / 12 / 6 dB, click the top block to reset the clip lamp and the peak readout). +- **SAT readout** (plot corner): click = measure the saturator's loudness change for 3 s, then write the SAT GAIN that cancels it (click again to cancel). +- **Scope:** CEIL runs +10 dB to -14 dB (default +2) so heavy clipping above 0 dBFS stays visible. Columns sit on a fixed grid in absolute time and the read position eases toward the newest bucket, so the picture scrolls steadily instead of flickering with each host block. +- **Clip and limiter side by side:** the scope and the GR meter stack the two removals instead of merging them. Scope bottom to top: output (UI colour), what the limiter removed (solid accent), what the clipper removed (hatched accent: every other column), up to the pre-clip peak. The GR bar is the total, the limiter's part solid from the top and the clipper's hatched right under it; its number is the total. The readouts keep them apart: GR = limiter, CLIP = clipper. They add up, so it does not matter which is larger. +- **SCOPE FILL** (About > Appearance): solid bars (default) or an outline stroke along the peaks, like SatXComp's spectrum fill. +- **DELTA** = what the clipper and limiter removed (pre-clip signal minus limiter output, before OUT GAIN). **BYPASS** = the input at the + same latency. + +## Parameters (slot = UI address; the sat slots are SatComp's) +| slot | id | range | default | +|---|---|---|---| +| 1 | shape | 0-14 | 0 | +| 2 | drive | 0-100 % | 0 | +| 3 | bias | -100-100 % | 0 | +| 4 / 5 | sat_hp / sat_lp | 20-2000 / 200-20000 Hz | 20 / 20000 (off) | +| 6 | tone | 1000-20000 Hz | 20000 (off) | +| 7 | os | 0-3 (x1 x2 x4 x8) | 0 | +| 25 | sat_mix | 0-100 % | 100 | +| 27 | sat_gain | -24-12 dB | 0 | +| 12 | lookahead (L.AHEAD) | on / off | on | +| 8 | ceiling | -24-0 dB | -0.3 | +| 9 | threshold | -30-0 dB | 0 | +| 10 | release | 15-80 ms | 80 | +| 11 | clip | 0-100 % | 0 | +| 22 | out_gain | -24-12 dB | 0 | +| 26 | bypass | on / off | off (never in presets) | + +The custom curve and ASYM per shaper are stored in the project and in presets, like SatComp. + +## Tests +`satlim-dsp`: 8 engine tests (exact delayed copy at x1, latency table, bypass, ceiling held at several modes, OUT GAIN after the ceiling, +clip lightens the limiter, delta, telemetry). `satlim-plugin`: params / presets / identity + 4 headless editor tests +(`gui/smoke.rs`, scripted input against a recording fake host). Limiter additions are tested in `satcomp-dsp` (defaults identical, zero-latency +mode holds the sample ceiling and passes quiet audio bit-exactly, clip off leaves a spike to the gain stage). + +## Not done / known +- The editor is tested headlessly; first-pass screenshots from REAPER came back (`docs/feedbacknotes/satlimpass1.png`) and pass 1 is applied. +- No audio golden for `LimEngine`, no M/S, no sidechain, no auto-release. diff --git a/docs/SatComp_spec.md b/docs/SatComp_spec.md deleted file mode 100644 index 31d4fc4..0000000 --- a/docs/SatComp_spec.md +++ /dev/null @@ -1,157 +0,0 @@ -# SatComp — JSFX spec v0.2 (throwaway) - -Name is settled: **SatComp**. A satellite-uplink look and feel is welcome as a theme (telemetry-style labels, signal/lock indicators), within the visual rules in §6. - -Personal-use REAPER JSFX: pre-drive saturator → characterful compressor, with a gain-diff readout and auto-compensation. Main use: drum chain staple, from subtle tube boost to gritty/punchy. - -Reference only (do NOT copy code): BurnPressor (Flat Madness) for the idea, Michael Gruhn's "Waveshaping Distortion" for the rational shaper `(1+k)x/(1+k|x|)`. Write DSP and UI from scratch, so a later clean-room claim is trivially true. - -File: `SatComp.jsfx` (single file, no @import). Stereo in/out only. - -## 1. Signal flow - -``` -in ──┬──────────────────────────────── dry (delayed by OS latency) ──┐ - └─ [SAT: band-split → LUT shaper (OS x1/x2/x4) → tone LP] → [COMP] → makeup ─┴─ Mix ─ out gain ─ out - ▲ -in RMS ─────────────┐ out RMS (pre out-gain) ────┤ - └──────────── gain diff = out − in ─────────────────────────────┘ -``` - -- Saturation is PRE only. There is no post-drive stage. -- Mix is a single knob, always dry/wet-complementary, never two sliders. -- NO hard clip at the output. -- Gain diff is measured on the signal before out gain (so auto-trim cannot feed back into its own measurement). - -## 2. Parameters - -All params are real `sliderN` (automation/Param list works). Hide them from the default JSFX UI by prefixing names with `-` and draw everything in `@gfx`. - -**SAT** -| param | range | notes | -|---|---|---| -| Shape | list | see §3 | -| Drive | 0–100% | exponential taper into pre-gain, ~0–36 dB | -| Bias | −100–100% | asymmetry → even harmonics; DC blocker after shaper (always on) | -| Sat HP | 20–2000 Hz (Off at min) | band-limits what gets saturated | -| Sat LP | 1k–20k Hz (Off at max) | same | -| Tone | 1k–20k Hz | post-shaper LP, fizz control | -| OS | Off / x2 / x4 | oversampling around shaper, **Off by default** (aliasing is a legitimate crunch texture; x2 suits smooth shapes, x4 suits folds/clip) | - -**COMP** -| param | range | notes | -|---|---|---| -| Thresh | −40–0 dB | | -| Ratio | 1–20, ∞ at max | | -| Attack | 0.05–100 ms | | -| Release | 5 ms–2 s, **Auto at max** | Auto = program-dependent, see §4 | -| Speed | 0–100% (α↔β) | scales all time constants (~0.25x–4x); low = fast reaction | -| Knee | 0–24 dB | | -| Knee Shape | 0–100% | knee curve family, see §4 | -| Detector | 0–100% | peak↔RMS morph | -| Det HP | Off–400 Hz | sidechain HP | -| Link | 0–100% | stereo link, 0 = independent, 100 = full (max/mean blend) | -| FF/FB | 0–100% | feedforward↔feedback detection | -| GR Dist | 0–100% | GR-coupled harmonic distortion in the gain element | - -**OUT** -| param | range | notes | -|---|---|---| -| Makeup | 0–24 dB | manual | -| Mix | 0–100% | latency-compensated dry | -| Out Gain | −24–+12 dB | manual trim | -| GainMatch | Manual / Auto / Match | see §5 | - -## 3. Saturator - -- Shaper is a **lookup table** (e.g. 4096 pts, linear or cubic interpolation) over input range ±8 (folds need headroom). Input = `x * drive_gain + bias`, clamped to the table range. Rebuild the table only when Shape changes (in `@slider`, never in `@gfx`). -- Presets (all normalized to roughly unity small-signal gain so Drive is the only level control): - 1. Tube — asymmetric soft-sat (positive and negative halves with different knees), even-harmonic leaning - 2. Soft — tanh - 3. Rational — `(1+k)x/(1+k|x|)`, the "subtle" one - 4. Atan - 5. Hard — clip with a tiny round-off - 6. Tri Fold — triangle foldback - 7. Sine Fold — `sin(x·π/2·g)`-style fold - 8. Crossover — dead-zone/zero-crossing distortion - 9. Cheby — mix of T2 + T3 (harmonic generator) -- Band-limited saturation, phase-coherent, no crossover: `out = x − bp(x) + shaper(bp(x))`, where `bp` is HP→LP of the saturator band. Drive 0 must null perfectly. -- Gain compensation inside the shaper section is NOT done here. The gain-diff feature is the compensation tool. -- Oversampling: Off / x2 / x4, default Off. x2 = one polyphase halfband stage; x4 = two cascaded halfband stages. No x8 or higher (diminishing returns, too much CPU in JSFX). Report latency with `pdc_delay` / `pdc_bot_ch` / `pdc_top_ch` for the active setting, and delay the dry path by the same amount; changing OS mode must update both together. Latency is 0 when OS is Off. -- Read-only transfer-curve plot in the UI (draw the table with drive/bias applied). No editable curve in v1. - -## 4. Compressor - -Design in the dB domain. All coefficients are srate-independent and recomputed in `@slider`/`@block`. - -- **Detector:** peak↔RMS morph. Detection is on the stereo-linked sidechain (HP filtered). The Link param blends per-channel and linked detection. -- **Gain computer:** threshold, ratio, knee in dB. **Knee Shape** morphs the knee curve family. The curve must stay continuous in value AND slope at both knee edges (C1). Prototype this in numpy first and plot it. Do not use a naive `t^p` as the shape; it breaks slope continuity. -- **Smoothing:** applied to GR in the dB domain with attack/release. All times scale with Speed. -- **Program-dependent release (Auto):** two release stages (fast + slow), blended by signal behavior (e.g. GR depth and/or crest factor), so sustained compression releases slower and transients release fast. Clamp the Auto range so it stays usable on drums. -- **FF/FB:** feedback mode detects from the compressor output (previous-sample, pre-makeup). Blend continuously with feedforward. -- **GR-coupled distortion (GR Dist):** inside the gain element, blend in a small saturating curve on the post-gain signal with amount proportional to the current GR (normalize, e.g. GR/12 dB, clamped). Zero GR = zero added distortion. -- **Not in v1** (note only): level-dependent attack, ratio-vs-GR (vari-mu), lookahead, detector tilt EQ. - -## 5. Gain diff + auto compensation - -- Running RMS of plug input and of pre-out-gain output, window ~400 ms–1 s. Diff in dB, displayed next to Out Gain, with sign. -- **Manual:** display only. -- **Auto:** the Out Gain trim follows `−diff`, heavily smoothed (about 1–2 s), clamped ±12 dB. Gate the update when the input is below about −60 dB so silence doesn't wind it up. -- **Match:** the user presses it, the plug averages the diff over ~3 s of playback, then **freezes** the trim at that value (button shows locked state; pressing again re-measures). -- Out Gain slider is the manual trim ON TOP of Auto/Match. - -## 6. UI (custom @gfx) - -Goals: small footprint (laptop screens), high contrast, tight spacing. Fixed layout at integer scale only (1x, optional 2x via window size), no continuous scaling. - -Visual rules: -- Background solid black. All text and line/stroke elements solid white. Solid red is the only accent color (GR meter, active/locked states). -- No rounded rects anywhere: square corners only, 1px strokes. -- Font: **Fira Code** via `gfx_setfont`. Distribution/fallback is not handled now; if it isn't installed, fall back to a generic monospace (Menlo/Consolas/Courier New). Keep the font name in one constant so it's trivial to swap. -- Satellite-uplink flavor is optional flavor only (e.g. "LOCK" / "SIG" style labels), not extra UI. - -Target window ~ 560×240 at 1x. Three columns: -- **SAT:** Shape selector, transfer plot, Drive/Bias, HP/LP/Tone, OS toggle -- **COMP:** Thresh, Ratio, Attack, Release, Knee, Knee Shape, Detector, Det HP, Link, Speed, FF/FB, GR Dist (compact cells, advanced params can sit in a smaller secondary row) -- **OUT:** standard GR meter (vertical bar, peak hold), gain-diff readout, Makeup, Mix, Out Gain, GainMatch mode (Manual/Auto/Match) - -Polish is the user's job later; build structure, not beauty. - -### Widget kit (write once, reuse) -- Single active-drag id, one hit-test helper, `mouse_cap` edge detection for press/release. -- Vertical drag = change value; **Shift = fine**; **double-click = reset to default**; mouse wheel support. -- Right-click or Ctrl-click: optional, skip for now. -- Widgets: value cell (label + readout + drag), selector (click to cycle or popup via `gfx_showmenu`), toggle, GR meter, diff readout, transfer plot. -- Writing back: set sliderN, call `sliderchange(...)`, and call `slider_automate(...)` on drag so changes record automation (check the current REAPER JSFX docs for exact signature/touch behavior). - -## 7. Gotchas to respect - -- JSFX functions need explicit `instance()`/`local()` declarations or variables leak into globals. -- `@gfx` runs on its own timing; no heavy DSP/table work there. -- Denormals: add a tiny DC offset or `|x| < 1e-30 → 0` in filters and envelopes. -- Recompute filter coefficients on `srate` change, not just on slider change. -- Keep CPU modest: LUT + OS (up to x4) + one compressor must be cheap, because this goes on many drum tracks. Skip the oversampling path entirely when OS is Off. - -## 8. Build order - -1. Skeleton: sliders, passthrough, stereo, `desc`/tags. -2. Compressor core (gain computer, smoothing, link, Det HP) + numpy plot of knee family to settle Knee Shape. -3. Saturator: LUT + presets + band-split + DC block + Tone. Then x2/x4 OS + PDC + dry delay. -4. Program-dependent release, FF/FB, GR Dist. -5. Gain diff + Auto/Match. -6. UI: widget kit → layout → meters → transfer plot. - -## 9. Verification - -No REAPER here, so JSFX can't be run in-session. Do: -- numpy prototypes for the gain computer (continuity checks), shaper tables (normalization, symmetry), and halfband response. -- Careful manual read of JSFX syntax and function scoping. -- Leave a short test checklist for the user in REAPER: drive 0 null test, OS Off/x2/x4 latency alignment with Mix at 50%, Auto stability on silence, automation recording from the custom UI. - -## Defaults decided without asking (change if wrong) -- OS: Off / x2 / x4, Off by default. Stereo only. No lookahead. No editable curve. -- Match = ~3 s average then freeze. Auto = 1–2 s smoothing, ±12 dB clamp. - -## Out of scope / later -- `gmem` gain-match pair across a whole FX chain (separate plug). -- Editable curve UI, bitmap font atlas, multiband saturation. diff --git a/docs/TEST_CHECKLIST.md b/docs/TEST_CHECKLIST.md index 7438891..0965334 100644 --- a/docs/TEST_CHECKLIST.md +++ b/docs/TEST_CHECKLIST.md @@ -21,7 +21,7 @@ Install: copy/symlink `SatComp.jsfx` into `Effects/`, insert as `JS: SatComp`. * 15. **Comp viz**: red fill follows input level on the transfer plot; dot rides the curve; fill empties on silence. 16. **Sat viz**: red part of the curve widens with level; dots reach the flat part with high Drive. 17. **Sat Mix**: Drive 60, Sat Mix 100 -> 0: sat fades out, no click, no level jump at 0 other than the drive gain. OS x2/x4: no comb when sweeping (dry leg is delay-matched). -18. **Bypass**: toggles click-free; loudness stays within ~1 dB on steady material; BYP readout shows the applied gain; GR meter keeps moving while bypassed. +18. **Bypass**: toggles click-free; output is the plain dry input (no level matching, so a hot saturator is louder when you hear the bypassed signal); GR meter keeps moving while bypassed. 19. **Out meter**: bars follow output, hold tick falls after 1 s, push Out Gain +12 on loud material -> red rect lights; click meter clears it. PK/RMS readouts sane. 20. **GR meter**: click cycles 3/6/12/18; heavy GR auto-widens the range; ticks/labels line up (labels at 1/2/3, 2/4/6, 3/6/9/12, 6/12/18). 21. **IN>OUT bar**: bar grows right for boost, left for cut, centre tick fixed. @@ -48,10 +48,10 @@ Install: copy/symlink `SatComp.jsfx` into `Effects/`, insert as `JS: SatComp`. * 37. **Spectrum**: red fill follows the signal, PRE vs POST differ by the compression; check low-end resolution, level window (-100..-30 dB) and slope; idle CPU unchanged with the EQ page closed. 38. **Automation**: touch/latch on an EQ node drag records freq+gain envelopes; check sliders 57/58 (high slider masks) record and play back. 39. **Colour schemes**: left-click logo cycles all 10; right-click shows the dropdown (current ticked) and picking one applies; save + reload project keeps it; old project (inverted) maps to Black/White. Check legibility of red-style accents on each (Sulfur has none by design), spectrum fill, GR meter, lit buttons. -40. **SAT block layout**: HP and LP rows in one cell drag/wheel/double-click independently; TONE, SAT MIX, OUT GAIN (inverted) in place; OUT GAIN cell and the plot drag edit the same value. Output and EQ OUT GAIN cells also inverted. +40. **SAT block layout**: HP and LP rows in one cell drag/wheel/double-click independently; TONE, SAT MIX, SAT GAIN (inverted) in place; SAT GAIN cell and the plot drag edit the same value. Output and EQ OUT GAIN cells also inverted. 41. **Lookahead**: L.AHEAD 0 -> bit-identical to before. Raise it on drums: transients are caught earlier (less overshoot), host PDC shifts the track by the same time (check alignment against a duplicate track, and Mix 50 % stays comb-free), Delta still sensible. Changing it live clicks (known). 42. **EQ bypass squares**: click the square in the EQ button / PRE tab / POST tab -> X appears, audio of that section is out (A/B with a strong boost), fades without clicks; re-enable has no burst. Module bypass overrides both; states persist in the project. 43. **Output column**: order MAKEUP, MIX, OUT GAIN (bottom, inverted). Values stay put as they change sign/size (zero padded); comp viewport metrics and OUT info lines don't jitter. 44. **Bypass dimming**: BYPASS on -> sat plot/selector/OS/EQ button/viewport/sat+comp cells at 50 %, header/out column full; off -> normal. Check on a few colour schemes. -45. **Readout refresh**: comp viewport LVL/OUT/GR and OUT column GR/PK/RMS update ~8x/s (readable), right-aligned values; IN>OUT, MAKEUP, MIX, OUT GAIN show plain values (no zero padding); sat OUT GAIN cell reads `+0.0dB`. +45. **Readout refresh**: comp viewport LVL/OUT/GR and OUT column GR/PK/RMS update ~8x/s (readable), right-aligned values; IN>OUT, MAKEUP, MIX, OUT GAIN show plain values (no zero padding); SAT GAIN cell reads `+0.0dB`. 46. **EQ bypass dimming**: bypass PRE -> PRE grid dims (POST grid does not); module bypass -> viewport + grid dim; global Bypass dims as before; combos stay at 50 %. diff --git a/docs/abouttextcopy.md b/docs/abouttextcopy.md index dec1b96..bb3385b 100644 --- a/docs/abouttextcopy.md +++ b/docs/abouttextcopy.md @@ -1,13 +1,77 @@ -A waveshaping saturator with compressor and 2-stage 3-band EQMade with bricking intentions (: +Misc control copy - repeat for all 3 plugins, common shared controls +=== +**== Misc Controls ==** +[Double-LMB] Slider resets parameter to default value +[LMB] GR meter cycle ranges +[LMB] Clip meter resets readout +[LMB/RMB] Top-left logo cycles color theme +[Double-LMB] Top-left logo cycles dark/light mode + +SatComp about copy +=== +A waveshaping saturator with compressor and 2-stage 3-band EQ. Made with bricking intentions (: Use saturator module to give compressor more spice to squash. -Left-click top-right pencil icon to enter custom draw mode. +[LMB] Top-right pencil icon enters custom draw mode. +[LMB] Lower-right SAT value triggers auto-gain match. Refine tone with pre/post-compressor 3-band EQ, then dial in the desired gain in the output module. -Double-click slider to reset parameter to its default value -Left/Right-click top-left icon for more color ways -Double-click top-left icon to switch between dark and light mode +**== Misc Controls ==** + +*insert attributions / Fira Code here* +thomchantra + +SatXComp about copy +=== +A 4-band compressor with waveshaping saturator and 5-band EQ. For surgical baking intentions :3 + +Set crossover range with X-OVR sliders with 12dB, 24dB, 48dB, and 96dB slope options, then drive each band to taste. + +Use Sidechain mode for dynamic EQ style ducking, then cook hard with waveshaping distortion. +[LMB] Top-right pencil icon enters custom draw mode. +[LMB] Lower-right SAT value triggers auto-gain match. + +Slower Attack and Release is ideal for low freq, faster Attack and Release for high freq. + +Refine tone with post-compressor 5-band EQ, or sculpt with notch, bandpass and allpass with dry signal blending. + +**== Spectrum Viewport ==** +[Accent] Gain Reduction vs Dry +[Inv Accent] Gain Increase vs Dry + +**== Multiband Handle Display ==** +[Top Horizontal Meter] In/Out Gain Difference +[Bottom Vertical Meter] Gain Reduction +[Top Vertical Meter] Gain Increase + +**== Misc Controls ==** + +*insert attributions / Fira Code here* +thomchantra + +SatLim about copy +=== +A 2-stage clipper/limiter with waveshaping saturator +When you need to nuke it from orbit B) + +Use Tube with low Drive for warm saturation, opt for destruction with Tri-fold, or annihilate with custom asymmetric waveshape. +[LMB] Top-right pencil icon enters custom draw mode. +[LMB] Lower-right SAT value triggers auto-gain match. + +Turn on Lookahead for brickwall, true peak limiting. +Lowering Threshold chews the input signal deeper. +Clip exposes and bricks more transients in the mix. + +Balance between Threshold (limiter) and Clip (clipper) to dial in desired loudness and character. + +Shorter Release gives a denser, punchier compression whilst introducing distortion artifacts, longer Release gives a smoother result with lower distortions. + +**== Transient/GR Meter ==** +[Solid] Limiter Gain Reduction +[Striped] Clipper Gain Reduction + +**== Misc Controls ==** *insert attributions / Fira Code here* -thomchantra \ No newline at end of file +thomchantra diff --git a/docs/colorscheme.md b/docs/colorscheme.md index 38516b8..6609691 100644 --- a/docs/colorscheme.md +++ b/docs/colorscheme.md @@ -18,8 +18,8 @@ Dark BG: #505050 UI: #FFFFFF ACCENT: #FF7300 Light BG: #FFFFFF UI: #505050 ACCENT: #FF7300 Ultramarine -Dark BG: #001A8C UI: #FFFFFF ACCENT: #264EFF -Light BG: #FFFFFF UI: #001A8C ACCENT: #264EFF +Dark BG: #001A8C UI: #FFFFFF ACCENT: #778DED +Light BG: #FFFFFF UI: #001A8C ACCENT: #778DED Azure Dark BG: #2B323C UI: #D0DBE4 ACCENT: #00CCFF @@ -81,3 +81,31 @@ Suika Dark BG: #A80400 UI: #FFFFFF ACCENT: #00FF6D Light BG: #FFFFFF UI: #A80400 ACCENT: #4CFF63 + +Brick +Dark BG: #820101 UI: #FFE7C9 ACCENT: #FF3131 +Light BG: #FFE7C9 UI: #820101 ACCENT: #F56565 + +Bob +Dark BG: #003D8C UI: #FFFFFF ACCENT: #FF6321 +Light BG: #FFFFFF UI: #003D8C ACCENT: #FF6321 + +Carbon +Dark BG: #1F1F1F UI: #DDE0EE ACCENT: #DF3333 +Light BG: #DDE0EE UI: #1F1F1F ACCENT: #DF3333 + +Olive +Dark BG: #33290E UI: #D1DAC6 ACCENT: #B87272 +Light BG: #D1DAC6 UI: #33290E ACCENT: #B87272 + +Jade +Dark BG: #063C4C UI: #00FF7F ACCENT: #FF0D00 +Light BG: #00FF7F UI: #063C4C ACCENT: #FF0D00 + +Honey +Dark BG: #342C19 UI: #FFD200 ACCENT: #FF530D +Light BG: #FFD200 UI: #342C19 ACCENT: #FF530D + +Stealth +Dark BG: #212121 UI: #4D4D4D ACCENT: #8F0D0D +Light BG: #4D4D4D UI: #212121 ACCENT: #8F0D0D diff --git a/docs/crashlogs/log1.md b/docs/crashlogs/log1.md deleted file mode 100644 index 891539c..0000000 --- a/docs/crashlogs/log1.md +++ /dev/null @@ -1,1389 +0,0 @@ -------------------------------------- -Translated Report (Full Report Below) -------------------------------------- -Process: REAPER [64971] -Path: /Applications/REAPER.app/Contents/MacOS/REAPER -Identifier: com.cockos.reaper -Version: 7.76.0_6cb0d69u (7.76.0_6cb0d69u) -Code Type: ARM-64 (Native) -Role: Foreground -Parent Process: launchd [1] -Coalition: com.cockos.reaper [2349] -User ID: 501 - -Date/Time: 2026-11-09 12:23:02.5650 +0700 -Launch Time: 2026-11-09 12:16:28.9903 +0700 -Hardware Model: Mac16,1 -OS Version: macOS 27.0.1 (26A434) -Release Type: User - -Crash Reporter Key: BCAEB6EC-392E-1692-8605-C8DE47F2E63E -Incident Identifier: 9A940F2A-0125-45AD-9DFD-3E4A04624005 - -Sleep/Wake UUID: A67ADBBD-58F8-4755-A606-8BA2EECBD9F6 - -Time Awake Since Boot: 680000 seconds -Time Since Wake: 4922 seconds - -System Integrity Protection: enabled - -Triggered by Thread: 0 reaper, Dispatch Queue: com.apple.main-thread - -Exception Type: EXC_CRASH (SIGABRT) -Exception Codes: 0x0000000000000000, 0x0000000000000000 - -Termination Reason: Namespace SIGNAL, Code 6, Abort trap: 6 -Terminating Process: REAPER [64971] - - -Application Specific Information: -abort() called - - -Thread 0 Crashed:: reaper Dispatch queue: com.apple.main-thread -0 libsystem_kernel.dylib 0x1862d1650 __pthread_kill + 8 -1 libsystem_pthread.dylib 0x18630d97c pthread_kill + 296 -2 libsystem_c.dylib 0x186210458 abort + 148 -3 satcomp 0x705555b39c 0x70553a4000 + 1799068 -4 satcomp 0x705555b1ac 0x70553a4000 + 1798572 -5 satcomp 0x7055519d0c 0x70553a4000 + 1531148 -6 satcomp 0x7055505170 0x70553a4000 + 1446256 -7 satcomp 0x70554fd648 0x70553a4000 + 1414728 -8 satcomp 0x70555058d0 0x70553a4000 + 1448144 -9 satcomp 0x705555bbd8 0x70553a4000 + 1801176 -10 satcomp 0x705555bb24 0x70553a4000 + 1800996 -11 satcomp 0x705555bcb4 0x70553a4000 + 1801396 -12 satcomp 0x705542c668 0x70553a4000 + 558696 -13 CoreFoundation 0x1863c31a0 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 -14 CoreFoundation 0x186452394 ___CFXRegistrationPost_block_invoke + 92 -15 CoreFoundation 0x1864522d8 _CFXRegistrationPost + 440 -16 CoreFoundation 0x18638f3d0 _CFXNotificationPost + 688 -17 Foundation 0x187a8038c -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 -18 AppKit 0x18aad82cc -[NSWindow resignKeyWindow] + 636 -19 REAPER 0x103363bf4 -[REAPERSwell_modelesswindow resignKeyWindow] + 52 -20 AppKit 0x18b3c7640 -[NSWindow _sendResignKeyWindow] + 100 -21 AppKit 0x18aa7ca80 -[NSWindow _changeKeyAndMainLimitedOK:] + 612 -22 AppKit 0x18aa7c7f4 -[NSWindow makeKeyWindow] + 144 -23 AppKit 0x18aa7c5ac -[NSWindow _makeKeyRegardlessOfVisibility] + 56 -24 AppKit 0x18abaf3c8 -[NSApplication _orderFrontModalWindow:relativeToWindow:] + 508 -25 AppKit 0x18abaeff0 -[NSApplication _commonBeginModalSessionForWindow:relativeToWindow:modalDelegate:didEndSelector:contextInfo:] + 1368 -26 AppKit 0x18abaea10 __35-[NSApplication runModalForWindow:]_block_invoke_2 + 36 -27 AppKit 0x18abae9d0 __35-[NSApplication runModalForWindow:]_block_invoke + 108 -28 AppKit 0x18abae280 _NSTryRunModal + 100 -29 AppKit 0x18abae15c -[NSApplication runModalForWindow:] + 276 -30 AppKit 0x18b5aeeec -[NSSavePanel runModal] + 336 -31 satcomp 0x705541b0bc 0x70553a4000 + 487612 -32 satcomp 0x7055418a40 0x70553a4000 + 477760 -33 satcomp 0x70553e73d8 0x70553a4000 + 275416 -34 satcomp 0x70553b4750 0x70553a4000 + 67408 -35 satcomp 0x70553f6b40 0x70553a4000 + 338752 -36 satcomp 0x7055417b8c 0x70553a4000 + 473996 -37 satcomp 0x705542b0b0 0x70553a4000 + 553136 -38 CoreFoundation 0x1863e88cc __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 32 -39 CoreFoundation 0x1863e85c8 __CFRunLoopDoTimer + 1084 -40 CoreFoundation 0x1863e80d8 __CFRunLoopDoTimers + 280 -41 CoreFoundation 0x1863cd5dc __CFRunLoopRun + 1852 -42 CoreFoundation 0x1864a782c _CFRunLoopRunSpecificWithOptions + 536 -43 HIToolbox 0x193800590 RunCurrentEventLoopInMode + 320 -44 HIToolbox 0x19380391c ReceiveNextEventCommon + 492 -45 HIToolbox 0x193986380 _BlockUntilNextEventMatchingListInMode + 48 -46 AppKit 0x18acc729c _DPSBlockUntilNextEventMatchingListInMode + 292 -47 AppKit 0x18a9844fc _DPSNextEvent + 580 -48 AppKit 0x18b1fc748 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 780 -49 AppKit 0x18b1fc26c -[NSApplication(NSEventRouting) nextEventMatchingMask:untilDate:inMode:dequeue:] + 292 -50 AppKit 0x18a97790c -[NSApplication run] + 396 -51 AppKit 0x18a94fc4c NSApplicationMain + 880 -52 dyld 0x185f37e80 start + 6688 - -Thread 1:: com.apple.NSEventThread -0 libsystem_kernel.dylib 0x1862c8c20 mach_msg2_trap + 8 -1 libsystem_kernel.dylib 0x1862db8e0 mach_msg2_internal + 76 -2 libsystem_kernel.dylib 0x1862d1a28 mach_msg_overwrite + 480 -3 libsystem_kernel.dylib 0x1862c8fac mach_msg + 24 -4 CoreFoundation 0x1863ceaec __CFRunLoopServiceMachPort + 160 -5 CoreFoundation 0x1863cd334 __CFRunLoopRun + 1172 -6 CoreFoundation 0x1864a782c _CFRunLoopRunSpecificWithOptions + 536 -7 AppKit 0x18aaa8844 _NSEventThread + 184 -8 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -9 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 2: - -Thread 3: -0 libsystem_kernel.dylib 0x1862c8c20 mach_msg2_trap + 8 -1 libsystem_kernel.dylib 0x1862db8e0 mach_msg2_internal + 76 -2 libsystem_kernel.dylib 0x1862d1a28 mach_msg_overwrite + 480 -3 libsystem_kernel.dylib 0x1862c8fac mach_msg + 24 -4 CoreMIDI 0x1a7ce9128 XServerMachPort::ReceiveMessage(int&, void*, int&) + 104 -5 CoreMIDI 0x1a7d0adf4 MIDIProcess::MIDIInPortThread::Run() + 148 -6 CoreMIDI 0x1a7cfe4d4 CADeprecated::XThread::RunHelper(void*) + 40 -7 CoreMIDI 0x1a7d09e14 CADeprecated::CAPThread::Entry(void*) + 96 -8 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -9 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 4:: */video -0 libsystem_kernel.dylib 0x1862cc308 __semwait_signal + 8 -1 libsystem_c.dylib 0x1861a3054 nanosleep + 220 -2 libsystem_c.dylib 0x1861a2f6c usleep + 68 -3 reaper_video.dylib 0x12c017f2c videoDecodeThread(void*) + 1300 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 5: -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1d0 _pthread_cond_wait + 980 -2 libc++.1.dylib 0x18621e7bc std::__1::condition_variable::wait(std::__1::unique_lock&) + 32 -3 Youlean Loudness Meter 2 0x701a6bfb28 0x701a680000 + 260904 -4 Youlean Loudness Meter 2 0x701a6bf9d0 0x701a680000 + 260560 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 6: -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1d0 _pthread_cond_wait + 980 -2 libc++.1.dylib 0x18621e7bc std::__1::condition_variable::wait(std::__1::unique_lock&) + 32 -3 Youlean Loudness Meter 2 0x701a6bfb28 0x701a680000 + 260904 -4 Youlean Loudness Meter 2 0x701a6bf9d0 0x701a680000 + 260560 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 7:: JUCE v8.0.12: Timer -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1d0 _pthread_cond_wait + 980 -2 libc++.1.dylib 0x18621e854 std::__1::condition_variable::__do_timed_wait(std::__1::unique_lock&, std::__1::chrono::time_point>>) + 104 -3 Scyllascope 0x701024a8a4 juce::WaitableEvent::wait(double) const + 576 -4 Scyllascope 0x701023fb4c juce::Timer::TimerThread::run() + 572 -5 Scyllascope 0x7010272c5c juce::Thread::createNativeThread(juce::Thread::Priority)::$_0::__invoke(void*) + 684 -6 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -7 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 8: -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1d0 _pthread_cond_wait + 980 -2 libc++.1.dylib 0x18621e7bc std::__1::condition_variable::wait(std::__1::unique_lock&) + 32 -3 Youlean Loudness Meter 2 0x701a6bfb28 0x701a680000 + 260904 -4 Youlean Loudness Meter 2 0x701a6bf9d0 0x701a680000 + 260560 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 9: -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1d0 _pthread_cond_wait + 980 -2 libc++.1.dylib 0x18621e7bc std::__1::condition_variable::wait(std::__1::unique_lock&) + 32 -3 Youlean Loudness Meter 2 0x701a6bfb28 0x701a680000 + 260904 -4 Youlean Loudness Meter 2 0x701a6bf9d0 0x701a680000 + 260560 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 10:: bg-worker -0 libsystem_kernel.dylib 0x1862c8b9c semaphore_wait_trap + 8 -1 libdispatch.dylib 0x18614e49c _dispatch_sema4_wait + 28 -2 libdispatch.dylib 0x18614eb28 _dispatch_semaphore_wait_slow + 132 -3 satcomp 0x705551aa00 0x70553a4000 + 1534464 -4 satcomp 0x705540715c 0x70553a4000 + 405852 -5 satcomp 0x7055408be4 0x70553a4000 + 412644 -6 satcomp 0x70553dfb7c 0x70553a4000 + 244604 -7 satcomp 0x70553fc18c 0x70553a4000 + 360844 -8 satcomp 0x705540af8c 0x70553a4000 + 421772 -9 satcomp 0x70553c1824 0x70553a4000 + 120868 -10 satcomp 0x705551f188 0x70553a4000 + 1552776 -11 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -12 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 11: - -Thread 12:: com.apple.audio.IOThread.client -0 libsystem_kernel.dylib 0x1862c8ba8 semaphore_wait_signal_trap + 8 -1 caulk 0x193267fc0 caulk::mach::semaphore::wait_signal_or_error(caulk::mach::semaphore&) + 36 -2 CoreAudio 0x189bf52d8 HALC_ProxyIOContext::IOWorkLoop() + 4932 -3 CoreAudio 0x1897c9b6c invocation function for block in HALC_ProxyIOContext::HALC_ProxyIOContext(unsigned int, unsigned int) + 172 -4 CoreAudio 0x189996c74 HALC_IOThread::Entry(void*) + 92 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 13:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 14:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 15:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 16:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 17:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 18:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 19:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 20:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 21:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 22:: */mediaafx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9c804 WorkerThreadInst::threadProc(void*) + 2284 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 23:: */livefx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9cb3c WorkerThreadInst::threadProc(void*) + 3108 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 24:: */livefx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9cb3c WorkerThreadInst::threadProc(void*) + 3108 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 25:: */livefx -0 libsystem_kernel.dylib 0x1862cc50c __psynch_cvwait + 8 -1 libsystem_pthread.dylib 0x18630e1fc _pthread_cond_wait + 1024 -2 REAPER 0x103390950 WaitForSingleObject(void*, unsigned int) + 668 -3 REAPER 0x102f9cb3c WorkerThreadInst::threadProc(void*) + 3108 -4 REAPER 0x103390b38 __threadproc(void*) + 32 -5 libsystem_pthread.dylib 0x18630dd00 _pthread_start + 136 -6 libsystem_pthread.dylib 0x186308cec thread_start + 8 - -Thread 26: - -Thread 27: - -Thread 28: - -Thread 29: - -Thread 30: - - -Thread 0 crashed with ARM Thread State (64-bit): - x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x0000000000000000 - x4: 0x000000013d34df90 x5: 0x0000000138518c00 x6: 0x0000000000000002 x7: 0x0000000000000000 - x8: 0x533b4bdd5ace8e81 x9: 0x533b4bdcb12df101 x10: 0x0000000000000002 x11: 0x00000000fffffffd - x12: 0x0000000000000000 x13: 0x0000000000000000 x14: 0x0000000000000000 x15: 0x0000000000000000 - x16: 0x0000000000000148 x17: 0x00000001eda73518 x18: 0x0000000000000000 x19: 0x0000000000000006 - x20: 0x0000000000000103 x21: 0x00000001ebe38060 x22: 0x000000705577c518 x23: 0x0000007055784000 - x24: 0x0000007055782000 x25: 0x0000000000041c00 x26: 0x000002a800000176 x27: 0x000000016cf9bb28 - x28: 0x0000000000000000 fp: 0x000000016cf9b7e0 lr: 0x000000018630d97c - sp: 0x000000016cf9b7c0 pc: 0x00000001862d1650 cpsr: 0x40000000 - far: 0x0000000000000000 esr: 0x56000080 (Syscall) - -Binary Images: - 0x102e60000 - 0x103873fff com.cockos.reaper (7.76.0_6cb0d69u) <63af0b43-88d0-345e-80d7-5bdce53efce9> /Applications/REAPER.app/Contents/MacOS/REAPER - 0x103e64000 - 0x103e6ffff libobjc-trampolines.dylib (*) <9ef9e491-f3d3-322c-918a-559d3b858d9a> /usr/lib/libobjc-trampolines.dylib - 0x113ee4000 - 0x113efffff libMetalMetricsInterpose.dylib (*) /Volumes/VOLUME/*/libMetalMetricsInterpose.dylib - 0x129ca4000 - 0x129cd3fff elastique3.dylib (*) /Applications/REAPER.app/Contents/Plugins/elastique3.dylib - 0x129c00000 - 0x129c07fff soundtouch.dylib (*) /Applications/REAPER.app/Contents/Plugins/soundtouch.dylib - 0x11af90000 - 0x11afabfff rubberband.dylib (*) /Applications/REAPER.app/Contents/Plugins/rubberband.dylib - 0x129c18000 - 0x129c6ffff jsfx.dylib (*) <1a896670-e67d-3d49-88dd-cabca854a415> /Applications/REAPER.app/Contents/Plugins/jsfx.dylib - 0x11ae20000 - 0x11ae43fff reaper_wave.dylib (*) /Applications/REAPER.app/Contents/Plugins/reaper_wave.dylib - 0x12b09c000 - 0x12b0c3fff reaper_mp3dec.dylib (*) <5c3d5154-798c-35da-bf71-d3b736a81df4> /Applications/REAPER.app/Contents/Plugins/reaper_mp3dec.dylib - 0x12b2bc000 - 0x12b303fff libmp3lame.dylib (*) <22134e04-d839-3b7c-a8ee-3aa135952a89> /Applications/REAPER.app/Contents/Plugins/libmp3lame.dylib - 0x12b654000 - 0x12b77ffff reaper_midi.dylib (*) <981f8b48-8c07-33ad-8fc4-0043cc789863> /Applications/REAPER.app/Contents/Plugins/reaper_midi.dylib - 0x12b348000 - 0x12b377fff reaper_wavpack.dylib (*) <3c5acd7b-deff-3364-a7ae-635d353222a6> /Applications/REAPER.app/Contents/Plugins/reaper_wavpack.dylib - 0x12b200000 - 0x12b26ffff reaper_opus.dylib (*) <13ce821c-8164-303c-9376-14ada1d65c12> /Applications/REAPER.app/Contents/Plugins/reaper_opus.dylib - 0x12b42c000 - 0x12b45bfff reaper_flac.dylib (*) <54e5c255-fa88-38e9-95ff-74c414b70927> /Applications/REAPER.app/Contents/Plugins/reaper_flac.dylib - 0x12b3e8000 - 0x12b3f7fff reaper_rex.dylib (*) <34e67550-7d19-3ba8-bcd3-6fd90b60e780> /Applications/REAPER.app/Contents/Plugins/reaper_rex.dylib - 0x11ae9c000 - 0x11aea7fff reaper_ddp.dylib (*) /Applications/REAPER.app/Contents/Plugins/reaper_ddp.dylib - 0x12b55c000 - 0x12b5abfff reaper_explorer.dylib (*) /Applications/REAPER.app/Contents/Plugins/reaper_explorer.dylib - 0x12b290000 - 0x12b29bfff reaper_cd.dylib (*) <056b3fca-d3df-34ad-8a18-97ec0982aa79> /Applications/REAPER.app/Contents/Plugins/reaper_cd.dylib - 0x12c1ec000 - 0x12c293fff reaper_ogg.dylib (*) <4328fdf4-6cff-3b59-8602-cdb8a829d878> /Applications/REAPER.app/Contents/Plugins/reaper_ogg.dylib - 0x12b5d0000 - 0x12b60ffff reaper_csurf.dylib (*) /Applications/REAPER.app/Contents/Plugins/reaper_csurf.dylib - 0x12c000000 - 0x12c0f7fff reaper_video.dylib (*) /Applications/REAPER.app/Contents/Plugins/reaper_video.dylib - 0x12b3c8000 - 0x12b3cffff reap_osx_modern.dylib (*) <30492a04-5521-3661-8c24-5cf77c5b71ac> /Applications/REAPER.app/Contents/Plugins/reap_osx_modern.dylib - 0x12c2e0000 - 0x12c353fff libavutil.60.26.101.dylib (*) /opt/homebrew/*/libavutil.60.26.101.dylib - 0x12c48c000 - 0x12c51bfff libssl.3.dylib (*) <704bf8e6-0dec-398e-986f-2eb58f3c6b3c> /opt/homebrew/*/libssl.3.dylib - 0x12ca04000 - 0x12cd43fff libcrypto.3.dylib (*) <6d7e86a1-ba7d-3b61-bfc7-248b1221632e> /opt/homebrew/*/libcrypto.3.dylib - 0x12c564000 - 0x12c5e3fff libswscale.9.5.101.dylib (*) <50bfe305-8558-335e-b305-09019ce57377> /opt/homebrew/*/libswscale.9.5.101.dylib - 0x12b3ac000 - 0x12b3bbfff libswresample.6.3.101.dylib (*) /opt/homebrew/*/libswresample.6.3.101.dylib - 0x12d7d8000 - 0x12e087fff libavcodec.62.28.101.dylib (*) <49303757-5681-368c-9db2-af5b5218adb6> /opt/homebrew/*/libavcodec.62.28.101.dylib - 0x12c7ec000 - 0x12c963fff libvpx.12.dylib (*) /opt/homebrew/*/libvpx.12.dylib - 0x12c63c000 - 0x12c6d3fff libdav1d.7.dylib (*) /opt/homebrew/*/libdav1d.7.dylib - 0x12b4c4000 - 0x12b4f7fff libmp3lame.0.dylib (*) /opt/homebrew/*/libmp3lame.0.dylib - 0x12c738000 - 0x12c783fff libopus.0.dylib (*) <1c7445f6-fb0e-33ea-8aa8-18597a9443ac> /opt/homebrew/*/libopus.0.dylib - 0x12d168000 - 0x12d3dbfff libSvtAv1Enc.4.1.0.dylib (*) <06e58860-87c7-3851-bb90-8d08a10ae2e7> /opt/homebrew/*/libSvtAv1Enc.4.1.0.dylib - 0x12d468000 - 0x12d587fff libx264.165.dylib (*) /opt/homebrew/*/libx264.165.dylib - 0x12eed0000 - 0x12f4affff libx265.216.dylib (*) <710dc56c-1d6c-3b7b-bba6-157396ddc818> /opt/homebrew/*/libx265.216.dylib - 0x12e7ac000 - 0x12e997fff libavformat.62.12.101.dylib (*) /opt/homebrew/*/libavformat.62.12.101.dylib - 0x12cf88000 - 0x12d04bfff libvlccore.9.dylib (*) <600321d1-62bd-395f-8699-aed018555ae1> /Applications/VLC.app/Contents/MacOS/lib/libvlccore.9.dylib - 0x16d630000 - 0x16e307fff libavcodec_plugin.dylib (*) <3da6d39e-ac45-3e06-acd0-b66c162cc860> /Applications/VLC.app/Contents/MacOS/plugins/libavcodec_plugin.dylib - 0x12b7cc000 - 0x12b7e3fff libvlc.5.dylib (*) <60f2f0e6-8acf-3f55-859c-17546d85ac58> /Applications/VLC.app/Contents/MacOS/lib/libvlc.5.dylib - 0x12b478000 - 0x12b47ffff libi420_rgb_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libi420_rgb_plugin.dylib - 0x12b418000 - 0x12b41bfff libi420_10_p010_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libi420_10_p010_plugin.dylib - 0x12b490000 - 0x12b493fff libscaletempo_pitch_plugin.dylib (*) <9752c99b-c2a5-3a9f-a9e3-e14bfe735860> /Applications/VLC.app/Contents/MacOS/plugins/libscaletempo_pitch_plugin.dylib - 0x12b4a4000 - 0x12b4a7fff libi420_yuy2_plugin.dylib (*) <858f1447-7e20-3047-9a05-b313704bd9c1> /Applications/VLC.app/Contents/MacOS/plugins/libi420_yuy2_plugin.dylib - 0x12b53c000 - 0x12b53ffff libi422_yuy2_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libi422_yuy2_plugin.dylib - 0x12b634000 - 0x12b637fff libyuy2_i420_plugin.dylib (*) <2dae5195-de46-32ef-9929-3f0dee40f299> /Applications/VLC.app/Contents/MacOS/plugins/libyuy2_i420_plugin.dylib - 0x12c148000 - 0x12c14ffff libi420_nv12_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libi420_nv12_plugin.dylib - 0x12c160000 - 0x12c163fff libyuy2_i422_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libyuy2_i422_plugin.dylib - 0x12c174000 - 0x12c17bfff libkeychain_plugin.dylib (*) <3c6552be-64b8-3221-9232-985d8666f08b> /Applications/VLC.app/Contents/MacOS/plugins/libkeychain_plugin.dylib - 0x12c18c000 - 0x12c18ffff libi422_i420_plugin.dylib (*) <4279056d-c9e3-3961-beab-8b886b9d18d3> /Applications/VLC.app/Contents/MacOS/plugins/libi422_i420_plugin.dylib - 0x12c1a0000 - 0x12c1a3fff libgrey_yuv_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libgrey_yuv_plugin.dylib - 0x12c1b4000 - 0x12c1b7fff libchain_plugin.dylib (*) <11fe731b-8256-3bff-9f23-c3e40e4db6b0> /Applications/VLC.app/Contents/MacOS/plugins/libchain_plugin.dylib - 0x12c1c8000 - 0x12c1cbfff libscale_plugin.dylib (*) <482bb48a-a07d-3dbc-89a7-0d594e17796d> /Applications/VLC.app/Contents/MacOS/plugins/libscale_plugin.dylib - 0x12c794000 - 0x12c797fff libyuvp_plugin.dylib (*) /Applications/VLC.app/Contents/MacOS/plugins/libyuvp_plugin.dylib - 0x12d698000 - 0x12d75ffff libdav1d_plugin.dylib (*) <81f4eb4e-87ff-3445-801c-2ecc40351645> /Applications/VLC.app/Contents/MacOS/plugins/libdav1d_plugin.dylib - 0x12c7a8000 - 0x12c7abfff libyuv_plugin.dylib (*) <6446a71d-d909-3354-960f-27c7efabc9a6> /Applications/VLC.app/Contents/MacOS/plugins/libyuv_plugin.dylib - 0x12c7bc000 - 0x12c7bffff libscaletempo_plugin.dylib (*) <23f21c98-24f3-3a7e-a975-ed7fc87097e8> /Applications/VLC.app/Contents/MacOS/plugins/libscaletempo_plugin.dylib - 0x12e9ec000 - 0x12ea93fff libswscale_plugin.dylib (*) <6d9def6a-e09f-3d0b-9a39-487a972b513b> /Applications/VLC.app/Contents/MacOS/plugins/libswscale_plugin.dylib - 0x12f608000 - 0x12f87bfff reaper_imgui-arm64.dylib (*) /Users/USER/Library/Application Support/REAPER/*/reaper_imgui-arm64.dylib - 0x12ec8c000 - 0x12edabfff reaper_js_ReaScriptAPI64ARM.dylib (*) <1ec74161-eae1-325c-bab0-3eec253a12a7> /Users/USER/Library/Application Support/REAPER/*/reaper_js_ReaScriptAPI64ARM.dylib - 0x12fb84000 - 0x12fd27fff reaper_reapack-arm64.dylib (*) <99d2acf4-bfe6-3926-8582-d8e8688cafb4> /Users/USER/Library/Application Support/REAPER/*/reaper_reapack-arm64.dylib - 0x168000000 - 0x16840bfff reaper_sws-arm64.dylib (*) <5ae5b818-2553-3924-89df-94afbfb7c922> /Library/Application Support/REAPER/*/reaper_sws-arm64.dylib - 0x13979c000 - 0x1397bbfff com.meldaproduction.MStereoScope (*) <995af32c-dc8d-349e-ab7d-f47c18f2666d> /Library/Audio/Plug-Ins/VST3/MeldaProduction/Stereo/MStereoScope.vst3/Contents/MacOS/MStereoScope.bin - 0x7016f60000 - 0x7019b53fff libMeldaProductionAudioPluginKernelV11.dylib (*) <2f2f4952-9d06-330c-9cc5-04ac8a6a1f5f> /Library/Application Support/MeldaProduction/*/libMeldaProductionAudioPluginKernelV11.dylib - 0x7010740000 - 0x7010e87fff com.voxengo.audio-plugins.VST3.SPAN (3.23) <3aa1dc06-f953-34a7-82d9-9fb75dc2b173> /Library/Audio/Plug-Ins/VST3/SPAN.vst3/Contents/MacOS/SPAN - 0x7010ed8000 - 0x70114fbfff com.voxengo.audio-plugins.VST3.Correlometer (1.9) <056e4443-5c3e-33a4-b988-b4e1aefafe48> /Library/Audio/Plug-Ins/VST3/Correlometer.vst3/Contents/MacOS/Correlometer - 0x701a680000 - 0x701ade7fff com.Youlean.vst3.Youlean-Loudness-Meter-2 (2.5.12) <1591aaa9-1e2b-36d7-b3e6-4436ae564f01> /Library/Audio/Plug-Ins/VST3/Youlean Loudness Meter 2.vst3/Contents/MacOS/Youlean Loudness Meter 2 - 0x701001c000 - 0x70103e3fff com.DsgDnB.Scyllascope (1.3.0) <5c5a7267-7020-3aad-8619-b88f2444540a> /Library/Audio/Plug-Ins/VST3/Scyllascope.vst3/Contents/MacOS/Scyllascope - 0x70553a4000 - 0x7055773fff com.nih-plug.satcomp (1.0.0) <077b5954-300c-32ec-95c5-4de9f1b60db5> /Library/Audio/Plug-Ins/VST3/satcomp.vst3/Contents/MacOS/satcomp - 0x700dc94000 - 0x700dcf7fff com.apple.AppleMetalOpenGLRenderer (1.0) <140d0cef-f342-380f-b7e7-cad89a979ec2> /System/Library/Extensions/AppleMetalOpenGLRenderer.bundle/Contents/MacOS/AppleMetalOpenGLRenderer - 0x1862c8000 - 0x1863069ab libsystem_kernel.dylib (*) /usr/lib/system/libsystem_kernel.dylib - 0x186307000 - 0x18631391b libsystem_pthread.dylib (*) <5a1828c3-cbc2-3b85-bd07-c8ed10021a41> /usr/lib/system/libsystem_pthread.dylib - 0x186195000 - 0x186217ca3 libsystem_c.dylib (*) /usr/lib/system/libsystem_c.dylib - 0x18634d000 - 0x1867dde9f com.apple.CoreFoundation (6.9) <727e905e-f344-3823-8e13-e7a096388321> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation - 0x187a77000 - 0x188d34287 com.apple.Foundation (6.9) <4317f7c6-73d2-3be9-b010-f318f1198a1b> /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation - 0x18a94b000 - 0x18bf8d50b com.apple.AppKit (6.9) <2688afbc-5c39-3132-bcf5-8d00d32d7615> /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit - 0x193745000 - 0x193a294ff com.apple.HIToolbox (2.1.1) <5d739a34-36b7-39b9-ba3b-7608b59c07a8> /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox - 0x185f06000 - 0x185fc56e3 dyld (*) /usr/lib/dyld - 0x0 - 0xffffffffffffffff ??? (*) <00000000-0000-0000-0000-000000000000> ??? - 0x1a7ca2000 - 0x1a7d68353 com.apple.audio.midi.CoreMIDI (2.0) /System/Library/Frameworks/CoreMIDI.framework/Versions/A/CoreMIDI - 0x186218000 - 0x1862ad033 libc++.1.dylib (*) <1e9ba4aa-b5da-3cf3-80ac-4b880049573f> /usr/lib/libc++.1.dylib - 0x18614b000 - 0x18619119f libdispatch.dylib (*) <022bf08f-0b3a-3225-9e65-16d1553ce90d> /usr/lib/system/libdispatch.dylib - 0x193248000 - 0x193272053 com.apple.audio.caulk (1.0) /System/Library/PrivateFrameworks/caulk.framework/Versions/A/caulk - 0x1895e5000 - 0x189d82633 com.apple.audio.CoreAudio (5.0) <3ab8f076-7437-38aa-9f5b-b083cf020ada> /System/Library/Frameworks/CoreAudio.framework/Versions/A/CoreAudio - -External Modification Summary: - Calls made by other processes targeting this process: - task_for_pid: 0 - thread_create: 0 - thread_set_state: 0 - Calls made by this process: - task_for_pid: 0 - thread_create: 0 - thread_set_state: 0 - Calls made by all processes on this machine: - task_for_pid: 0 - thread_create: 0 - thread_set_state: 0 - -VM Region Summary: -ReadOnly portion of Libraries: Total=3.1G resident=0K(0%) swapped_out_or_unallocated=3.1G(100%) -Writable regions: Total=2.9G written=2547K(0%) resident=1731K(0%) swapped_out=816K(0%) unallocated=2.9G(100%) - - VIRTUAL REGION -REGION TYPE SIZE COUNT (non-coalesced) -=========== ======= ======= -Accelerate Framework 384K 3 -Activity Tracing 256K 1 -AttributeGraph Data 1024K 1 -CG Image 224K 12 -ColorSync 64K 4 -CoreAnimation 5088K 194 -CoreGraphics 64K 4 -CoreImage 32K 2 -CoreServices 176K 1 -CoreUI Image Data 3504K 31 -Dyld Private Memory 128K 1 -Foundation 48K 2 -Guard 385.0G 1 -Image IO 256K 16 -Mach Message 400K 3 -Malloc 2.6G 164 -Malloc Guard Page 480K 30 -Malloc Large (reserved) 213.2M 3 reserved VM address space (unallocated) -OS Alloc Once 32K 1 -OpenGL GLSL 256K 3 -Stack 25.4M 31 -Stack Guard 56.5M 31 -Untagged 2144K 43 -Untagged (reserved) 768K 1 reserved VM address space (unallocated) -__AUTH 6690K 713 -__AUTH_CONST 100.0M 1067 -__CTF 824 1 -__DATA 99.0M 1165 -__DATA_CONST 42.2M 1138 -__DATA_DIRTY 14.7M 952 -__FONT_DATA 2352 1 -__GLSLBUILTINS 5176K 1 -__LINKEDIT 1.6G 70 -__OBJC_RO 118.0M 1 -__OBJC_RW 2735K 1 -__TEXT 1.5G 1227 -__TPRO_CONST 132K 4 -mapped file 528.5M 66 -page table in kernel 1731K 1 -shared memory 1040K 25 -=========== ======= ======= -TOTAL 391.9G 7016 -TOTAL, minus reserved VM space 391.7G 7016 - - ------------ -Full Report ------------ - -{"app_name":"REAPER","timestamp":"2026-11-09 12:23:12.00 +0700","app_version":"7.76.0_6cb0d69u","slice_uuid":"63af0b43-88d0-345e-80d7-5bdce53efce9","build_version":"7.76.0_6cb0d69u","platform":1,"bundleID":"com.cockos.reaper","share_with_app_devs":1,"is_first_party":0,"bug_type":"309","os_version":"macOS 27.0.1 (26A434)","roots_installed":0,"name":"REAPER","incident_id":"9A940F2A-0125-45AD-9DFD-3E4A04624005"} -{ - "uptime" : 680000, - "procRole" : "Foreground", - "version" : 2, - "userID" : 501, - "deployVersion" : 210, - "modelCode" : "Mac16,1", - "coalitionID" : 2349, - "osVersion" : { - "train" : "macOS 27.0.1", - "build" : "26A434", - "releaseType" : "User" - }, - "captureTime" : "2026-11-09 12:23:02.5650 +0700", - "codeSigningMonitor" : 2, - "incident" : "9A940F2A-0125-45AD-9DFD-3E4A04624005", - "pid" : 64971, - "translated" : false, - "cpuType" : "ARM-64", - "procLaunch" : "2026-11-09 12:16:28.9903 +0700", - "procStartAbsTime" : 16487735686715, - "procExitAbsTime" : 16497174125932, - "procName" : "REAPER", - "procPath" : "\/Applications\/REAPER.app\/Contents\/MacOS\/REAPER", - "bundleInfo" : {"CFBundleShortVersionString":"7.76.0_6cb0d69u","CFBundleVersion":"7.76.0_6cb0d69u","CFBundleIdentifier":"com.cockos.reaper"}, - "storeInfo" : {"deviceIdentifierForVendor":"33852C0A-DBC5-520A-BD13-E89C78348C42","thirdParty":true}, - "parentProc" : "launchd", - "parentPid" : 1, - "coalitionName" : "com.cockos.reaper", - "crashReporterKey" : "BCAEB6EC-392E-1692-8605-C8DE47F2E63E", - "chargingStatus" : {"externalSourceConnected":true}, - "developerMode" : 1, - "codeSigningID" : "com.cockos.reaper", - "codeSigningTeamID" : "Y3T58622SG", - "codeSigningFlags" : 570491653, - "codeSigningValidationCategory" : 6, - "codeSigningTrustLevel" : 4294967295, - "codeSigningAuxiliaryInfo" : 0, - "instructionByteStream" : {"beforePC":"fyMD1f17v6n9AwCR69\/\/l78DAJH9e8Go\/w9f1sADX9YQKYDSARAA1A==","atPC":"AwEAVH8jA9X9e7+p\/QMAkeDf\/5e\/AwCR\/XvBqP8PX9bAA1\/WcAqA0g=="}, - "bootSessionUUID" : "155FC183-A78F-4EF9-97A3-47237D7C69EF", - "wakeTime" : 4922, - "sleepWakeUUID" : "A67ADBBD-58F8-4755-A606-8BA2EECBD9F6", - "sip" : "enabled", - "exception" : {"codes":"0x0000000000000000, 0x0000000000000000","rawCodes":[0,0],"type":"EXC_CRASH","signal":"SIGABRT"}, - "termination" : {"flags":0,"code":6,"namespace":"SIGNAL","indicator":"Abort trap: 6","byProc":"REAPER","byPid":64971}, - "asi" : {"libsystem_c.dylib":["abort() called"]}, - "extMods" : {"caller":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"system":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"targeted":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"warnings":0}, - "faultingThread" : 0, - "threads" : [{"threadState":{"x":[{"value":0},{"value":0},{"value":0},{"value":0},{"value":5321842576},{"value":5239835648},{"value":2},{"value":0},{"value":5997470742857289345},{"value":5997470740011413761},{"value":2},{"value":4294967293},{"value":0},{"value":0},{"value":0},{"value":0},{"value":328},{"value":8282125592},{"value":0},{"value":6},{"value":259},{"value":8252522592,"symbolLocation":224,"symbol":"_main_thread"},{"value":482470249752,"symbolLocation":20568,"symbol":"clap_entry"},{"value":482470281216},{"value":482470273024},{"value":269312},{"value":2920577761654},{"value":6123273000},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546315644},"cpsr":{"value":1073741824},"fp":{"value":6123272160},"sp":{"value":6123272128},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546069072,"matchesCrashFrame":1},"far":{"value":0}},"id":9347784,"triggered":true,"name":"reaper","queue":"com.apple.main-thread","frames":[{"imageOffset":38480,"symbol":"__pthread_kill","symbolLocation":8,"imageIndex":69},{"imageOffset":27004,"symbol":"pthread_kill","symbolLocation":296,"imageIndex":70},{"imageOffset":504920,"symbol":"abort","symbolLocation":148,"imageIndex":71},{"imageOffset":1799068,"imageIndex":67},{"imageOffset":1798572,"imageIndex":67},{"imageOffset":1531148,"imageIndex":67},{"imageOffset":1446256,"imageIndex":67},{"imageOffset":1414728,"imageIndex":67},{"imageOffset":1448144,"imageIndex":67},{"imageOffset":1801176,"imageIndex":67},{"imageOffset":1800996,"imageIndex":67},{"imageOffset":1801396,"imageIndex":67},{"imageOffset":558696,"imageIndex":67},{"imageOffset":483744,"symbol":"__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__","symbolLocation":148,"imageIndex":72},{"imageOffset":1069972,"symbol":"___CFXRegistrationPost_block_invoke","symbolLocation":92,"imageIndex":72},{"imageOffset":1069784,"symbol":"_CFXRegistrationPost","symbolLocation":440,"imageIndex":72},{"imageOffset":271312,"symbol":"_CFXNotificationPost","symbolLocation":688,"imageIndex":72},{"imageOffset":37772,"symbol":"-[NSNotificationCenter postNotificationName:object:userInfo:]","symbolLocation":88,"imageIndex":73},{"imageOffset":1626828,"symbol":"-[NSWindow resignKeyWindow]","symbolLocation":636,"imageIndex":74},{"imageOffset":5258228,"symbol":"-[REAPERSwell_modelesswindow resignKeyWindow]","symbolLocation":52,"imageIndex":0},{"imageOffset":10995264,"symbol":"-[NSWindow _sendResignKeyWindow]","symbolLocation":100,"imageIndex":74},{"imageOffset":1251968,"symbol":"-[NSWindow _changeKeyAndMainLimitedOK:]","symbolLocation":612,"imageIndex":74},{"imageOffset":1251316,"symbol":"-[NSWindow makeKeyWindow]","symbolLocation":144,"imageIndex":74},{"imageOffset":1250732,"symbol":"-[NSWindow _makeKeyRegardlessOfVisibility]","symbolLocation":56,"imageIndex":74},{"imageOffset":2507720,"symbol":"-[NSApplication _orderFrontModalWindow:relativeToWindow:]","symbolLocation":508,"imageIndex":74},{"imageOffset":2506736,"symbol":"-[NSApplication _commonBeginModalSessionForWindow:relativeToWindow:modalDelegate:didEndSelector:contextInfo:]","symbolLocation":1368,"imageIndex":74},{"imageOffset":2505232,"symbol":"__35-[NSApplication runModalForWindow:]_block_invoke_2","symbolLocation":36,"imageIndex":74},{"imageOffset":2505168,"symbol":"__35-[NSApplication runModalForWindow:]_block_invoke","symbolLocation":108,"imageIndex":74},{"imageOffset":2503296,"symbol":"_NSTryRunModal","symbolLocation":100,"imageIndex":74},{"imageOffset":2503004,"symbol":"-[NSApplication runModalForWindow:]","symbolLocation":276,"imageIndex":74},{"imageOffset":12992236,"symbol":"-[NSSavePanel runModal]","symbolLocation":336,"imageIndex":74},{"imageOffset":487612,"imageIndex":67},{"imageOffset":477760,"imageIndex":67},{"imageOffset":275416,"imageIndex":67},{"imageOffset":67408,"imageIndex":67},{"imageOffset":338752,"imageIndex":67},{"imageOffset":473996,"imageIndex":67},{"imageOffset":553136,"imageIndex":67},{"imageOffset":637132,"symbol":"__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__","symbolLocation":32,"imageIndex":72},{"imageOffset":636360,"symbol":"__CFRunLoopDoTimer","symbolLocation":1084,"imageIndex":72},{"imageOffset":635096,"symbol":"__CFRunLoopDoTimers","symbolLocation":280,"imageIndex":72},{"imageOffset":525788,"symbol":"__CFRunLoopRun","symbolLocation":1852,"imageIndex":72},{"imageOffset":1419308,"symbol":"_CFRunLoopRunSpecificWithOptions","symbolLocation":536,"imageIndex":72},{"imageOffset":767376,"symbol":"RunCurrentEventLoopInMode","symbolLocation":320,"imageIndex":75},{"imageOffset":780572,"symbol":"ReceiveNextEventCommon","symbolLocation":492,"imageIndex":75},{"imageOffset":2364288,"symbol":"_BlockUntilNextEventMatchingListInMode","symbolLocation":48,"imageIndex":75},{"imageOffset":3654300,"symbol":"_DPSBlockUntilNextEventMatchingListInMode","symbolLocation":292,"imageIndex":74},{"imageOffset":234748,"symbol":"_DPSNextEvent","symbolLocation":580,"imageIndex":74},{"imageOffset":9115464,"symbol":"-[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:]","symbolLocation":780,"imageIndex":74},{"imageOffset":9114220,"symbol":"-[NSApplication(NSEventRouting) nextEventMatchingMask:untilDate:inMode:dequeue:]","symbolLocation":292,"imageIndex":74},{"imageOffset":182540,"symbol":"-[NSApplication run]","symbolLocation":396,"imageIndex":74},{"imageOffset":19532,"symbol":"NSApplicationMain","symbolLocation":880,"imageIndex":74},{"imageOffset":204416,"symbol":"start","symbolLocation":6688,"imageIndex":76}]},{"id":9347795,"name":"com.apple.NSEventThread","threadState":{"x":[{"value":268451845},{"value":21592279046},{"value":8589934592,"objc-selector":""},{"value":100068443029504},{"value":0},{"value":100068443029504},{"value":2},{"value":4294967295},{"value":0},{"value":17179869184},{"value":0},{"value":2},{"value":0},{"value":0},{"value":23299},{"value":0},{"value":18446744073709551569},{"value":8282127384},{"value":0},{"value":4294967295},{"value":2},{"value":100068443029504},{"value":0},{"value":100068443029504},{"value":21592279046},{"value":6126133400},{"value":8589934592,"objc-selector":""},{"value":18446744073709550527},{"value":4412409862}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546110688},"cpsr":{"value":0},"fp":{"value":6126133248},"sp":{"value":6126133168},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546033696},"far":{"value":0}},"frames":[{"imageOffset":3104,"symbol":"mach_msg2_trap","symbolLocation":8,"imageIndex":69},{"imageOffset":80096,"symbol":"mach_msg2_internal","symbolLocation":76,"imageIndex":69},{"imageOffset":39464,"symbol":"mach_msg_overwrite","symbolLocation":480,"imageIndex":69},{"imageOffset":4012,"symbol":"mach_msg","symbolLocation":24,"imageIndex":69},{"imageOffset":531180,"symbol":"__CFRunLoopServiceMachPort","symbolLocation":160,"imageIndex":72},{"imageOffset":525108,"symbol":"__CFRunLoopRun","symbolLocation":1172,"imageIndex":72},{"imageOffset":1419308,"symbol":"_CFRunLoopRunSpecificWithOptions","symbolLocation":536,"imageIndex":72},{"imageOffset":1431620,"symbol":"_NSEventThread","symbolLocation":184,"imageIndex":74},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9347802,"frames":[],"threadState":{"x":[{"value":6127857664},{"value":47875},{"value":6127321088},{"value":0},{"value":409604},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":6127857664},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546296024},"far":{"value":0}}},{"id":9347828,"frames":[{"imageOffset":3104,"symbol":"mach_msg2_trap","symbolLocation":8,"imageIndex":69},{"imageOffset":80096,"symbol":"mach_msg2_internal","symbolLocation":76,"imageIndex":69},{"imageOffset":39464,"symbol":"mach_msg_overwrite","symbolLocation":480,"imageIndex":69},{"imageOffset":4012,"symbol":"mach_msg","symbolLocation":24,"imageIndex":69},{"imageOffset":291112,"symbol":"XServerMachPort::ReceiveMessage(int&, void*, int&)","symbolLocation":104,"imageIndex":78},{"imageOffset":429556,"symbol":"MIDIProcess::MIDIInPortThread::Run()","symbolLocation":148,"imageIndex":78},{"imageOffset":378068,"symbol":"CADeprecated::XThread::RunHelper(void*)","symbolLocation":40,"imageIndex":78},{"imageOffset":425492,"symbol":"CADeprecated::CAPThread::Entry(void*)","symbolLocation":96,"imageIndex":78},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}],"threadState":{"x":[{"value":268451845},{"value":17179869186},{"value":0},{"value":339761977884672},{"value":0},{"value":339761977884672},{"value":100},{"value":0},{"value":0},{"value":17179869184},{"value":100},{"value":0},{"value":0},{"value":0},{"value":79107},{"value":0},{"value":18446744073709551569},{"value":8282127384},{"value":0},{"value":0},{"value":100},{"value":339761977884672},{"value":0},{"value":339761977884672},{"value":17179869186},{"value":6130149844},{"value":0},{"value":18446744073709550527},{"value":2}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546110688},"cpsr":{"value":0},"fp":{"value":6130149504},"sp":{"value":6130149424},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546033696},"far":{"value":0}}},{"id":9347856,"name":"*\/video","threadState":{"x":[{"value":4},{"value":0},{"value":1},{"value":1},{"value":0},{"value":50000000},{"value":111},{"value":3440},{"value":8252564424,"symbolLocation":0,"symbol":"clock_sem"},{"value":3},{"value":17},{"value":6197075568528807424},{"value":1},{"value":16},{"value":6153399936},{"value":8252647208,"symbolLocation":0,"symbol":"OBJC_CLASS_$___NSCFString"},{"value":334},{"value":8282125640},{"value":0},{"value":0},{"value":6153400000},{"value":5034242048,"symbolLocation":0,"symbol":"SWELL_GetListViewHeaderHeight"},{"value":5034242048,"symbolLocation":0,"symbol":"SWELL_GetListViewHeaderHeight"},{"value":5034242048,"symbolLocation":0,"symbol":"SWELL_GetListViewHeaderHeight"},{"value":5034242048,"symbolLocation":0,"symbol":"SWELL_GetListViewHeaderHeight"},{"value":0},{"value":5034242048,"symbolLocation":0,"symbol":"SWELL_GetListViewHeaderHeight"},{"value":0},{"value":5034242048,"symbolLocation":0,"symbol":"SWELL_GetListViewHeaderHeight"}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6544830548},"cpsr":{"value":2684354560},"fp":{"value":6153399984},"sp":{"value":6153399936},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546047752},"far":{"value":0}},"frames":[{"imageOffset":17160,"symbol":"__semwait_signal","symbolLocation":8,"imageIndex":69},{"imageOffset":57428,"symbol":"nanosleep","symbolLocation":220,"imageIndex":71},{"imageOffset":57196,"symbol":"usleep","symbolLocation":68,"imageIndex":71},{"imageOffset":98092,"symbol":"videoDecodeThread(void*)","symbolLocation":1300,"imageIndex":20},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9347899,"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29136,"symbol":"_pthread_cond_wait","symbolLocation":980,"imageIndex":70},{"imageOffset":26556,"symbol":"std::__1::condition_variable::wait(std::__1::unique_lock&)","symbolLocation":32,"imageIndex":79},{"imageOffset":260904,"imageIndex":65},{"imageOffset":260560,"imageIndex":65},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}],"threadState":{"x":[{"value":260},{"value":0},{"value":0},{"value":0},{"value":0},{"value":160},{"value":0},{"value":0},{"value":481295691368},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":5029349288},{"value":5029349352},{"value":481295692000},{"value":0},{"value":0},{"value":0},{"value":256},{"value":1},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317776},"cpsr":{"value":1610612736},"fp":{"value":481295691488},"sp":{"value":481295691344},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}}},{"id":9347900,"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29136,"symbol":"_pthread_cond_wait","symbolLocation":980,"imageIndex":70},{"imageOffset":26556,"symbol":"std::__1::condition_variable::wait(std::__1::unique_lock&)","symbolLocation":32,"imageIndex":79},{"imageOffset":260904,"imageIndex":65},{"imageOffset":260560,"imageIndex":65},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}],"threadState":{"x":[{"value":260},{"value":0},{"value":0},{"value":0},{"value":0},{"value":160},{"value":0},{"value":0},{"value":481304866408},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":5031701104},{"value":5031701168},{"value":481304867040},{"value":0},{"value":0},{"value":0},{"value":256},{"value":1},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317776},"cpsr":{"value":1610612736},"fp":{"value":481304866528},"sp":{"value":481304866384},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}}},{"id":9347902,"name":"JUCE v8.0.12: Timer","threadState":{"x":[{"value":260},{"value":0},{"value":186112},{"value":0},{"value":0},{"value":160},{"value":0},{"value":299998792},{"value":481311092248},{"value":0},{"value":1536},{"value":6597069768194},{"value":6597069768194},{"value":1536},{"value":0},{"value":6597069768192},{"value":305},{"value":8282125520},{"value":0},{"value":6049399664},{"value":6049399728},{"value":481311092960},{"value":299998792},{"value":0},{"value":186112},{"value":187136},{"value":186881},{"value":687382206},{"value":4294966381}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317776},"cpsr":{"value":1610612736},"fp":{"value":481311092368},"sp":{"value":481311092224},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29136,"symbol":"_pthread_cond_wait","symbolLocation":980,"imageIndex":70},{"imageOffset":26708,"symbol":"std::__1::condition_variable::__do_timed_wait(std::__1::unique_lock&, std::__1::chrono::time_point>>)","symbolLocation":104,"imageIndex":79},{"imageOffset":2287780,"symbol":"juce::WaitableEvent::wait(double) const","symbolLocation":576,"imageIndex":66},{"imageOffset":2243404,"symbol":"juce::Timer::TimerThread::run()","symbolLocation":572,"imageIndex":66},{"imageOffset":2452572,"symbol":"juce::Thread::createNativeThread(juce::Thread::Priority)::$_0::__invoke(void*)","symbolLocation":684,"imageIndex":66},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9347903,"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29136,"symbol":"_pthread_cond_wait","symbolLocation":980,"imageIndex":70},{"imageOffset":26556,"symbol":"std::__1::condition_variable::wait(std::__1::unique_lock&)","symbolLocation":32,"imageIndex":79},{"imageOffset":260904,"imageIndex":65},{"imageOffset":260560,"imageIndex":65},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}],"threadState":{"x":[{"value":260},{"value":0},{"value":0},{"value":0},{"value":0},{"value":160},{"value":0},{"value":0},{"value":481420095080},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":5237253544},{"value":5237253608},{"value":481420095712},{"value":0},{"value":0},{"value":0},{"value":256},{"value":1},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317776},"cpsr":{"value":1610612736},"fp":{"value":481420095200},"sp":{"value":481420095056},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}}},{"id":9347904,"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29136,"symbol":"_pthread_cond_wait","symbolLocation":980,"imageIndex":70},{"imageOffset":26556,"symbol":"std::__1::condition_variable::wait(std::__1::unique_lock&)","symbolLocation":32,"imageIndex":79},{"imageOffset":260904,"imageIndex":65},{"imageOffset":260560,"imageIndex":65},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}],"threadState":{"x":[{"value":260},{"value":0},{"value":0},{"value":0},{"value":0},{"value":160},{"value":0},{"value":0},{"value":481420668520},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":481700847728},{"value":481700847792},{"value":481420669152},{"value":0},{"value":0},{"value":0},{"value":256},{"value":1},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317776},"cpsr":{"value":1610612736},"fp":{"value":481420668640},"sp":{"value":481420668496},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}}},{"id":9348371,"name":"bg-worker","threadState":{"x":[{"value":14},{"value":8589934595,"objc-selector":"Փ\u000eu"},{"value":171798697235},{"value":547913272918531},{"value":14680198217728},{"value":547913272918016},{"value":48},{"value":0},{"value":0},{"value":1},{"value":0},{"value":8192},{"value":105553127185584},{"value":2095104},{"value":2043},{"value":3714072746},{"value":18446744073709551580},{"value":8282129856},{"value":0},{"value":105553161913664},{"value":105553161913600},{"value":18446744073709551615},{"value":5324342976},{"value":6048374016},{"value":6},{"value":482464246768},{"value":482464246752},{"value":18446744073709551615},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6544483484},"cpsr":{"value":1610612736},"fp":{"value":482464246528},"sp":{"value":482464246512},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546033564},"far":{"value":0}},"frames":[{"imageOffset":2972,"symbol":"semaphore_wait_trap","symbolLocation":8,"imageIndex":69},{"imageOffset":13468,"symbol":"_dispatch_sema4_wait","symbolLocation":28,"imageIndex":80},{"imageOffset":15144,"symbol":"_dispatch_semaphore_wait_slow","symbolLocation":132,"imageIndex":80},{"imageOffset":1534464,"imageIndex":67},{"imageOffset":405852,"imageIndex":67},{"imageOffset":412644,"imageIndex":67},{"imageOffset":244604,"imageIndex":67},{"imageOffset":360844,"imageIndex":67},{"imageOffset":421772,"imageIndex":67},{"imageOffset":120868,"imageIndex":67},{"imageOffset":1552776,"imageIndex":67},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9349991,"frames":[],"threadState":{"x":[{"value":6123843584},{"value":85235},{"value":6123307008},{"value":0},{"value":409604},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":6123843584},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546296024},"far":{"value":0}}},{"id":9350132,"name":"com.apple.audio.IOThread.client","threadState":{"x":[{"value":14},{"value":162311},{"value":0},{"value":0},{"value":0},{"value":512},{"value":512},{"value":0},{"value":1},{"value":3298534884098},{"value":3298534884096},{"value":3298534884098},{"value":481189330952},{"value":2},{"value":48},{"value":6},{"value":18446744073709551579},{"value":8282129864},{"value":0},{"value":5360834360},{"value":5360834352},{"value":3},{"value":512},{"value":105553136983048},{"value":105553176334640},{"value":0},{"value":5360834480},{"value":1},{"value":6155660864}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6763741120},"cpsr":{"value":1610612736},"fp":{"value":6155660560},"sp":{"value":6155660544},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546033576},"far":{"value":0}},"frames":[{"imageOffset":2984,"symbol":"semaphore_wait_signal_trap","symbolLocation":8,"imageIndex":69},{"imageOffset":131008,"symbol":"caulk::mach::semaphore::wait_signal_or_error(caulk::mach::semaphore&)","symbolLocation":36,"imageIndex":81},{"imageOffset":6357720,"symbol":"HALC_ProxyIOContext::IOWorkLoop()","symbolLocation":4932,"imageIndex":82},{"imageOffset":1985388,"symbol":"invocation function for block in HALC_ProxyIOContext::HALC_ProxyIOContext(unsigned int, unsigned int)","symbolLocation":172,"imageIndex":82},{"imageOffset":3873908,"symbol":"HALC_IOThread::Entry(void*)","symbolLocation":92,"imageIndex":82},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350222,"name":"*\/mediaafx","threadState":{"x":[{"value":260},{"value":0},{"value":18565376},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18565377},{"value":0},{"value":12288},{"value":52776558145538},{"value":52776558145538},{"value":12288},{"value":0},{"value":52776558145536},{"value":305},{"value":8282125520},{"value":0},{"value":105553157158152},{"value":105553157158216},{"value":1},{"value":5000000},{"value":0},{"value":18565376},{"value":18565632},{"value":18565377},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481191521600},"sp":{"value":481191521456},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350223,"name":"*\/mediaafx","threadState":{"x":[{"value":260},{"value":0},{"value":18675968},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18675969},{"value":0},{"value":7936},{"value":34084860468994},{"value":34084860468994},{"value":7936},{"value":0},{"value":34084860468992},{"value":305},{"value":8282125520},{"value":0},{"value":105553157158536},{"value":105553157158600},{"value":1},{"value":5000000},{"value":0},{"value":18675968},{"value":18676224},{"value":18675969},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481192095040},"sp":{"value":481192094896},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350224,"name":"*\/mediaafx","threadState":{"x":[{"value":316},{"value":0},{"value":18627072},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18627073},{"value":0},{"value":6912},{"value":29686813956866},{"value":29686813956866},{"value":6912},{"value":0},{"value":29686813956864},{"value":305},{"value":8282125520},{"value":0},{"value":105553157158664},{"value":105553157158728},{"value":1},{"value":5000000},{"value":0},{"value":18627072},{"value":18627328},{"value":18627073},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481192668480},"sp":{"value":481192668336},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350225,"name":"*\/mediaafx","threadState":{"x":[{"value":260},{"value":0},{"value":18587648},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18587649},{"value":0},{"value":6144},{"value":26388279072770},{"value":26388279072770},{"value":6144},{"value":0},{"value":26388279072768},{"value":305},{"value":8282125520},{"value":0},{"value":105553157158792},{"value":105553157158856},{"value":1},{"value":5000000},{"value":0},{"value":18587648},{"value":18587904},{"value":18587649},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481193241920},"sp":{"value":481193241776},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350226,"name":"*\/mediaafx","threadState":{"x":[{"value":260},{"value":0},{"value":18634496},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18634497},{"value":0},{"value":7168},{"value":30786325584898},{"value":30786325584898},{"value":7168},{"value":0},{"value":30786325584896},{"value":305},{"value":8282125520},{"value":0},{"value":105553157158920},{"value":105553157158984},{"value":1},{"value":5000000},{"value":0},{"value":18634496},{"value":18634752},{"value":18634497},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481193815360},"sp":{"value":481193815216},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350227,"name":"*\/mediaafx","threadState":{"x":[{"value":260},{"value":0},{"value":18652928},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18652929},{"value":0},{"value":6144},{"value":26388279072770},{"value":26388279072770},{"value":6144},{"value":0},{"value":26388279072768},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159048},{"value":105553157159112},{"value":1},{"value":5000000},{"value":0},{"value":18652928},{"value":18653184},{"value":18652929},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481194388800},"sp":{"value":481194388656},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350228,"name":"*\/mediaafx","threadState":{"x":[{"value":316},{"value":0},{"value":18647040},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18647041},{"value":0},{"value":6656},{"value":28587302328834},{"value":28587302328834},{"value":6656},{"value":0},{"value":28587302328832},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159176},{"value":105553157159240},{"value":1},{"value":5000000},{"value":0},{"value":18647040},{"value":18647296},{"value":18647041},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481194962240},"sp":{"value":481194962096},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350229,"name":"*\/mediaafx","threadState":{"x":[{"value":316},{"value":0},{"value":18668032},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18668033},{"value":0},{"value":5376},{"value":23089744188674},{"value":23089744188674},{"value":5376},{"value":0},{"value":23089744188672},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159304},{"value":105553157159368},{"value":1},{"value":5000000},{"value":0},{"value":18668032},{"value":18668288},{"value":18668033},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481294544192},"sp":{"value":481294544048},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350230,"name":"*\/mediaafx","threadState":{"x":[{"value":260},{"value":0},{"value":18684672},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18684673},{"value":0},{"value":7168},{"value":30786325584898},{"value":30786325584898},{"value":7168},{"value":0},{"value":30786325584896},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159432},{"value":105553157159496},{"value":1},{"value":5000000},{"value":0},{"value":18684672},{"value":18684928},{"value":18684673},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481295117632},"sp":{"value":481295117488},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350231,"name":"*\/mediaafx","threadState":{"x":[{"value":316},{"value":0},{"value":18688512},{"value":0},{"value":0},{"value":160},{"value":0},{"value":5000000},{"value":18688513},{"value":0},{"value":7936},{"value":34084860468994},{"value":34084860468994},{"value":7936},{"value":0},{"value":34084860468992},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159560},{"value":105553157159624},{"value":1},{"value":5000000},{"value":0},{"value":18688512},{"value":18688768},{"value":18688513},{"value":4354604204,"symbolLocation":0,"symbol":"g_config_workerthread_prio"},{"value":4294967295}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481415408960},"sp":{"value":481415408816},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1296388,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":2284,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350232,"name":"*\/livefx","threadState":{"x":[{"value":260},{"value":0},{"value":893440},{"value":0},{"value":0},{"value":160},{"value":0},{"value":20000000},{"value":4772353},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159688},{"value":105553157159752},{"value":1},{"value":20000000},{"value":0},{"value":893440},{"value":4772608},{"value":4772353},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481416703296},"sp":{"value":481416703152},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1297212,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":3108,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350233,"name":"*\/livefx","threadState":{"x":[{"value":260},{"value":0},{"value":893440},{"value":0},{"value":0},{"value":160},{"value":0},{"value":20000000},{"value":4772353},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159816},{"value":105553157159880},{"value":1},{"value":20000000},{"value":0},{"value":893440},{"value":4772608},{"value":4772353},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481417276736},"sp":{"value":481417276592},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1297212,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":3108,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9350234,"name":"*\/livefx","threadState":{"x":[{"value":260},{"value":0},{"value":893440},{"value":0},{"value":0},{"value":160},{"value":0},{"value":20000000},{"value":4772353},{"value":0},{"value":0},{"value":2},{"value":2},{"value":0},{"value":0},{"value":0},{"value":305},{"value":8282125520},{"value":0},{"value":105553157159944},{"value":105553157160008},{"value":1},{"value":20000000},{"value":0},{"value":893440},{"value":4772608},{"value":4772353},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":6546317820},"cpsr":{"value":2684354560},"fp":{"value":481417850176},"sp":{"value":481417850032},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546048268},"far":{"value":0}},"frames":[{"imageOffset":17676,"symbol":"__psynch_cvwait","symbolLocation":8,"imageIndex":69},{"imageOffset":29180,"symbol":"_pthread_cond_wait","symbolLocation":1024,"imageIndex":70},{"imageOffset":5441872,"symbol":"WaitForSingleObject(void*, unsigned int)","symbolLocation":668,"imageIndex":0},{"imageOffset":1297212,"symbol":"WorkerThreadInst::threadProc(void*)","symbolLocation":3108,"imageIndex":0},{"imageOffset":5442360,"symbol":"__threadproc(void*)","symbolLocation":32,"imageIndex":0},{"imageOffset":27904,"symbol":"_pthread_start","symbolLocation":136,"imageIndex":70},{"imageOffset":7404,"symbol":"thread_start","symbolLocation":8,"imageIndex":70}]},{"id":9351606,"frames":[],"threadState":{"x":[{"value":6124417024},{"value":182459},{"value":6123880448},{"value":0},{"value":409604},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":6124417024},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546296024},"far":{"value":0}}},{"id":9351607,"frames":[],"threadState":{"x":[{"value":6127284224},{"value":255003},{"value":6126747648},{"value":0},{"value":409604},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":6127284224},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546296024},"far":{"value":0}}},{"id":9352822,"frames":[],"threadState":{"x":[{"value":6126710784},{"value":183283},{"value":6126174208},{"value":0},{"value":409604},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":6126710784},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546296024},"far":{"value":0}}},{"id":9352823,"frames":[],"threadState":{"x":[{"value":6128431104},{"value":188931},{"value":6127894528},{"value":0},{"value":409604},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":6128431104},"esr":{"value":1442840704,"description":"(Syscall)"},"pc":{"value":6546296024},"far":{"value":0}}},{"id":9353455,"frames":[],"threadState":{"x":[{"value":481291137024},{"value":0},{"value":481290600448},{"value":0},{"value":278532},{"value":18446744073709551615},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":0},"cpsr":{"value":0},"fp":{"value":0},"sp":{"value":481291137024},"esr":{"value":0},"pc":{"value":6546296024},"far":{"value":0}}}], - "usedImages" : [ - { - "source" : "P", - "arch" : "arm64", - "base" : 4343595008, - "CFBundleShortVersionString" : "7.76.0_6cb0d69u", - "CFBundleIdentifier" : "com.cockos.reaper", - "size" : 10567680, - "uuid" : "63af0b43-88d0-345e-80d7-5bdce53efce9", - "path" : "\/Applications\/REAPER.app\/Contents\/MacOS\/REAPER", - "name" : "REAPER", - "CFBundleVersion" : "7.76.0_6cb0d69u" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 4360388608, - "size" : 49152, - "uuid" : "9ef9e491-f3d3-322c-918a-559d3b858d9a", - "path" : "\/usr\/lib\/libobjc-trampolines.dylib", - "name" : "libobjc-trampolines.dylib" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 4629348352, - "size" : 114688, - "uuid" : "b7d8c7ba-8c30-3362-b3c7-d0998077dc1d", - "path" : "\/Volumes\/VOLUME\/*\/libMetalMetricsInterpose.dylib", - "name" : "libMetalMetricsInterpose.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 4996087808, - "size" : 196608, - "uuid" : "fdeee20a-415a-3c11-b3e0-2f7a3d2ffb81", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/elastique3.dylib", - "name" : "elastique3.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 4995416064, - "size" : 32768, - "uuid" : "b467a3bf-d8d5-30c0-a58e-945a0ce2c239", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/soundtouch.dylib", - "name" : "soundtouch.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 4747493376, - "size" : 114688, - "uuid" : "e8b80eeb-df32-3f3f-99d5-8c869d457618", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/rubberband.dylib", - "name" : "rubberband.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 4995514368, - "size" : 360448, - "uuid" : "1a896670-e67d-3d49-88dd-cabca854a415", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/jsfx.dylib", - "name" : "jsfx.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 4745986048, - "size" : 147456, - "uuid" : "ba5355e0-01c0-31c8-827e-bc457175245a", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_wave.dylib", - "name" : "reaper_wave.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5017026560, - "size" : 163840, - "uuid" : "5c3d5154-798c-35da-bf71-d3b736a81df4", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_mp3dec.dylib", - "name" : "reaper_mp3dec.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5019254784, - "size" : 294912, - "uuid" : "22134e04-d839-3b7c-a8ee-3aa135952a89", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/libmp3lame.dylib", - "name" : "libmp3lame.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5023023104, - "size" : 1228800, - "uuid" : "981f8b48-8c07-33ad-8fc4-0043cc789863", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_midi.dylib", - "name" : "reaper_midi.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5019828224, - "size" : 196608, - "uuid" : "3c5acd7b-deff-3364-a7ae-635d353222a6", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_wavpack.dylib", - "name" : "reaper_wavpack.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5018484736, - "size" : 458752, - "uuid" : "13ce821c-8164-303c-9376-14ada1d65c12", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_opus.dylib", - "name" : "reaper_opus.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5020762112, - "size" : 196608, - "uuid" : "54e5c255-fa88-38e9-95ff-74c414b70927", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_flac.dylib", - "name" : "reaper_flac.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5020483584, - "size" : 65536, - "uuid" : "34e67550-7d19-3ba8-bcd3-6fd90b60e780", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_rex.dylib", - "name" : "reaper_rex.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 4746493952, - "size" : 49152, - "uuid" : "f0c06206-3678-308d-986f-cc50f60ea061", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_ddp.dylib", - "name" : "reaper_ddp.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5022007296, - "size" : 327680, - "uuid" : "daed245b-073b-35bd-93a0-5be72df093d8", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_explorer.dylib", - "name" : "reaper_explorer.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5019074560, - "size" : 49152, - "uuid" : "056b3fca-d3df-34ad-8a18-97ec0982aa79", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_cd.dylib", - "name" : "reaper_cd.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5035180032, - "size" : 688128, - "uuid" : "4328fdf4-6cff-3b59-8602-cdb8a829d878", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_ogg.dylib", - "name" : "reaper_ogg.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5022482432, - "size" : 262144, - "uuid" : "beba3477-3808-3dec-ba8a-cddff1b94f65", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_csurf.dylib", - "name" : "reaper_csurf.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5033164800, - "size" : 1015808, - "uuid" : "f48aab88-2228-3f9f-946c-58e30e57428f", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reaper_video.dylib", - "name" : "reaper_video.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5020352512, - "size" : 32768, - "uuid" : "30492a04-5521-3661-8c24-5cf77c5b71ac", - "path" : "\/Applications\/REAPER.app\/Contents\/Plugins\/reap_osx_modern.dylib", - "name" : "reap_osx_modern.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5036179456, - "size" : 475136, - "uuid" : "c65071ae-5ed4-3e54-b56c-4b625005edbc", - "path" : "\/opt\/homebrew\/*\/libavutil.60.26.101.dylib", - "name" : "libavutil.60.26.101.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5037932544, - "size" : 589824, - "uuid" : "704bf8e6-0dec-398e-986f-2eb58f3c6b3c", - "path" : "\/opt\/homebrew\/*\/libssl.3.dylib", - "name" : "libssl.3.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5043666944, - "size" : 3407872, - "uuid" : "6d7e86a1-ba7d-3b61-bfc7-248b1221632e", - "path" : "\/opt\/homebrew\/*\/libcrypto.3.dylib", - "name" : "libcrypto.3.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5038817280, - "size" : 524288, - "uuid" : "50bfe305-8558-335e-b305-09019ce57377", - "path" : "\/opt\/homebrew\/*\/libswscale.9.5.101.dylib", - "name" : "libswscale.9.5.101.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5020237824, - "size" : 65536, - "uuid" : "e59853f8-fd79-3cc8-95d6-95ff184ba81f", - "path" : "\/opt\/homebrew\/*\/libswresample.6.3.101.dylib", - "name" : "libswresample.6.3.101.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5058166784, - "size" : 9109504, - "uuid" : "49303757-5681-368c-9db2-af5b5218adb6", - "path" : "\/opt\/homebrew\/*\/libavcodec.62.28.101.dylib", - "name" : "libavcodec.62.28.101.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5041471488, - "size" : 1540096, - "uuid" : "abef3286-0a7b-3e10-8825-81c8a863efa8", - "path" : "\/opt\/homebrew\/*\/libvpx.12.dylib", - "name" : "libvpx.12.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5039702016, - "size" : 622592, - "uuid" : "b317db1b-7e5e-3ad6-8dfb-5f30139ba348", - "path" : "\/opt\/homebrew\/*\/libdav1d.7.dylib", - "name" : "libdav1d.7.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5021384704, - "size" : 212992, - "uuid" : "de863ab7-3cf8-38fe-ae37-59a526573730", - "path" : "\/opt\/homebrew\/*\/libmp3lame.0.dylib", - "name" : "libmp3lame.0.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5040734208, - "size" : 311296, - "uuid" : "1c7445f6-fb0e-33ea-8aa8-18597a9443ac", - "path" : "\/opt\/homebrew\/*\/libopus.0.dylib", - "name" : "libopus.0.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5051416576, - "size" : 2572288, - "uuid" : "06e58860-87c7-3851-bb90-8d08a10ae2e7", - "path" : "\/opt\/homebrew\/*\/libSvtAv1Enc.4.1.0.dylib", - "name" : "libSvtAv1Enc.4.1.0.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5054562304, - "size" : 1179648, - "uuid" : "b916484f-5239-335b-b9fe-4e71261da16b", - "path" : "\/opt\/homebrew\/*\/libx264.165.dylib", - "name" : "libx264.165.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5082251264, - "size" : 6160384, - "uuid" : "710dc56c-1d6c-3b7b-bba6-157396ddc818", - "path" : "\/opt\/homebrew\/*\/libx265.216.dylib", - "name" : "libx265.216.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5074763776, - "size" : 2015232, - "uuid" : "da948b54-d8e2-3e3d-8efc-097ee2fbc2a7", - "path" : "\/opt\/homebrew\/*\/libavformat.62.12.101.dylib", - "name" : "libavformat.62.12.101.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5049450496, - "size" : 802816, - "uuid" : "600321d1-62bd-395f-8699-aed018555ae1", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/lib\/libvlccore.9.dylib", - "name" : "libvlccore.9.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 6130171904, - "size" : 13467648, - "uuid" : "3da6d39e-ac45-3e06-acd0-b66c162cc860", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libavcodec_plugin.dylib", - "name" : "libavcodec_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5024563200, - "size" : 98304, - "uuid" : "60f2f0e6-8acf-3f55-859c-17546d85ac58", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/lib\/libvlc.5.dylib", - "name" : "libvlc.5.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5021073408, - "size" : 32768, - "uuid" : "e5ee2c91-b180-3082-9fec-f624c83e63af", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libi420_rgb_plugin.dylib", - "name" : "libi420_rgb_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5020680192, - "size" : 16384, - "uuid" : "f3610263-f7e8-31cb-9d9d-8eced5725499", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libi420_10_p010_plugin.dylib", - "name" : "libi420_10_p010_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5021171712, - "size" : 16384, - "uuid" : "9752c99b-c2a5-3a9f-a9e3-e14bfe735860", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libscaletempo_pitch_plugin.dylib", - "name" : "libscaletempo_pitch_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5021253632, - "size" : 16384, - "uuid" : "858f1447-7e20-3047-9a05-b313704bd9c1", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libi420_yuy2_plugin.dylib", - "name" : "libi420_yuy2_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5021876224, - "size" : 16384, - "uuid" : "ca4cf604-6588-39b3-91e7-9b1d5a2677a5", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libi422_yuy2_plugin.dylib", - "name" : "libi422_yuy2_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5022892032, - "size" : 16384, - "uuid" : "2dae5195-de46-32ef-9929-3f0dee40f299", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libyuy2_i420_plugin.dylib", - "name" : "libyuy2_i420_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5034508288, - "size" : 32768, - "uuid" : "d107acae-a835-3cc4-bd43-a200af1b8c24", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libi420_nv12_plugin.dylib", - "name" : "libi420_nv12_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5034606592, - "size" : 16384, - "uuid" : "a0b9902a-a6e1-3cf7-bc76-a9997640a925", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libyuy2_i422_plugin.dylib", - "name" : "libyuy2_i422_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5034688512, - "size" : 32768, - "uuid" : "3c6552be-64b8-3221-9232-985d8666f08b", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libkeychain_plugin.dylib", - "name" : "libkeychain_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5034786816, - "size" : 16384, - "uuid" : "4279056d-c9e3-3961-beab-8b886b9d18d3", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libi422_i420_plugin.dylib", - "name" : "libi422_i420_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5034868736, - "size" : 16384, - "uuid" : "d57407c8-8e20-3672-a170-48b1af424fb8", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libgrey_yuv_plugin.dylib", - "name" : "libgrey_yuv_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5034950656, - "size" : 16384, - "uuid" : "11fe731b-8256-3bff-9f23-c3e40e4db6b0", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libchain_plugin.dylib", - "name" : "libchain_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5035032576, - "size" : 16384, - "uuid" : "482bb48a-a07d-3dbc-89a7-0d594e17796d", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libscale_plugin.dylib", - "name" : "libscale_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5041111040, - "size" : 16384, - "uuid" : "fac3d456-4c92-372a-b223-14d1969c13cc", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libyuvp_plugin.dylib", - "name" : "libyuvp_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5056856064, - "size" : 819200, - "uuid" : "81f4eb4e-87ff-3445-801c-2ecc40351645", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libdav1d_plugin.dylib", - "name" : "libdav1d_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5041192960, - "size" : 16384, - "uuid" : "6446a71d-d909-3354-960f-27c7efabc9a6", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libyuv_plugin.dylib", - "name" : "libyuv_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5041274880, - "size" : 16384, - "uuid" : "23f21c98-24f3-3a7e-a975-ed7fc87097e8", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libscaletempo_plugin.dylib", - "name" : "libscaletempo_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5077123072, - "size" : 688128, - "uuid" : "6d9def6a-e09f-3d0b-9a39-487a972b513b", - "path" : "\/Applications\/VLC.app\/Contents\/MacOS\/plugins\/libswscale_plugin.dylib", - "name" : "libswscale_plugin.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5089820672, - "size" : 2572288, - "uuid" : "c7798dc2-75c9-38fe-b9a4-235e2091f679", - "path" : "\/Users\/USER\/Library\/Application Support\/REAPER\/*\/reaper_imgui-arm64.dylib", - "name" : "reaper_imgui-arm64.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5079875584, - "size" : 1179648, - "uuid" : "1ec74161-eae1-325c-bab0-3eec253a12a7", - "path" : "\/Users\/USER\/Library\/Application Support\/REAPER\/*\/reaper_js_ReaScriptAPI64ARM.dylib", - "name" : "reaper_js_ReaScriptAPI64ARM.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5095571456, - "size" : 1720320, - "uuid" : "99d2acf4-bfe6-3926-8582-d8e8688cafb4", - "path" : "\/Users\/USER\/Library\/Application Support\/REAPER\/*\/reaper_reapack-arm64.dylib", - "name" : "reaper_reapack-arm64.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 6039797760, - "size" : 4243456, - "uuid" : "5ae5b818-2553-3924-89df-94afbfb7c922", - "path" : "\/Library\/Application Support\/REAPER\/*\/reaper_sws-arm64.dylib", - "name" : "reaper_sws-arm64.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 5259247616, - "CFBundleIdentifier" : "com.meldaproduction.MStereoScope", - "size" : 131072, - "uuid" : "995af32c-dc8d-349e-ab7d-f47c18f2666d", - "path" : "\/Library\/Audio\/Plug-Ins\/VST3\/MeldaProduction\/Stereo\/MStereoScope.vst3\/Contents\/MacOS\/MStereoScope.bin", - "name" : "MStereoScope.bin", - "CFBundleVersion" : "17.10" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 481421557760, - "size" : 46088192, - "uuid" : "2f2f4952-9d06-330c-9cc5-04ac8a6a1f5f", - "path" : "\/Library\/Application Support\/MeldaProduction\/*\/libMeldaProductionAudioPluginKernelV11.dylib", - "name" : "libMeldaProductionAudioPluginKernelV11.dylib" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 481312374784, - "CFBundleShortVersionString" : "3.23", - "CFBundleIdentifier" : "com.voxengo.audio-plugins.VST3.SPAN", - "size" : 7634944, - "uuid" : "3aa1dc06-f953-34a7-82d9-9fb75dc2b173", - "path" : "\/Library\/Audio\/Plug-Ins\/VST3\/SPAN.vst3\/Contents\/MacOS\/SPAN", - "name" : "SPAN", - "CFBundleVersion" : "3.23" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 481320337408, - "CFBundleShortVersionString" : "1.9", - "CFBundleIdentifier" : "com.voxengo.audio-plugins.VST3.Correlometer", - "size" : 6438912, - "uuid" : "056e4443-5c3e-33a4-b988-b4e1aefafe48", - "path" : "\/Library\/Audio\/Plug-Ins\/VST3\/Correlometer.vst3\/Contents\/MacOS\/Correlometer", - "name" : "Correlometer", - "CFBundleVersion" : "1.9" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 481479360512, - "CFBundleShortVersionString" : "2.5.12", - "CFBundleIdentifier" : "com.Youlean.vst3.Youlean-Loudness-Meter-2", - "size" : 7766016, - "uuid" : "1591aaa9-1e2b-36d7-b3e6-4436ae564f01", - "path" : "\/Library\/Audio\/Plug-Ins\/VST3\/Youlean Loudness Meter 2.vst3\/Contents\/MacOS\/Youlean Loudness Meter 2", - "name" : "Youlean Loudness Meter 2", - "CFBundleVersion" : "2.5.12" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 481304887296, - "CFBundleShortVersionString" : "1.3.0", - "CFBundleIdentifier" : "com.DsgDnB.Scyllascope", - "size" : 3964928, - "uuid" : "5c5a7267-7020-3aad-8619-b88f2444540a", - "path" : "\/Library\/Audio\/Plug-Ins\/VST3\/Scyllascope.vst3\/Contents\/MacOS\/Scyllascope", - "name" : "Scyllascope", - "CFBundleVersion" : "1.3.0" - }, - { - "source" : "P", - "arch" : "arm64", - "base" : 482466217984, - "CFBundleShortVersionString" : "1.0.0", - "CFBundleIdentifier" : "com.nih-plug.satcomp", - "size" : 3997696, - "uuid" : "077b5954-300c-32ec-95c5-4de9f1b60db5", - "path" : "\/Library\/Audio\/Plug-Ins\/VST3\/satcomp.vst3\/Contents\/MacOS\/satcomp", - "name" : "satcomp", - "CFBundleVersion" : "1.0.0" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 481267630080, - "CFBundleShortVersionString" : "1.0", - "CFBundleIdentifier" : "com.apple.AppleMetalOpenGLRenderer", - "size" : 409600, - "uuid" : "140d0cef-f342-380f-b7e7-cad89a979ec2", - "path" : "\/System\/Library\/Extensions\/AppleMetalOpenGLRenderer.bundle\/Contents\/MacOS\/AppleMetalOpenGLRenderer", - "name" : "AppleMetalOpenGLRenderer", - "CFBundleVersion" : "1" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6546030592, - "size" : 256428, - "uuid" : "f63bf418-8f75-34a4-aaf1-8caf2b9b6a05", - "path" : "\/usr\/lib\/system\/libsystem_kernel.dylib", - "name" : "libsystem_kernel.dylib" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6546288640, - "size" : 51484, - "uuid" : "5a1828c3-cbc2-3b85-bd07-c8ed10021a41", - "path" : "\/usr\/lib\/system\/libsystem_pthread.dylib", - "name" : "libsystem_pthread.dylib" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6544773120, - "size" : 535716, - "uuid" : "fba7b23e-aa60-3a90-9aa4-a7a2e0ad63ee", - "path" : "\/usr\/lib\/system\/libsystem_c.dylib", - "name" : "libsystem_c.dylib" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6546575360, - "CFBundleShortVersionString" : "6.9", - "CFBundleIdentifier" : "com.apple.CoreFoundation", - "size" : 4787872, - "uuid" : "727e905e-f344-3823-8e13-e7a096388321", - "path" : "\/System\/Library\/Frameworks\/CoreFoundation.framework\/Versions\/A\/CoreFoundation", - "name" : "CoreFoundation", - "CFBundleVersion" : "5027.0.69" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6570864640, - "CFBundleShortVersionString" : "6.9", - "CFBundleIdentifier" : "com.apple.Foundation", - "size" : 19649160, - "uuid" : "4317f7c6-73d2-3be9-b010-f318f1198a1b", - "path" : "\/System\/Library\/Frameworks\/Foundation.framework\/Versions\/C\/Foundation", - "name" : "Foundation", - "CFBundleVersion" : "5027.0.69" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6619967488, - "CFBundleShortVersionString" : "6.9", - "CFBundleIdentifier" : "com.apple.AppKit", - "size" : 23340300, - "uuid" : "2688afbc-5c39-3132-bcf5-8d00d32d7615", - "path" : "\/System\/Library\/Frameworks\/AppKit.framework\/Versions\/C\/AppKit", - "name" : "AppKit", - "CFBundleVersion" : "2775.10.103.1" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6768840704, - "CFBundleShortVersionString" : "2.1.1", - "CFBundleIdentifier" : "com.apple.HIToolbox", - "size" : 3032320, - "uuid" : "5d739a34-36b7-39b9-ba3b-7608b59c07a8", - "path" : "\/System\/Library\/Frameworks\/Carbon.framework\/Versions\/A\/Frameworks\/HIToolbox.framework\/Versions\/A\/HIToolbox", - "name" : "HIToolbox" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6542090240, - "size" : 784100, - "uuid" : "d341ddcb-7969-3a9c-8e03-0cf4751398a9", - "path" : "\/usr\/lib\/dyld", - "name" : "dyld" - }, - { - "size" : 0, - "source" : "A", - "base" : 0, - "uuid" : "00000000-0000-0000-0000-000000000000" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 7110008832, - "CFBundleShortVersionString" : "2.0", - "CFBundleIdentifier" : "com.apple.audio.midi.CoreMIDI", - "size" : 811860, - "uuid" : "da3e2cf1-d70c-3055-bf59-0f604da694a9", - "path" : "\/System\/Library\/Frameworks\/CoreMIDI.framework\/Versions\/A\/CoreMIDI", - "name" : "CoreMIDI", - "CFBundleVersion" : "88" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6545309696, - "size" : 610356, - "uuid" : "1e9ba4aa-b5da-3cf3-80ac-4b880049573f", - "path" : "\/usr\/lib\/libc++.1.dylib", - "name" : "libc++.1.dylib" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6544470016, - "size" : 287136, - "uuid" : "022bf08f-0b3a-3225-9e65-16d1553ce90d", - "path" : "\/usr\/lib\/system\/libdispatch.dylib", - "name" : "libdispatch.dylib" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6763610112, - "CFBundleShortVersionString" : "1.0", - "CFBundleIdentifier" : "com.apple.audio.caulk", - "size" : 172116, - "uuid" : "c7ba2b3e-b175-30e9-abf6-4d568d9daa51", - "path" : "\/System\/Library\/PrivateFrameworks\/caulk.framework\/Versions\/A\/caulk", - "name" : "caulk" - }, - { - "source" : "P", - "arch" : "arm64e", - "base" : 6599626752, - "CFBundleShortVersionString" : "5.0", - "CFBundleIdentifier" : "com.apple.audio.CoreAudio", - "size" : 7984692, - "uuid" : "3ab8f076-7437-38aa-9f5b-b083cf020ada", - "path" : "\/System\/Library\/Frameworks\/CoreAudio.framework\/Versions\/A\/CoreAudio", - "name" : "CoreAudio", - "CFBundleVersion" : "5.0" - } -], - "sharedCache" : { - "base" : 6537347072, - "size" : 7410368512, - "uuid" : "c284a291-b68b-3d0d-a1a0-3f866f87efdc" -}, - "vmSummary" : "ReadOnly portion of Libraries: Total=3.1G resident=0K(0%) swapped_out_or_unallocated=3.1G(100%)\nWritable regions: Total=2.9G written=2547K(0%) resident=1731K(0%) swapped_out=816K(0%) unallocated=2.9G(100%)\n\n VIRTUAL REGION \nREGION TYPE SIZE COUNT (non-coalesced) \n=========== ======= ======= \nAccelerate Framework 384K 3 \nActivity Tracing 256K 1 \nAttributeGraph Data 1024K 1 \nCG Image 224K 12 \nColorSync 64K 4 \nCoreAnimation 5088K 194 \nCoreGraphics 64K 4 \nCoreImage 32K 2 \nCoreServices 176K 1 \nCoreUI Image Data 3504K 31 \nDyld Private Memory 128K 1 \nFoundation 48K 2 \nGuard 385.0G 1 \nImage IO 256K 16 \nMach Message 400K 3 \nMalloc 2.6G 164 \nMalloc Guard Page 480K 30 \nMalloc Large (reserved) 213.2M 3 reserved VM address space (unallocated)\nOS Alloc Once 32K 1 \nOpenGL GLSL 256K 3 \nStack 25.4M 31 \nStack Guard 56.5M 31 \nUntagged 2144K 43 \nUntagged (reserved) 768K 1 reserved VM address space (unallocated)\n__AUTH 6690K 713 \n__AUTH_CONST 100.0M 1067 \n__CTF 824 1 \n__DATA 99.0M 1165 \n__DATA_CONST 42.2M 1138 \n__DATA_DIRTY 14.7M 952 \n__FONT_DATA 2352 1 \n__GLSLBUILTINS 5176K 1 \n__LINKEDIT 1.6G 70 \n__OBJC_RO 118.0M 1 \n__OBJC_RW 2735K 1 \n__TEXT 1.5G 1227 \n__TPRO_CONST 132K 4 \nmapped file 528.5M 66 \npage table in kernel 1731K 1 \nshared memory 1040K 25 \n=========== ======= ======= \nTOTAL 391.9G 7016 \nTOTAL, minus reserved VM space 391.7G 7016 \n", - "legacyInfo" : { - "threadTriggered" : { - "name" : "reaper", - "queue" : "com.apple.main-thread" - } -}, - "logWritingSignature" : "0133e4cb1ce286f8efa45d79fecd17517f11b121", - "roots_installed" : 0, - "bug_type" : "309", - "trmStatus" : 1, - "trialInfo" : { - "rollouts" : [ - { - "rolloutId" : "6297d96be2c9387df974efa4", - "factorPackIds" : [ - - ], - "deploymentId" : 240000032 - }, - { - "rolloutId" : "67648e5334a82511f4acf879", - "factorPackIds" : [ - - ], - "deploymentId" : 240000008 - } - ], - "experiments" : [ - - ] -} -} - -Model: Mac16,1, BootROM 20457.1.29, proc 10:0:4:6 processors, 16 GB, SMC -Graphics: Apple M4, Apple M4, Built-In -Display: Color LCD, 3024 x 1964 Retina, Main, MirrorOff, Online -Display: LS24F32xG, 1920 x 1080 (1080p FHD - Full High Definition), MirrorOff, Online -Memory Module: LPDDR5, Micron -AirPort: spairport_wireless_card_type_wifi (0x14E4, 0x4388), wl0: Jul 2 2026 00:44:50 version 23.10.1039.0.41.51.239 FWID 01-974167da -IO80211_driverkit-1585.80 "IO80211_driverkit-1585.80" Sep 18 2026 22:02:52 -AirPort: -Bluetooth: Version (null), 0 services, 0 devices, 0 incoming serial ports -Network Service: Wi-Fi, AirPort, en0 -Thunderbolt Bus: MacBook Pro, Apple Inc. -Thunderbolt Bus: MacBook Pro, Apple Inc. -Thunderbolt Bus: MacBook Pro, Apple Inc. diff --git a/docs/install/INSTALL-Linux.txt b/docs/install/INSTALL-Linux.txt new file mode 100644 index 0000000..67c3e3c --- /dev/null +++ b/docs/install/INSTALL-Linux.txt @@ -0,0 +1,47 @@ +@NAME@ @VER@ - installation (Linux, experimental) +================================================= + +This Linux build is new and lightly tested. Known issue: the meters and the scope can stutter on some +systems (a fix is planned). Feedback is very welcome (see "Got issues?" below). + +This zip contains two plug-in formats (VST3 and CLAP). The VST3 is a FOLDER, not a single file. + +Easiest: the install script +--------------------------- +1. Unzip the download and open a terminal in the unzipped folder. +2. Run: bash install.sh + It copies both formats into your home folder (~/.vst3 and ~/.clap). Add --system to install + for all users instead (it asks for your password). +3. Rescan plug-ins in your host (REAPER: Options > Preferences > Plug-ins > VST/CLAP > Re-scan) + or restart it. The plug-in appears as "@NAME@". + +By hand +------- +~/.vst3 and ~/.clap are HIDDEN folders (names starting with a dot). In your file manager press +Ctrl+H to show hidden files, and create the folder if it does not exist yet. + VST3: copy the whole folder VST3/@PLUGIN@.vst3 into ~/.vst3/ + (for all users: /usr/local/lib/vst3/) + CLAP: copy CLAP/@PLUGIN@.clap into ~/.clap/ + (for all users: /usr/local/lib/clap/) + +Needs an X11 session (the window is drawn through X11 and OpenGL). The manual button opens the +PDF with your default viewer (xdg-open). + +Your settings and presets +------------------------- + Presets: ~/.config/@NAME@/Presets + Themes: ~/.config/SatComp/themes.json (shared by SatComp, SatXComp and SatLim) + +Uninstall: delete the files you copied. + + +Got issues? +----------- +Found a bug, or something sounds or looks odd? Please submit a bug report on GitHub: + https://github.com/thomchantra/SatComp/issues +Say which plug-in and version, your host (DAW) and operating system, and what you did. A screenshot +or a short description of how to reproduce it helps a lot. + +Enjoying it? You can support the project here: https://ko-fi.com/thomchantra + +Licence: GPL-3.0-or-later, see LICENSE. diff --git a/docs/install/INSTALL-Windows.txt b/docs/install/INSTALL-Windows.txt new file mode 100644 index 0000000..bba7cea --- /dev/null +++ b/docs/install/INSTALL-Windows.txt @@ -0,0 +1,36 @@ +@NAME@ @VER@ - installation (Windows) +===================================== + +This zip contains two plug-in formats. Install the one your host uses (or both): + + VST3\@PLUGIN@.vst3 the VST3 plug-in. It is a FOLDER: copy the whole folder, do not open it + CLAP\@PLUGIN@.clap the CLAP plug-in (a single file) + +1. Unzip the download anywhere. +2. VST3: copy the folder VST3\@PLUGIN@.vst3 into + C:\Program Files\Common Files\VST3\ + (Windows asks for administrator permission. No admin rights? Use + %LOCALAPPDATA%\Programs\Common\VST3\ + instead; most hosts scan it.) +3. CLAP: copy CLAP\@PLUGIN@.clap into + C:\Program Files\Common Files\CLAP\ + (or %LOCALAPPDATA%\Programs\Common\CLAP\) +4. Rescan plug-ins in your host (or restart it). The plug-in appears as "@NAME@". + +Your settings and presets +------------------------- + Presets: %APPDATA%\@NAME@\Presets + Themes: %APPDATA%\SatComp\themes.json (shared by SatComp, SatXComp and SatLim) + +Uninstall: delete the folder or file you copied. + +Got issues? +----------- +Found a bug, or something sounds or looks odd? Please submit a bug report on GitHub: + https://github.com/thomchantra/SatComp/issues +Say which plug-in and version, your host (DAW) and operating system, and what you did. A screenshot +or a short description of how to reproduce it helps a lot. + +Enjoying it? You can support the project here: https://ko-fi.com/thomchantra + +Licence: GPL-3.0-or-later, see LICENSE. diff --git a/docs/install/INSTALL-macOS.txt b/docs/install/INSTALL-macOS.txt new file mode 100644 index 0000000..0b36d97 --- /dev/null +++ b/docs/install/INSTALL-macOS.txt @@ -0,0 +1,42 @@ +@NAME@ @VER@ - installation (macOS) +=================================== + +This zip contains two plug-in formats. Install the one your host uses (or both): + + VST3/@PLUGIN@.vst3 the VST3 plug-in + CLAP/@PLUGIN@.clap the CLAP plug-in + +The build is universal (Apple silicon and Intel). + +1. Unzip the download. +2. VST3: copy VST3/@PLUGIN@.vst3 into + ~/Library/Audio/Plug-Ins/VST3/ + (for all users: /Library/Audio/Plug-Ins/VST3/) +3. CLAP: copy CLAP/@PLUGIN@.clap into + ~/Library/Audio/Plug-Ins/CLAP/ + (for all users: /Library/Audio/Plug-Ins/CLAP/) +4. Rescan plug-ins in your host (or restart it). The plug-in appears as "@NAME@". + +The build is not notarized. If macOS says the plug-in is damaged or from an unidentified +developer, run this in Terminal once (adjust the path to what you installed): + + xattr -dr com.apple.quarantine ~/Library/Audio/Plug-Ins/VST3/@PLUGIN@.vst3 + xattr -dr com.apple.quarantine ~/Library/Audio/Plug-Ins/CLAP/@PLUGIN@.clap + +Your settings and presets +------------------------- + Presets: ~/Library/Application Support/@NAME@/Presets + Themes: ~/Library/Application Support/SatComp/themes.json (shared by SatComp, SatXComp and SatLim) + +Uninstall: delete the files you copied. + +Got issues? +----------- +Found a bug, or something sounds or looks odd? Please submit a bug report on GitHub: + https://github.com/thomchantra/SatComp/issues +Say which plug-in and version, your host (DAW) and operating system, and what you did. A screenshot +or a short description of how to reproduce it helps a lot. + +Enjoying it? You can support the project here: https://ko-fi.com/thomchantra + +Licence: GPL-3.0-or-later, see LICENSE. diff --git a/docs/install/install-linux.sh b/docs/install/install-linux.sh new file mode 100644 index 0000000..ec237d6 --- /dev/null +++ b/docs/install/install-linux.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# @NAME@ @VER@ installer for Linux: copies the VST3 and CLAP plug-ins into your plug-in folders. +# bash install.sh install for you (~/.vst3 and ~/.clap) +# bash install.sh --system install for all users (/usr/local/lib/vst3 and /usr/local/lib/clap, uses sudo) +# bash install.sh --uninstall remove what this script installed +set -e +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +plugin="@PLUGIN@" +name="@NAME@" + +if [ "$1" = "--system" ]; then + vst3_dir=/usr/local/lib/vst3; clap_dir=/usr/local/lib/clap; sudo=sudo +else + vst3_dir="$HOME/.vst3"; clap_dir="$HOME/.clap"; sudo= +fi + +if [ "$1" = "--uninstall" ] || [ "$2" = "--uninstall" ]; then + $sudo rm -rf "$vst3_dir/$plugin.vst3" "$clap_dir/$plugin.clap" + echo "$name removed from $vst3_dir and $clap_dir" + exit 0 +fi + +[ -d "$here/VST3/$plugin.vst3" ] || { echo "Run this script from the unzipped folder (VST3/$plugin.vst3 not found)."; exit 1; } + +$sudo mkdir -p "$vst3_dir" "$clap_dir" +$sudo rm -rf "$vst3_dir/$plugin.vst3" "$clap_dir/$plugin.clap" +$sudo cp -r "$here/VST3/$plugin.vst3" "$vst3_dir/" +$sudo cp "$here/CLAP/$plugin.clap" "$clap_dir/" + +echo "$name @VER@ installed:" +echo " VST3 $vst3_dir/$plugin.vst3" +echo " CLAP $clap_dir/$plugin.clap" +echo "Rescan plug-ins in your host (REAPER: Options > Preferences > Plug-ins > VST/CLAP > Re-scan)." diff --git a/docs/manual/SatComp-Manual-v0.5.2.pdf b/docs/manual/SatComp-Manual-v0.5.2.pdf new file mode 100644 index 0000000..de54adf Binary files /dev/null and b/docs/manual/SatComp-Manual-v0.5.2.pdf differ diff --git a/docs/manual/SatComp.md b/docs/manual/SatComp.md new file mode 100644 index 0000000..5806bb7 --- /dev/null +++ b/docs/manual/SatComp.md @@ -0,0 +1,116 @@ +--- +title: SatComp +version: 0.5.2 +tagline: waveshaping saturator with compressor and 2-stage 3-band EQ +screenshot: ../screenshot.png +--- + +# SatComp 0.5.2 + +A waveshaping saturator with a compressor and a 2-stage 3-band EQ. Give the compressor more spice to squash. Made with bricking intentions. + +![SatComp](../screenshot.png) + +## 1. The idea + +SatComp is a single strip: a saturator that feeds a compressor, an EQ that can sit before or after it, and a true-peak limiter at the end. + +``` +IN > [pre EQ] > SAT > COMP > MIX > [post EQ] > OUT GAIN > LIM > OUT +``` + +The saturator comes first on purpose: driving the shaper changes what the compressor hears, so the harder you saturate, the more there is to squash. + +## 2. Layout + +| Area | What it does | +|---|---| +| Header | logo (themes), preset bar, window scale, oversampling, SIDECHAIN, EQ page, DELTA, BYPASS | +| Saturator (left) | shaper, DRIVE, BIAS, ASYM, HP, LP, TONE, SAT MIX, SAT GAIN and the transfer plot | +| Compressor plot (middle) | transfer curve with the live operating point, the threshold dot and the ratio square | +| Compressor cells | THRESH, RATIO, ATTACK, RELEASE, KNEE, K.SHAPE, PEAK>RMS, LOW CUT, L.AHEAD, SPEED, FF>FB, GR DIST | +| Output column | LIM / TRIM / PK / RMS readouts, GAIN MATCH, IN>OUT, MAKEUP, MIX, OUT GAIN | +| Meters | post-saturator level meter, gain reduction meter, output meter | + +## 3. Saturator + +| Control | What it does | +|---|---| +| Shaper | 15 waveshapers: Tube, Soft, Rational, Atan, Hard, Tri Fold, Sine Fold, Crossover, Cheby, Wrap, Rectify, Bitcrush, Asym Fold, Diode and **Custom** | +| DRIVE | how hard the signal is pushed into the shaper | +| BIAS | shifts the signal off-centre before the shaper: more even harmonics | +| ASYM | how much of the shaper's even-order part is kept. Lowering it stops lopsided curves from dragging DC and sub-bass pulses into the signal. Stored per shaper. | +| HP / LP | decide which part of the signal is saturated; the rest passes clean | +| TONE | low-pass on the shaped signal only | +| SAT MIX | blend between clean and saturated | +| SAT GAIN | level after the saturator, which is also the compressor's input level. Click the **SAT** readout in the plot corner to auto-match it. | +| x1 / x2 / x4 | oversampling of the saturator (less aliasing, more latency) | + +**Custom curve.** Click the pencil icon in the plot corner to draw your own curve (up to 10 points). The symmetry tool draws one half and mirrors the other. + +## 4. Compressor + +| Control | What it does | +|---|---| +| THRESH / RATIO | where compression starts and how much. You can also drag the dot (threshold) and the square (ratio) in the plot. | +| ATTACK / RELEASE | how fast the gain reacts | +| KNEE / K.SHAPE | width and curve of the transition around the threshold | +| PEAK>RMS | detector type: 0 % peak, 100 % RMS | +| LOW CUT | high-pass in the detector only, so kicks and bass stop driving the reduction. The audio is untouched. | +| L.AHEAD | lookahead: the detector sees the signal before the gain is applied, so the compressor is already down when a transient arrives | +| SPEED | scales attack and release together | +| FF>FB | detector topology: 0 % feed-forward, 100 % feedback | +| GR DIST | soft saturation after the gain reduction, growing with how hard the compressor works | + +### Sidechain + +**SIDECHAIN** keys the compressor from the second stereo input, with key gain, HP and LP and a **SOLO** to listen to the key. **KEY MIX** takes the place of FF>FB and blends the key with the signal's own level. Routing belongs to the track, so the switch is saved with the project but not in presets. + +## 5. EQ + +The **EQ** button opens two EQ stages, one before and one after the compressor. Each has three bands plus a tilt, with a live spectrum. Use the pre stage to change what the compressor reacts to, the post stage to refine the tone. + +## 6. Output + +| Control | What it does | +|---|---| +| MAKEUP | gain after the compressor | +| MIX | parallel blend of the processed signal with the dry input | +| OUT GAIN | final level | +| LIM | true-peak brickwall output limiter at -0.2 dBTP, on by default. Its reduction is the LIM readout. | +| GAIN MATCH | measures the loudness change for 3 seconds and stores a trim so processed and dry levels match | +| IN>OUT | net loudness change across the plug-in | +| DELTA | listen to what the compressor removes | +| BYPASS | plain bypass at the plug-in's latency: your dry signal at its own level | + +The **gain reduction meter** on the right shows the compressor's work. **Click** it to cycle its range. The number at the top is the reduction. The thin meter to its left is the level after the saturator; it turns accent for a second when the saturator output passes 0 dBFS. **Click** the output meter's top block to reset the clip lamp and the peak readout. + +**Waveform scope.** Click the icon in the corner of the compressor plot for a half or full wave view of the output with the gain reduction stacked on top (a transient meter). Drag it to change the time window and the ceiling. + +## 7. Recipes + +**Thick drums.** Pick Tube or Diode, drive to 30-40 %, set ASYM to around 50 %, then compress with a fast attack and a medium release. Let the compressor squash what the saturator added. + +**Grit that follows the level.** Raise GR DIST. The distortion grows with how hard the compressor works and vanishes when it is not reducing. + +**Ducking.** Turn SIDECHAIN on and key from a kick. Raise LOW CUT to keep bass from fighting the key. + +## 8. Good to know + +- **Latency** is constant (about 2.2 ms at 48 kHz) and reported to the host, whether the limiter is on or off. +- **Presets:** six Drums presets ship with the plug-in; yours are saved to `SatComp/Presets` in your application-support folder. A name in asterisks means the preset has been modified. +- **Themes:** click the logo for the next scheme, double-click it for dark/light, right-click for the list. The title opens About, Preferences and the changelog. +- **About page:** click the title. **OPEN MANUAL (PDF)** opens this manual. The signal flow is live, and its PRE EQ, POST EQ and LIM blocks are switches you can click to bypass them. +- Double-click any slider to reset it. + +## Support and links + +- Source code, issues and releases: [github.com/thomchantra/SatComp](https://github.com/thomchantra/SatComp) +- Support the project: [ko-fi.com/thomchantra](https://ko-fi.com/thomchantra) + +Found a bug or have an idea? Open an issue on GitHub. Thank you for using SatComp. + +## Notes to check (delete before the PDF) + +- Order of the pre and post EQ relative to the saturator (diagram assumes sat > comp, pre EQ first in the chain). +- Recipe values are suggestions. diff --git a/docs/manual/SatLim-Manual-v0.1.0.pdf b/docs/manual/SatLim-Manual-v0.1.0.pdf new file mode 100644 index 0000000..d584d17 Binary files /dev/null and b/docs/manual/SatLim-Manual-v0.1.0.pdf differ diff --git a/docs/manual/SatLim.md b/docs/manual/SatLim.md new file mode 100644 index 0000000..6c3e422 --- /dev/null +++ b/docs/manual/SatLim.md @@ -0,0 +1,109 @@ +--- +title: SatLim +version: 0.1.0 +tagline: 2-stage clipper / limiter with waveshaping saturator +screenshot: ../screenshot-satlim.png +--- + +# SatLim 0.1.0 + +A 2-stage clipper and limiter with a waveshaping saturator. When you need to nuke it from orbit. + +![SatLim](../screenshot-satlim.png) + +## 1. The idea + +SatLim chews the signal in three steps: a saturator, a hard clipper that bricks the peaks, and a true-peak limiter that catches what the clipper leaves behind. + +``` +IN > SAT (x1-x8) > lift to the ceiling > CLIP > LIMITER > OUT GAIN > OUT +``` + +- **THRESHOLD** is the input level that lands on the ceiling. The signal is lifted by `CEILING - THRESHOLD` dB, so lowering the threshold pushes harder into the clipper and limiter. +- **CLIP** clamps the peaks at the ceiling (oversampled) before the limiter sees them. The more clip, the less the limiter has to do, and the more the transients get bricked. +- **LIMITER** catches the remaining inter-sample peaks. With lookahead on it is a true-peak brickwall. +- **OUT GAIN** is after the limiter on purpose. The ceiling is what the limiter holds; the output gain is free, so you can pull the level back for converters that see inter-sample peaks. + +## 2. Layout + +| Area | What it does | +|---|---| +| Header | logo (themes), preset bar, window scale, DELTA, BYPASS | +| Transient scope | the output with what the limiter and the clipper removed, stacked | +| Scope controls | SRC, WAVE, WIN and CEIL settings under the scope | +| Saturator (left) | shaper, DRIVE, BIAS, ASYM, HP, LP, TONE, SAT MIX, SAT GAIN and the transfer plot | +| Meters (middle) | post-saturator level, gain reduction, output level | +| Right column | OVERSAMPLE, readouts, L.AHEAD, CEILING, THRESHOLD, CLIP, RELEASE, OUT GAIN | + +## 3. Limiter section + +| Control | What it does | +|---|---| +| CEILING | the level the limiter holds | +| THRESHOLD | input level that lands on the ceiling; lower is harder | +| CLIP | 0-100 %. 0 = off. Otherwise a hard clamp at the ceiling, driven up to +6 dB into it. | +| RELEASE | 15-80 ms. A shorter release gives a denser, punchier result and more distortion artifacts; a longer one is smoother with less distortion. | +| L.AHEAD | on: 1.5 ms lookahead with true-peak detection, a brickwall. Off: zero limiter latency, but the gain follows sample peaks, so inter-sample overs can pass. | +| OUT GAIN | final level, after the limiter | +| x1 / x2 / x4 / x8 | oversampling of the saturator and the clipper (more oversampling, less aliasing, more latency) | + +**Balance THRESHOLD and CLIP.** Use THRESHOLD to set how hard the signal hits the ceiling and CLIP to choose how much of that is bricked by the clipper instead of squeezed by the limiter. More clip sounds harder and more distorted; more limiting sounds denser and flatter. + +## 4. Saturator + +| Control | What it does | +|---|---| +| Shaper | 15 waveshapers, from Tube for warm saturation through Tri Fold for destruction to **Custom** | +| DRIVE, BIAS, ASYM, HP, LP, TONE, SAT MIX | the same as in SatComp: push, offset, even-order amount, band split, tone, wet/dry | +| SAT GAIN | level after the saturator. Click the **SAT** readout to auto-match it. | + +**Custom curve.** Click the pencil icon to draw your own transfer curve (up to 10 points), with a symmetry tool for odd curves. + +## 5. Scope and meters + +The **transient scope** shows the output waveform (UI colour) with two things stacked on top: what the limiter removed (solid accent) and what the clipper removed (hatched accent), up to the peak before clipping. Drag the scope to change its window; **CEIL** sets the ceiling of the view (+10 to -14 dB) so heavy clipping above 0 dBFS stays visible. + +| Readout | Meaning | +|---|---| +| GR | limiter gain reduction | +| CLIP | clipper reduction | +| TRU.PK | true peak of the output (8x), whether lookahead is on or off. It turns accent only when it clips. | +| RMS | output level | + +The **gain reduction meter** splits the same way: the limiter's part solid, the clipper's part hatched under it. **Click** it to cycle its range. The output meter's top block holds the clip lamp; **click** it to reset it and the peak readout. + +## 6. Output and tools + +| Control | What it does | +|---|---| +| DELTA | listen to what the clipper and limiter removed | +| BYPASS | plain bypass: your input at the plug-in's latency, at its own level | + +## 7. Recipes + +**Master-bus loudness.** Pick Tube with low drive, a ceiling at -1 dB, THRESHOLD around -4 to -6 dB and a moderate CLIP. Use a release around 40 ms. Pull OUT GAIN down 0.5 dB if you need headroom for the converter. + +**Crunchy drums.** Diode with 30 % drive, x4, lookahead off, a short release and a firmer CLIP. Watch the scope: the hatched part is the clipper doing the work. + +**Brickwall safety.** Keep CLIP at 0, put the ceiling where you want it and use a low threshold only if you want loudness as well as protection. + +## 8. Good to know + +- **Latency** is the saturator oversampler plus the clipper oversampler plus the limiter lookahead. It is reported to the host and changes with the x1-x8 setting and L.AHEAD. +- **Presets:** six factory presets ship with the plug-in; yours are saved to `SatLim/Presets` in your application-support folder. +- **Themes:** click the logo for the next scheme, double-click it for dark/light, right-click for the list. **Preferences** has **SCOPE FILL**: solid bars or an outline. +- **About page:** click the title for the signal flow, **OPEN MANUAL (PDF)**, Preferences and the changelog. +- Double-click any slider to reset it. + +## Support and links + +- Source code, issues and releases: [github.com/thomchantra/SatComp](https://github.com/thomchantra/SatComp) +- Support the project: [ko-fi.com/thomchantra](https://ko-fi.com/thomchantra) + +Found a bug or have an idea? Open an issue on GitHub. Thank you for using SatLim. + +## Notes to check (delete before the PDF) + +- Header cells: DELTA and BYPASS positions; the window-scale cell. +- Scope SRC and WAVE option names. +- Recipe values are suggestions (Master_Loud and Drums_Crunch presets use similar ones). diff --git a/docs/manual/SatXComp-Manual-v0.1.0.pdf b/docs/manual/SatXComp-Manual-v0.1.0.pdf new file mode 100644 index 0000000..88016c6 Binary files /dev/null and b/docs/manual/SatXComp-Manual-v0.1.0.pdf differ diff --git a/docs/manual/SatXComp.md b/docs/manual/SatXComp.md new file mode 100644 index 0000000..f956c09 --- /dev/null +++ b/docs/manual/SatXComp.md @@ -0,0 +1,159 @@ +--- +title: SatXComp +version: 0.1.0 +tagline: 4-band compressor with a waveshaping saturator on every band +screenshot: ../screenshot-satxcomp.png +--- + +# SatXComp 0.1.0 + +A 4-band compressor with a waveshaping saturator on every band and a 5-band EQ. Split the signal, drive each band to taste, then squash it. For surgical baking. + +![SatXComp](../screenshot-satxcomp.png) + +## 1. The idea + +The signal is split into four bands (LO, ML, MH, HI) by three crossovers. Every band has its own **saturator** and **compressor**, and the bands sum back together before the EQ, the output stage and a true-peak limiter. + +``` +IN > [4-band split] > per band: SAT > COMP > mix / gain > [sum] > 5-band EQ > MIX > OUT GAIN > LIM > OUT +``` + +The saturator only adds harmonics inside its own band, so driving the lows hard does not smear the highs. The compressor can reduce gain above the threshold, lift gain below it, or both. + +## 2. Layout + +| Area | What it does | +|---|---| +| Header | logo (themes), preset bar, window scale, SIDECHAIN, EQ page switch, LIM meter | +| Spectrum viewport | live spectrum of the output over the dry signal, crossover lines, one handle per band | +| Band tabs | LO / ML / MH / HI: select a band, switch it on or off, DELTA and SOLO for the selected band | +| Saturator (left) | shaper, DRIVE, BIAS, ASYM, TONE, HP, LP, SAT MIX, SAT GAIN and the transfer plot | +| Meters (middle) | post-saturator level meter of the selected band and its gain meter | +| Compressor (centre) | THRESH, RATIO, ATTACK, RELEASE, mode switch with RANGE, KNEE, K.SHAPE, PEAK>RMS, FF>FB, GR DIST, SPEED, COMP MIX, CMP GAIN | +| Right column | LIM / PK / RMS readouts, XOV1-3, oversampling, L.AHEAD, TRIM, GAIN MATCH, IN>OUT, MIX, OUT GAIN | + +## 3. The spectrum viewport + +The viewport shows the output spectrum drawn over the dry input. + +- **Accent colour:** the compressor took gain away here (output below dry). +- **Inverted accent:** gain was added here (output above dry), from upward compression or a boosting saturator. + +On a neutral grey theme (such as Ashen) the added gain is white, or black on a light scheme. + +**Crossovers.** Drag a dotted line to move that crossover, or use the XOV sliders. Each crossover has its own slope button: 12, 24, 48 or 96 dB per octave. Steeper slopes isolate the bands better; gentler ones sound smoother. The bands sum flat at every setting, and changing a slope crossfades without clicks. + +**Band handles.** Each band has a handle sitting at its threshold: + +- **Drag** it up or down to set the threshold. **Click** it to select the band. **Double-click** resets the threshold. +- The **bar below** the handle is gain reduction (accent colour), 2 px per dB. +- The **bar above** it is gain increase from upward compression, in the inverted accent colour. +- The small **horizontal bar on top** shows the in/out level difference of the band: right = louder, left = quieter. + +## 4. Saturator (per band) + +Select a band with its tab; the saturator and compressor cells show that band. + +| Control | What it does | +|---|---| +| Shaper | 15 waveshapers: Tube, Soft, Rational, Atan, Hard, Tri Fold, Sine Fold, Crossover, Cheby, Wrap, Rectify, Bitcrush, Asym Fold, Diode and **Custom**. Click the name or right-click for the list. | +| DRIVE | how hard the band is pushed into the shaper | +| BIAS | shifts the signal off-centre before the shaper: more even harmonics | +| ASYM | how much of the shaper's even-order part is kept (100 % = all). Lowering it keeps lopsided curves from dragging DC and sub-bass pulses into the signal. Stored per shaper. | +| TONE | low-pass on the shaped signal only, to tame the harmonics | +| HP / LP | high-pass and low-pass that decide which part of the band is saturated; the rest passes clean | +| SAT MIX | blend between clean and saturated band | +| SAT GAIN | level after the saturator. Click the **SAT** readout in the plot corner to auto-match: it measures for 3 seconds and sets the SAT GAIN that cancels the loudness change. Click again to cancel. | + +**Custom curve.** Click the pencil icon in the plot corner to draw your own transfer curve (up to 10 points). The symmetry tool draws one half and mirrors the other, which keeps the curve odd and DC-free. Each band keeps its own custom curve. + +## 5. Compressor (per band) + +| Control | What it does | +|---|---| +| THRESH | level where compression starts (also the band handle) | +| RATIO | amount of compression above (and, upward, below) the threshold | +| ATTACK / RELEASE | how fast the gain reacts. Slower suits low bands, faster suits high bands. | +| KNEE / K.SHAPE | width and curve of the transition around the threshold | +| PEAK>RMS | detector type: 0 % peak, 100 % RMS | +| FF>FB | detector topology: 0 % feed-forward, 100 % feedback (replaced by KEY MIX with the sidechain on) | +| GR DIST | soft saturation after the gain reduction, growing with how hard the compressor works | +| SPEED | scales attack and release together: lower is faster, higher is slower | +| COMP MIX | parallel blend of the compressed and uncompressed band | +| CMP GAIN | makeup gain of the band | + +### Compressor mode + +The switch above RANGE steps through three modes (click or wheel): + +- **DWNWARD:** the ordinary compressor: reduces gain above the threshold. +- **UPWARD:** lifts what is below the threshold toward it by the ratio, never more than **RANGE** dB. Quiet detail comes up; loud parts are untouched. +- **UP/DWN:** both from the same threshold: lifts below, reduces above. + +RANGE is dim in DWNWARD because it only limits the lift. + +### Gain meter + +The vertical meter next to the compressor cells shows the selected band. In DWNWARD it shows reduction. In UPWARD and UP/DWN it is centre-tapped: lift grows upward in the inverted accent, reduction grows downward in the accent. **Click** it to cycle its range (3, 6, 12, 18 dB). The number window at the top shows the lift; in UP/DWN a second window at the bottom shows the reduction. + +## 6. Sidechain + +Switch **SIDECHAIN** on to key the compressors from the plug-in's second stereo input (route a track's send to input 3/4 in your host). The key is conditioned (SC gain, HP, LP), split across the four bands and drives each band's compressor, so it ducks like a dynamic EQ: only the band the key excites gets reduced. + +- **KEY MIX** (replaces FF>FB while sidechain is on) blends the key with the band's own level. +- **SOLO** lets you listen to the key as the detector hears it. +- The SIDECHAIN button is white when the host supplies a bus, and in the accent colour when it is on without one. + +Sidechain routing belongs to the track, so it is saved with the project but not in presets. + +## 7. EQ page + +The **EQ** button swaps the viewport for a 5-band post-compressor EQ with a live spectrum. Each band can be a bell, shelf, notch, bandpass or allpass; there is also a tilt control. Use the EQ's own mix to blend the filtered signal with the dry one, which is how the notch, bandpass and allpass types become useful for sculpting. The EQ page shows its own IN>OUT difference (I>O). + +## 8. Output section + +| Control | What it does | +|---|---| +| MIX | blend of the processed signal with the dry input | +| OUT GAIN | final level | +| LIM | the output limiter: a true-peak brickwall at -0.2 dBTP, on by default. Its reduction shows in the LIM readout. | +| x1 / x2 / x4 | oversampling for the saturators | +| L.AHEAD | lookahead for the compressors | +| GAIN MATCH | measures the loudness change over 3 seconds and sets a trim so bypassed and processed levels match | +| IN>OUT | net loudness change across the plug-in | +| DELTA | listen to what the selected band (or the whole chain) removes | +| BYPASS | plain bypass at the plug-in's latency: your dry signal at its own level | + +## 9. Recipes + +**Heavy low end without a muddy top.** Set XOV1 near 150 Hz at 24 dB. Drive LO with Tube, set ASYM to around 50 % and a slow attack and release. Leave the other bands clean. + +**Dynamic EQ ducking.** Turn SIDECHAIN on, route the key (for example a kick) to the second input and solo the band you want to duck. Use a fast attack and release, then trim with KEY MIX. + +**Bring up the room.** Set a band to UPWARD with a low threshold, RANGE around 6 dB and a gentle ratio. Quiet tails come up; peaks stay put. Watch the bar above the band handle. + +**Glue the whole mix.** Use 12 dB crossovers, a low ratio on every band and a slow release, then raise COMP MIX to taste. + +## 10. Good to know + +- **Latency** is constant and reported to the host. Switching the limiter or bands never changes it. +- **Presets:** four factory presets ship with the plug-in. Your own are saved to `SatXComp/Presets` in your application-support folder. A name wrapped in asterisks means the preset has been modified. Presets keep the bands, curves and EQ, but not the sidechain routing or bypass. +- **Themes:** click the logo for the next theme, double-click it for dark/light, right-click for the list. The title opens About, Preferences and the changelog. +- **About page:** click the title. Besides the changelog and **OPEN MANUAL (PDF)**, the signal flow is live: dots show the level, bands light up while they work, and each band block, EQ, LIM and the SIDECHAIN box are switches you can click to bypass them. +- **Shortcuts:** double-click any slider to reset it. + +## Support and links + +- Source code, issues and releases: [github.com/thomchantra/SatComp](https://github.com/thomchantra/SatComp) +- Support the project: [ko-fi.com/thomchantra](https://ko-fi.com/thomchantra) + +Found a bug or have an idea? Open an issue on GitHub. Thank you for using SatXComp. + +## Notes to check (delete before the PDF) + +- Window scale: the cell next to the preset bar is the scale; confirm it is click-to-cycle. +- EQ filter types and the EQ's MIX / tilt wording. +- "Click it to cycle its range (3, 6, 12, 18 dB)" for the gain meter. +- The routing hint "input 3/4" is the usual host convention; confirm for REAPER. +- Recipe parameter values are suggestions, not tested presets. diff --git a/docs/manual/build.py b/docs/manual/build.py new file mode 100644 index 0000000..bf4be55 --- /dev/null +++ b/docs/manual/build.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Build the manual PDFs: docs/manual/.md -> docs/manual/-Manual-v.pdf + +A4, solid black pages, white Fira Code. Needs `pip install weasyprint markdown` (and pango: `brew install pango`; +on macOS run with DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib). Usage: build.py [Plugin ...] (default: all) +The section "## Notes to check ..." is the author's review list and is dropped from the PDF. +""" +import pathlib, re, sys +import markdown +from weasyprint import HTML + +HERE = pathlib.Path(__file__).resolve().parent +FONTS = HERE.parent.parent / "Fonts" / "Fira_Code_v6.2" / "ttf" + +CSS = """ +@font-face { font-family: 'Fira Code'; font-weight: 400; src: url('%(f)s/FiraCode-Regular.ttf'); } +@font-face { font-family: 'Fira Code'; font-weight: 700; src: url('%(f)s/FiraCode-Bold.ttf'); } +@page { + size: A4; margin: 18mm 16mm 20mm 16mm; background: #000; + @bottom-left { content: '%(title)s %(version)s'; font: 7.5pt 'Fira Code'; color: #888; } + @bottom-right { content: counter(page); font: 7.5pt 'Fira Code'; color: #888; } +} +@page :first { @bottom-left { content: ''; } @bottom-right { content: ''; } } +html { background: #000; color: #fff; font: 8.6pt/1.5 'Fira Code', monospace; } +body { margin: 0; } +h1 { font-size: 22pt; margin: 0 0 4mm; padding: 2mm 3mm; background: #fff; color: #000; } +h2 { font-size: 11.5pt; margin: 8mm 0 2.5mm; padding-bottom: 1mm; border-bottom: 1.5px solid #fff; page-break-after: avoid; } +h3 { font-size: 9.6pt; margin: 5mm 0 1.5mm; page-break-after: avoid; } +h3::before { content: '> '; } +p { margin: 0 0 2.5mm; } +em { font-style: normal; text-decoration: underline; } +strong { font-weight: 700; } +a { color: #fff; } +img { display: block; max-width: 100%%; max-height: 118mm; width: auto; height: auto; margin: 4mm auto; border: 1px solid #555; } +code { font: inherit; border: 1px solid #555; padding: 0 1mm; } +pre { border: 1px solid #fff; padding: 2.5mm 3mm; margin: 2mm 0 4mm; white-space: pre-wrap; page-break-inside: avoid; } +pre code { border: 0; padding: 0; } +ul, ol { margin: 0 0 3mm; padding-left: 5mm; } +li { margin-bottom: 1mm; } +table { width: 100%%; border-collapse: collapse; margin: 2mm 0 4mm; font-size: 8pt; } +th { background: #fff; color: #000; text-align: left; padding: 1mm 2mm; } +td { border: 1px solid #555; padding: 1mm 2mm; vertical-align: top; } +tr { page-break-inside: avoid; } +td:first-child { white-space: nowrap; font-weight: 700; } +.tagline { color: #bbb; margin: -2mm 0 4mm; } +""" + +def split_front(text): + m = re.match(r"---\n(.*?)\n---\n", text, re.S) + meta = dict(l.split(": ", 1) for l in m.group(1).splitlines()) if m else {} + return meta, text[m.end():] if m else text + +def build(md_path): + meta, body = split_front(md_path.read_text()) + body = re.split(r"\n## Notes to check", body)[0] + html = markdown.markdown(body, extensions=["tables", "fenced_code"]) + # the tagline goes right under the first heading + html = html.replace("", "\n

%s

" % meta.get("tagline", ""), 1) + css = CSS % {"f": FONTS.as_uri(), "title": meta["title"], "version": "v" + meta["version"]} + out = md_path.with_name("%s-Manual-v%s.pdf" % (meta["title"], meta["version"])) + HTML(string="%s" % html, base_url=str(md_path.parent) + "/").write_pdf(out, stylesheets=[__import__("weasyprint").CSS(string=css)]) + print("wrote", out.name) + +if __name__ == "__main__": + names = sys.argv[1:] or ["SatComp", "SatXComp", "SatLim"] + for n in names: + build(HERE / (n + ".md")) diff --git a/docs/releases/v0.5.2.md b/docs/releases/v0.5.2.md new file mode 100644 index 0000000..af9dde1 --- /dev/null +++ b/docs/releases/v0.5.2.md @@ -0,0 +1,44 @@ +This release bundles three plug-ins. SatComp gains an output true-peak limiter and a post-saturator level meter (and was reorganised underneath), and SatXComp and SatLim make their first appearance. + +| Plug-in | Version | What | +|---|---|---| +| SatComp | 0.5.2 | output limiter, post-sat meter, engine reorganised | +| SatXComp | 0.1.0 | new: 4-band multiband compressor with a saturator per band (upward modes too) and a 5-band post EQ | +| SatLim | 0.1.0 | new: saturator into an oversampled clipper and a true-peak limiter | + +Each zip is named with its plug-in's own version. From now on a single plug-in update is released under its own tag (`satxcomp-v...`, `satlim-v...`) instead of bumping SatComp. + +## New plug-ins +- **SatXComp 0.1.0:** four bands (LO, ML, MH, HI) split by three Linkwitz-Riley crossovers with 12, 24, 48 or 96 dB slopes. Each band has a band-limited saturator, a compressor with DWNWARD, UPWARD (lift) or UP/DWN modes, solo and delta, and its own SAT GAIN match. Sidechain key split across the bands, a 5-band post EQ, a true-peak output limiter, a waveform scope, and four factory presets. The spectrum shows gain reduction in the accent colour and gain increase in its inverse. +- **SatLim 0.1.0:** the SatComp saturator (x1 to x8) into an oversampled clip and a true-peak brickwall limiter with optional lookahead, a transient scope with the limiter's and the clipper's removal stacked, an 8x TRU.PK readout, and six factory presets. + +## New in SatComp +- **Output limiter (LIM button, on by default).** A true-peak brickwall at -0.2 dBTP for the end of the chain, so inter-sample peaks do not slip past a limiter downstream. 4x oversampled detection, 1.5 ms lookahead, program-dependent release. Its gain reduction is the `LIM` readout in the output column; the compressor GR number moved to the top of the GR meter. The switch is saved with presets and the project. +- **Constant extra latency of about 2.2 ms at 48 kHz**, reported to the host whether the limiter is on or off (so toggling never shifts the track). +- **Thin post-saturator level meter** between the saturator and compressor cells; the whole meter turns accent for 1 s when the saturator output passes 0 dBFS. +- **Signal flow** on the About page shows the limiter. +- **INIT starts with drive 0 and threshold 0.** +- **Better saturator (ASYM).** The even-order part of the waveshaper no longer drags DC and sub-bass pulses into the signal, so lopsided shapers and custom curves keep their grit with calmer peaks. The new ASYM slider under the plot sets how much of the even part each shaper keeps (stored per shaper, saved with presets and projects). INIT sounds slightly cleaner in the lows with Tube, Diode, Rectify, Asym Fold and Custom. +- **Limiter retune.** A hard clip at the ceiling in front of the gain stage takes tall peaks so the body is not ducked, and the release range is 15-80 ms. +- **SAT GAIN.** The saturator's OUT GAIN cell is renamed SAT GAIN (same parameter, presets unchanged). + +## Install and manuals +- **Linux (experimental).** Every plug-in also comes as a Linux x64 zip (VST3 and CLAP) with an `install.sh` that copies them into `~/.vst3` and `~/.clap`. It is new and lightly tested: it needs an X11 session, and the meters and the transient scope can stutter on some systems (a fix is planned). Please report what you find. +- **Easier install.** Each zip now mirrors the install folders: `VST3/.vst3` (on Windows the whole `.vst3` folder, do not open it), `CLAP/.clap`, an `INSTALL.txt` for your system, the licence and the manual. Copy the contents to the usual VST3 and CLAP folders. +- **A manual for every plug-in** (PDF, in each zip and attached to this release), also reachable from inside the plug-in: click the title, then **OPEN MANUAL (PDF)** on the About tab. The sources are in `docs/manual/`. +- **Live signal flow on the About tab.** Dots show the level and stages light up while they work. The blocks are switches: in SatXComp the bands, EQ, LIM and SIDECHAIN, in SatComp PRE EQ, POST EQ and LIM. SatXComp's flow shows each band's compressor mode (down, up or both). + +## Changed +- **Engine split into blocks.** The saturator, compressor, sidechain key input and EQ stages are now separate, reusable pieces; the SatComp engine only wires them together. Rendering 101 test scenarios (every shaper and oversampling mode, compressor, EQ, sidechain, bypass, delta, gain match, automation, other sample rates) through v0.5.1 and v0.5.2 gives bit-identical audio and meter values (the limiter-era check shifts by the new latency; bypass, delta and sidechain-solo control timing is 2 ms earlier). +- **BYPASS is a plain bypass (SatComp and SatXComp).** The loudness-matched bypass of v0.3-0.5.1 is retired: it scaled the dry input to the processed RMS, which with a hot saturator and no limiter in the path could peak up to +10 dB. Bypass now returns the dry input at its own level, like SatLim's, and the BYP readout is gone. Bypass audio differs from v0.5.1; everything else renders identically. +- **Shared UI toolkit.** The drawing canvas, colour schemes, fonts and the slider/button widget kit moved into their own crate. A scripted 460-frame render of the editor (sliders, EQ page, About, Appearance, menus, scope, presets) drew identically to v0.5.1 before the limiter work changed the layout. +- The About > Changelog page has a v0.5.2 entry. + +- **Theme gain colour.** Where a spectrum or meter shows gain added (SatXComp), the colour is the accent's inverse and keeps its hue on every colour theme; only truly neutral themes such as Ashen use white (black in light mode). + +## Notes +- Parameter ids, presets, projects and `themes.json` are unchanged: a v0.5.1 preset or project loads the same, with the limiter switched on (it did not exist before). A v0.5.1 project will sound the same except for peaks above -0.2 dBTP, and the track is delayed by the new latency (compensated by the host). +- AU is shelved for now (no demand yet). +- CPU use is unchanged within measurement noise (about 0.3-0.7% of one core at 48 kHz); the limiter's interpolator only runs while the signal is loud enough to matter. + +Full changelog: https://github.com/thomchantra/satcomp/compare/v0.5.1...v0.5.2 diff --git a/docs/screenshot-satlim.png b/docs/screenshot-satlim.png new file mode 100644 index 0000000..0f0a61d Binary files /dev/null and b/docs/screenshot-satlim.png differ diff --git a/docs/screenshot-satxcomp.png b/docs/screenshot-satxcomp.png new file mode 100644 index 0000000..695454a Binary files /dev/null and b/docs/screenshot-satxcomp.png differ diff --git a/docs/screenshot.png b/docs/screenshot.png index d07f9e7..8718e73 100644 Binary files a/docs/screenshot.png and b/docs/screenshot.png differ diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 4ae2225..edc777a 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -2294,7 +2294,7 @@ dependencies = [ [[package]] name = "satcomp" -version = "0.5.1" +version = "0.5.2" dependencies = [ "include_dir", "nih_plug", @@ -2302,13 +2302,70 @@ dependencies = [ "parking_lot", "rfd", "satcomp-dsp", + "satcomp-ui", "serde", "serde_json", ] [[package]] name = "satcomp-dsp" -version = "0.5.1" +version = "0.5.2" + +[[package]] +name = "satcomp-ui" +version = "0.5.2" +dependencies = [ + "nih_plug", + "nih_plug_egui", + "serde", + "serde_json", +] + +[[package]] +name = "satlim" +version = "0.1.0" +dependencies = [ + "include_dir", + "nih_plug", + "nih_plug_egui", + "parking_lot", + "rfd", + "satcomp-dsp", + "satcomp-ui", + "satlim-dsp", + "serde", + "serde_json", +] + +[[package]] +name = "satlim-dsp" +version = "0.1.0" +dependencies = [ + "satcomp-dsp", +] + +[[package]] +name = "satxcomp" +version = "0.1.0" +dependencies = [ + "include_dir", + "nih_plug", + "nih_plug_egui", + "parking_lot", + "rfd", + "satcomp-dsp", + "satcomp-ui", + "satxcomp-dsp", + "serde", + "serde_json", +] + +[[package]] +name = "satxcomp-dsp" +version = "0.1.0" +dependencies = [ + "satcomp-dsp", +] [[package]] name = "scopeguard" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 3fb8e92..55bd414 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["satcomp-dsp", "satcomp-plugin", "xtask"] +members = ["satcomp-dsp", "satcomp-ui", "satcomp-plugin", "satxcomp-dsp", "satxcomp-plugin", "satlim-dsp", "satlim-plugin", "xtask"] exclude = ["vendor"] resolver = "2" diff --git a/rust/satcomp-dsp/Cargo.toml b/rust/satcomp-dsp/Cargo.toml index 0f9040e..fdb02e7 100644 --- a/rust/satcomp-dsp/Cargo.toml +++ b/rust/satcomp-dsp/Cargo.toml @@ -1,7 +1,11 @@ [package] name = "satcomp-dsp" -version = "0.5.1" +version = "0.5.2" edition = "2021" publish = false [dependencies] + +[features] +# dev-only: environment-variable overrides of the limiter constants (offline sweeps) +tune = [] diff --git a/rust/satcomp-dsp/examples/golden.rs b/rust/satcomp-dsp/examples/golden.rs new file mode 100644 index 0000000..b839584 --- /dev/null +++ b/rust/satcomp-dsp/examples/golden.rs @@ -0,0 +1,95 @@ +//! Golden-render tool. +//! +//! golden render render every scenario to /.f32 + .txt (telemetry), print a summary +//! golden diff [shift] +//! compare two render folders: max |diff|, differing samples, telemetry equality. +//! With `shift` (stereo samples) B is compared with its first `shift` samples dropped, for +//! a change that only added constant latency (A[i] must equal B[i + shift]). +//! golden record rewrite tests/golden/golden.txt from the current build +//! +//! Build it once against the stable tag and once against the refactor, render both, diff. +//! `render` honours GOLDEN_ONLY= to run a subset. + +#[path = "../tests/golden/scen.rs"] +mod scen; + +use std::fs; +use std::path::Path; + +fn main() { + let a: Vec = std::env::args().collect(); + match a.get(1).map(String::as_str) { + Some("render") => { + let dir = Path::new(&a[2]); + fs::create_dir_all(dir).unwrap(); + let only = std::env::var("GOLDEN_ONLY").ok(); + for sc in scen::scenarios() { + if only.as_ref().map_or(false, |o| !sc.name.contains(o.as_str())) { + continue; + } + let o = scen::render(&sc); + let bytes: Vec = o.audio.iter().flat_map(|s| s.to_bits().to_le_bytes()).collect(); + fs::write(dir.join(format!("{}.f32", sc.name)), bytes).unwrap(); + let txt: String = o.telem.iter().map(|(k, v)| format!("{k} {v:016x}\n")).collect(); + fs::write(dir.join(format!("{}.txt", sc.name)), txt).unwrap(); + let (ha, ht, rms, pk) = scen::summarize(&o); + println!("{:34} audio {ha:016x} telem {ht:016x} rms {rms:.6} pk {pk:.6}", sc.name); + } + } + Some("diff") => diff(Path::new(&a[2]), Path::new(&a[3]), a.get(4).and_then(|v| v.parse().ok()).unwrap_or(0)), + Some("record") => { + let mut out = String::from("# name audio-hash telemetry-hash rms peak (cargo run --release -p satcomp-dsp --example golden -- record)\n"); + for sc in scen::scenarios() { + let o = scen::render(&sc); + let (ha, ht, rms, pk) = scen::summarize(&o); + out += &format!("{} {ha:016x} {ht:016x} {rms:.12e} {pk:.12e}\n", sc.name); + } + fs::write(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/golden/golden.txt"), out).unwrap(); + println!("wrote tests/golden/golden.txt"); + } + _ => eprintln!("usage: golden render | diff | record"), + } +} + +fn diff(a: &Path, b: &Path, shift: usize) { + let mut names: Vec = fs::read_dir(a) + .unwrap() + .filter_map(|e| e.ok()) + .filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".f32").map(String::from))) + .collect(); + names.sort(); + let (mut same, mut total) = (0, 0); + println!("{:34} {:>12} {:>10} {:>10} telemetry", "scenario", "max|diff|", "differing", "samples"); + for n in &names { + total += 1; + let rd = |d: &Path| -> Vec { + fs::read(d.join(format!("{n}.f32"))) + .map(|v| v.chunks_exact(4).map(|c| f32::from_bits(u32::from_le_bytes([c[0], c[1], c[2], c[3]]))).collect()) + .unwrap_or_default() + }; + let (x, y) = (rd(a), rd(b)); + let mut max = 0.0f64; + let mut cnt = 0usize; + if x.len() != y.len() { + println!("{n:34} LENGTH DIFFERS {} vs {}", x.len(), y.len()); + continue; + } + let sh = shift * 2; + let (x, y) = (&x[..x.len().saturating_sub(sh)], &y[sh.min(y.len())..]); + for (p, q) in x.iter().zip(y) { + if p.to_bits() != q.to_bits() { + cnt += 1; + max = max.max((*p as f64 - *q as f64).abs()); + } + } + let ta = fs::read_to_string(a.join(format!("{n}.txt"))).unwrap_or_default(); + let tb = fs::read_to_string(b.join(format!("{n}.txt"))).unwrap_or_default(); + let tdiff: Vec<&str> = ta.lines().zip(tb.lines()).filter(|(p, q)| p != q).map(|(p, _)| p.split(' ').next().unwrap_or("")).collect(); + let tel = if ta == tb { "identical".to_string() } else { format!("DIFFERS in {} ({} lines; first: {})", tdiff.len(), tdiff.len(), tdiff.first().unwrap_or(&"-")) }; + if cnt == 0 && (ta == tb || shift > 0) { + same += 1; + } + println!("{n:34} {max:12.3e} {cnt:10} {:10} {tel}", x.len()); + } + println!("\n{same}/{total} scenarios bit-identical (audio and telemetry)"); +} diff --git a/rust/satcomp-dsp/src/biquad.rs b/rust/satcomp-dsp/src/biquad.rs index d092015..3c72a6e 100644 --- a/rust/satcomp-dsp/src/biquad.rs +++ b/rust/satcomp-dsp/src/biquad.rs @@ -71,13 +71,40 @@ pub fn high_shelf(f: f64, g: f64, q: f64, sr: f64) -> Coef { ] } -/// Filter kinds: 0 HPF, 1 LPF, 2 low shelf, 3 high shelf, 4 bell. +/// RBJ all-pass (unity magnitude, phase turns through 180 degrees at `f`). +pub fn allpass(f: f64, q: f64, sr: f64) -> Coef { + let w = w0(f, sr); + let (cs, al) = (w.cos(), w.sin() / (2.0 * q)); + let a0 = 1.0 + al; + [(1.0 - al) / a0, -2.0 * cs / a0, (1.0 + al) / a0, -2.0 * cs / a0, (1.0 - al) / a0] +} + +/// RBJ band-pass, constant 0 dB peak gain. +pub fn bandpass(f: f64, q: f64, sr: f64) -> Coef { + let w = w0(f, sr); + let (cs, al) = (w.cos(), w.sin() / (2.0 * q)); + let a0 = 1.0 + al; + [al / a0, 0.0, -al / a0, -2.0 * cs / a0, (1.0 - al) / a0] +} + +/// RBJ notch. +pub fn notch(f: f64, q: f64, sr: f64) -> Coef { + let w = w0(f, sr); + let (cs, al) = (w.cos(), w.sin() / (2.0 * q)); + let a0 = 1.0 + al; + [1.0 / a0, -2.0 * cs / a0, 1.0 / a0, -2.0 * cs / a0, (1.0 - al) / a0] +} + +/// Filter kinds: 0 HPF, 1 LPF, 2 low shelf, 3 high shelf, 4 bell, 5 all-pass, 6 band-pass, 7 notch. pub fn eq_coef(kind: u8, f: f64, g: f64, q: f64, sr: f64) -> Coef { match kind { 0 => hp(f, q, sr), 1 => lp(f, q, sr), 2 => low_shelf(f, g, q, sr), 3 => high_shelf(f, g, q, sr), + 5 => allpass(f, q, sr), + 6 => bandpass(f, q, sr), + 7 => notch(f, q, sr), _ => peaking(f, g, q, sr), } } @@ -115,6 +142,21 @@ mod tests { assert!((mag_db(&high_shelf(4000.0, 6.0, 0.7, SR), w(20000.0)) - 6.0).abs() < 0.3); } + #[test] + fn allpass_bandpass_notch_shapes() { + let w = |f: f64| 2.0 * PI * f / SR; + let ap = allpass(1000.0, 0.7, SR); + for f in [50.0, 1000.0, 9000.0] { + assert!(mag_db(&ap, w(f)).abs() < 0.01); + } + let bp = bandpass(1000.0, 2.0, SR); + assert!(mag_db(&bp, w(1000.0)).abs() < 0.05); + assert!(mag_db(&bp, w(100.0)) < -15.0 && mag_db(&bp, w(10000.0)) < -15.0); + let nt = notch(1000.0, 2.0, SR); + assert!(mag_db(&nt, w(1000.0)) < -40.0); + assert!(mag_db(&nt, w(100.0)).abs() < 0.5 && mag_db(&nt, w(10000.0)).abs() < 0.5); + } + #[test] fn identity_passes_through() { let mut s = [0.0; 2]; diff --git a/rust/satcomp-dsp/src/compressor.rs b/rust/satcomp-dsp/src/compressor.rs new file mode 100644 index 0000000..82a1dec --- /dev/null +++ b/rust/satcomp-dsp/src/compressor.rs @@ -0,0 +1,399 @@ +//! The compressor block: peak/RMS detector with optional low cut, feed-forward/feedback blend, optional external key +//! (blended with the main detector level), static gain computer, attack/release ballistics with auto-release, and +//! gain-reduction distortion. The detector listens to one signal and the gain is applied to another, so lookahead (and a +//! parallel dry path) are the caller's business. Stereo, f64. + +use crate::biquad::{self, bq, Coef}; +use crate::level::{one_pole, DB_AMP, LN10_20}; +use crate::DENORM; + +/// Static gain computer: returns GR in dB (>= 0) for a level in dB. C1 knee, quad -> smoothstep -> smootherstep. +#[derive(Clone, Copy, Debug)] +pub struct GainComputer { + pub thr: f64, + pub knw: f64, + pub cslope: f64, + pub kc0: f64, + pub kc1: f64, + pub kc2: f64, +} + +impl Default for GainComputer { + fn default() -> Self { + Self { thr: -18.0, knw: 6.0, cslope: 0.75, kc0: 1.0, kc1: 0.0, kc2: 0.0 } + } +} + +impl GainComputer { + pub fn from_params(p: &CompParams) -> Self { + let inv_r = if p.ratio >= 19.9 { 0.0 } else { 1.0 / p.ratio }; + let sh2 = p.knee_shape * 0.02; + let (kc0, kc1, kc2) = if sh2 <= 1.0 { (1.0 - sh2, sh2, 0.0) } else { (0.0, 2.0 - sh2, sh2 - 1.0) }; + Self { thr: p.thresh, knw: p.knee, cslope: 1.0 - inv_r, kc0, kc1, kc2 } + } + + #[inline] + pub fn gr(&self, x: f64) -> f64 { + let d = x - self.thr; + if self.knw > 0.001 { + if d <= -self.knw * 0.5 { + 0.0 + } else if d >= self.knw * 0.5 { + d * self.cslope + } else { + let u = (d + self.knw * 0.5) / self.knw; + let (u2, u3) = (u * u, u * u * u); + let u4 = u2 * u2; + let g = self.kc0 * u2 * 0.5 + self.kc1 * (u3 - u4 * 0.5) + self.kc2 * (u4 * u2 - 3.0 * u4 * u + 2.5 * u4); + self.cslope * self.knw * g + } + } else if d > 0.0 { + d * self.cslope + } else { + 0.0 + } + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct CompParams { + /// dB + pub thresh: f64, + /// 1..20 (>= 19.9 = inf) + pub ratio: f64, + /// ms + pub attack: f64, + /// ms (>= 1990 = auto) + pub release: f64, + /// 0..100 % + pub speed: f64, + /// dB + pub knee: f64, + /// 0..100 % + pub knee_shape: f64, + /// 0..100 % (peak > rms) + pub detector: f64, + /// 0..400 Hz (<= 15 = off) + pub det_hp: f64, + /// 0..100 % feed-forward > feedback + pub ff_fb: f64, + /// 0..100 % + pub gr_dist: f64, + /// 0..100 %: external key vs main detector level when a key is supplied (0 = main only, 100 = key only) + pub key_mix: f64, + /// upward: signals BELOW the threshold are lifted (ratio and knee as in the downward mode, mirrored around the threshold). + /// With `down` off nothing above the threshold is touched; with both on the band lifts below and reduces above the same + /// threshold. The default (up off, down on) is the ordinary downward compressor, bit-identical. + pub up: bool, + /// reduce what is above the threshold (the ordinary compressor); only meaningful together with `up` (without `up` it is + /// always on) + pub down: bool, + /// dB: the most the upward mode lifts + pub up_range: f64, +} + +impl Default for CompParams { + fn default() -> Self { + Self { + thresh: -18.0, + ratio: 4.0, + attack: 10.0, + release: 150.0, + speed: 50.0, + knee: 6.0, + knee_shape: 0.0, + detector: 30.0, + det_hp: 0.0, + ff_fb: 0.0, + gr_dist: 0.0, + key_mix: 100.0, + up: false, + down: true, + up_range: 12.0, + } + } +} + +/// What one `Compressor::tick` produced. +#[derive(Clone, Copy, Debug)] +pub struct CompOut { + /// the compressed signal (gain applied to the `sig` input, with GR distortion) + pub y: [f64; 2], + /// gain reduction per channel, dB (0 in the upward mode) + pub g: [f64; 2], + /// gain lift per channel, dB (>= 0, only in the upward mode) + pub lift: [f64; 2], + /// loudest detector level (linear) + pub level: f64, +} + +#[derive(Default)] +pub struct Compressor { + gc: GainComputer, + a_att: f64, + auto_rel: bool, + a_rel_f: f64, + a_rel_s: f64, + rms_c: f64, + pk_d: f64, + ms_c: f64, + avg_c: f64, + det_m: f64, + use_dhp: bool, + dhc: Coef, + dhs: [[f64; 2]; 2], + fb: f64, + gdist: f64, + key_mix: f64, + prev: [f64; 2], + rm: [f64; 2], + rm_k: [f64; 2], + dhs_k: [[f64; 2]; 2], + grf: [f64; 2], + grs: [f64; 2], + pk_env: f64, + ms_env: f64, + gavg: f64, + up: bool, + down: bool, + up_range: f64, + /// smoothed gain lift per channel (upward mode) + gl: [f64; 2], +} + +impl Compressor { + pub fn new() -> Self { + Self { dhc: biquad::IDENTITY, ..Default::default() } + } + + pub fn gain_computer(&self) -> GainComputer { + self.gc + } + + pub fn derive(&mut self, p: &CompParams, sr: f64) { + if p.up != self.up || p.down != self.down { + // the two modes keep separate ballistics state: start the new mode from unity + self.gl = [0.0; 2]; + self.grf = [0.0; 2]; + self.grs = [0.0; 2]; + self.gavg = 0.0; + } + self.up = p.up; + self.down = p.down; + self.up_range = p.up_range.max(0.0); + self.gc = GainComputer::from_params(p); + let spd = 4f64.powf((p.speed - 50.0) / 50.0); + self.a_att = 1.0 - (-1.0 / (sr * (p.attack * 0.001 * spd).max(0.00001))).exp(); + self.auto_rel = p.release >= 1990.0; + let a_rel = 1.0 - (-1.0 / (sr * (p.release * 0.001 * spd).max(0.00001))).exp(); + self.a_rel_f = if self.auto_rel { 1.0 - (-1.0 / (sr * 0.04 * spd)).exp() } else { a_rel }; + self.a_rel_s = 1.0 - (-1.0 / (sr * 0.6 * spd)).exp(); + self.rms_c = one_pole(sr, 0.01); + self.pk_d = (-1.0 / (sr * 0.05)).exp(); + self.ms_c = one_pole(sr, 0.3); + self.avg_c = one_pole(sr, 0.25); + self.det_m = p.detector * 0.01; + self.use_dhp = p.det_hp > 15.0; + if self.use_dhp { + self.dhc = biquad::hp(p.det_hp, 0.70710678, sr); + } + self.fb = p.ff_fb * 0.01; + self.key_mix = (p.key_mix * 0.01).clamp(0.0, 1.0); + self.gdist = p.gr_dist * 0.01; + } + + /// `det` = what the detector listens to, `sig` = what the gain is applied to (the detector signal delayed by the + /// lookahead), `key` = external key when one is active (replaces feed-forward/feedback with the key mix). + #[inline] + pub fn tick(&mut self, det: [f64; 2], sig: [f64; 2], key: Option<[f64; 2]>) -> CompOut { + let mut lv = [0.0f64; 2]; + for c in 0..2 { + // KEY MIX: detector level = (1-m) * main + m * key (levels, not audio, so the two never phase-interact). + // Without an active key m = 0. With one, FF>FB is not applied (it is replaced by KEY MIX). + let km = if key.is_some() { self.key_mix } else { 0.0 }; + let mut l = 0.0; + if km < 1.0 { + let xd = if key.is_some() { det[c] } else { det[c] + self.fb * (self.prev[c] - det[c]) }; + l += (1.0 - km) * det_level(xd, &mut self.rm[c], &mut self.dhs[c], self.use_dhp, &self.dhc, self.det_m, self.rms_c); + } + if km > 0.0 { + let k = key.unwrap_or([0.0; 2]); + l += km * det_level(k[c], &mut self.rm_k[c], &mut self.dhs_k[c], self.use_dhp, &self.dhc, self.det_m, self.rms_c); + } + lv[c] = l; + } + let lmx = lv[0].max(lv[1]); + + // Upward part: the gain computer mirrored around the threshold gives the lift for a level below it (same ratio, same + // knee), capped at the range. The lift rises when the level falls (release ballistics) and is pulled back quickly + // when it rises (attack), so loud transients are never boosted. + let mut lift = [0.0f64; 2]; + if self.up { + for c in 0..2 { + let x = DB_AMP * lv[c].max(0.000001).ln(); + let tl = self.gc.gr(2.0 * self.gc.thr - x).min(self.up_range); + let k = if tl < self.gl[c] { + self.a_att + } else if self.auto_rel { + self.a_rel_s + } else { + self.a_rel_f + }; + self.gl[c] += (tl - self.gl[c]) * k; + if self.gl[c] < 0.000000001 { + self.gl[c] = 0.0; + } + lift[c] = self.gl[c]; + } + if !self.down { + let y = [sig[0] * (lift[0] * LN10_20).exp(), sig[1] * (lift[1] * LN10_20).exp()]; + self.prev = y; + return CompOut { y, g: [0.0; 2], lift, level: lmx }; + } + } + + let mut tg = [0.0f64; 2]; + for c in 0..2 { + tg[c] = self.gc.gr(DB_AMP * lv[c].max(0.000001).ln()); + } + let mut g = [0.0f64; 2]; + for c in 0..2 { + let k = if tg[c] > self.grf[c] { self.a_att } else { self.a_rel_f }; + self.grf[c] += (tg[c] - self.grf[c]) * k; + if self.grf[c] < 0.000000001 { + self.grf[c] = 0.0; + } + } + if self.auto_rel { + for c in 0..2 { + let k = if tg[c] > self.grs[c] { self.a_att } else { self.a_rel_s }; + self.grs[c] += (tg[c] - self.grs[c]) * k; + if self.grs[c] < 0.000000001 { + self.grs[c] = 0.0; + } + } + self.pk_env = lmx.max(self.pk_env * self.pk_d); + self.ms_env += (lmx * lmx + DENORM - self.ms_env) * self.ms_c; + let crest = self.pk_env / (self.ms_env.sqrt() + 0.000000001); + let cn = ((crest - 1.5) * 0.2857).clamp(0.0, 1.0); + self.gavg += (self.grf[0].max(self.grf[1]) - self.gavg) * self.avg_c; + let wgt = 0.1 + 0.75 * (self.gavg * 0.1111).min(1.0) * (1.0 - cn); + for c in 0..2 { + g[c] = self.grf[c] + wgt * (self.grs[c] - self.grf[c]); + } + } else { + g = self.grf; + } + + let mut y = [sig[0] * ((lift[0] - g[0]) * LN10_20).exp(), sig[1] * ((lift[1] - g[1]) * LN10_20).exp()]; + if self.gdist > 0.0 { + for c in 0..2 { + let dd = self.gdist * (g[c] * 0.0833333).min(1.0); + y[c] += dd * (y[c] / (1.0 + 0.5 * y[c].abs()) - y[c]); + } + } + self.prev = y; + CompOut { y, g, lift, level: lmx } + } +} + +/// Detector level of one source: optional low cut, then peak/RMS blend. +#[inline] +fn det_level(mut xd: f64, rm: &mut f64, hs: &mut [f64; 2], use_hp: bool, hc: &Coef, det_m: f64, rms_c: f64) -> f64 { + if use_hp { + xd = bq(hs, hc, xd); + } + let a = xd.abs(); + *rm += (xd * xd + DENORM - *rm) * rms_c; + if det_m > 0.0 { + a + det_m * (1.41421356 * rm.sqrt() - a) + } else { + a + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SR: f64 = 48000.0; + + /// run a 1 kHz tone of `amp` through the compressor for `secs`, return (output rms ratio to input, last lift, last gr) + fn run(p: &CompParams, amp: f64, secs: f64) -> (f64, f64, f64) { + let mut c = Compressor::new(); + c.derive(p, SR); + let n = (SR * secs) as usize; + let (mut si, mut so) = (0.0, 0.0); + let (mut lift, mut gr) = (0.0, 0.0); + for i in 0..n { + let x = amp * (2.0 * std::f64::consts::PI * 1000.0 * i as f64 / SR).sin(); + let o = c.tick([x, x], [x, x], None); + if i > n / 2 { + si += x * x; + so += o.y[0] * o.y[0]; + } + lift = o.lift[0]; + gr = o.g[0]; + } + ((so / si).sqrt(), lift, gr) + } + + fn base() -> CompParams { + CompParams { thresh: -30.0, ratio: 2.0, knee: 0.0, attack: 5.0, release: 50.0, detector: 100.0, ..CompParams::default() } + } + + #[test] + fn downward_mode_is_unchanged_and_reports_no_lift() { + let (_, lift, gr) = run(&base(), 0.5, 1.0); // -6 dB, well above -30 + assert_eq!(lift, 0.0); + assert!(gr > 5.0, "downward still reduces: {gr}"); + } + + #[test] + fn upward_mode_lifts_a_quiet_signal_up_to_the_range_and_leaves_a_loud_one_alone() { + let p = CompParams { up: true, down: false, up_range: 12.0, ..base() }; + // -50 dB tone: 20 dB under the threshold, ratio 2 would lift 10 dB (under the 12 dB range) + let (ratio, lift, gr) = run(&p, 0.00316, 1.0); + assert!((lift - 10.0).abs() < 1.0, "lift {lift}"); + assert!((20.0 * ratio.log10() - lift).abs() < 1.0, "output follows the lift: {}", 20.0 * ratio.log10()); + assert_eq!(gr, 0.0); + // -70 dB: would be 20 dB, capped at the 12 dB range + let (_, lift, _) = run(&p, 0.000316, 1.0); + assert!((lift - 12.0).abs() < 0.5, "capped at the range: {lift}"); + // -6 dB (above the threshold): untouched + let (ratio, lift, gr) = run(&p, 0.5, 1.0); + assert!(lift < 0.01 && gr == 0.0 && (ratio - 1.0).abs() < 0.01, "loud signal untouched: lift {lift} ratio {ratio}"); + } + + #[test] + fn both_mode_lifts_below_and_reduces_above_the_same_threshold() { + let p = CompParams { up: true, down: true, up_range: 12.0, ..base() }; + let (ratio, lift, gr) = run(&p, 0.00316, 1.0); // -50 dB: lifted + assert!((lift - 10.0).abs() < 1.0 && gr == 0.0, "quiet: lift {lift} gr {gr}"); + assert!((20.0 * ratio.log10() - lift).abs() < 1.0); + let (ratio, lift, gr) = run(&p, 0.5, 1.0); // -6 dB: reduced like the plain compressor + let (plain, _, plain_gr) = run(&base(), 0.5, 1.0); + assert!(lift < 0.01, "no lift up there: {lift}"); + assert!((gr - plain_gr).abs() < 0.2 && (ratio - plain).abs() < 0.01, "same reduction as downward: {gr} vs {plain_gr}"); + } + + #[test] + fn upward_lift_gives_way_quickly_when_the_level_rises() { + let p = CompParams { up: true, down: false, up_range: 12.0, attack: 1.0, release: 400.0, ..base() }; + let mut c = Compressor::new(); + c.derive(&p, SR); + let tone = |i: usize, a: f64| a * (2.0 * std::f64::consts::PI * 1000.0 * i as f64 / SR).sin(); + let mut lift = 0.0; + for i in 0..(SR * 2.0) as usize { + let x = tone(i, 0.001); // -60 dB: lifts to the range + lift = c.tick([x, x], [x, x], None).lift[0]; + } + assert!(lift > 11.0, "{lift}"); + let mut after = lift; + for i in 0..(SR * 0.02) as usize { + let x = tone(i, 0.5); // a loud hit: the lift must collapse within 20 ms (attack 1 ms) + after = c.tick([x, x], [x, x], None).lift[0]; + } + assert!(after < 1.0, "lift after a loud hit: {after}"); + } +} diff --git a/rust/satcomp-dsp/src/delay.rs b/rust/satcomp-dsp/src/delay.rs new file mode 100644 index 0000000..841601e --- /dev/null +++ b/rust/satcomp-dsp/src/delay.rs @@ -0,0 +1,107 @@ +//! Power-of-two delay ring (const-generic length). `advance()` once per sample, then optionally `put()`, then `tap(d)` reads `d` samples back +//! (`tap(0)` is the sample just put). Writing is separate from advancing on purpose: some rings are only written while a +//! feature is active but must keep moving every sample so the read index stays aligned with the other rings. + +/// `N` must be a power of two and larger than any delay that will be tapped. Fixed size (boxed array) so the masked +/// index needs no bounds check. +#[derive(Clone)] +pub struct Delay { + buf: Box<[f64; N]>, + pos: usize, +} + +impl Default for Delay { + fn default() -> Self { + Self::new() + } +} + +impl Delay { + const MASK: usize = N - 1; + + pub fn new() -> Self { + assert!(N.is_power_of_two()); + Self { buf: vec![0.0; N].into_boxed_slice().try_into().expect("length is N"), pos: 0 } + } + + #[inline] + pub fn advance(&mut self) { + self.pos = (self.pos + 1) & Self::MASK; + } + + #[inline] + pub fn put(&mut self, v: f64) { + self.buf[self.pos & Self::MASK] = v; + } + + #[inline] + pub fn tap(&self, d: usize) -> f64 { + self.buf[(self.pos + N - d) & Self::MASK] + } + + pub fn clear(&mut self) { + self.buf.iter_mut().for_each(|v| *v = 0.0); + } +} + +/// A left/right pair of rings. +#[derive(Clone)] +pub struct StereoDelay(pub [Delay; 2]); + +impl Default for StereoDelay { + fn default() -> Self { + Self::new() + } +} + +impl StereoDelay { + pub fn new() -> Self { + Self([Delay::new(), Delay::new()]) + } + #[inline] + pub fn advance(&mut self) { + self.0[0].advance(); + self.0[1].advance(); + } + #[inline] + pub fn put(&mut self, v: [f64; 2]) { + self.0[0].put(v[0]); + self.0[1].put(v[1]); + } + #[inline] + pub fn tap(&self, d: usize) -> [f64; 2] { + [self.0[0].tap(d), self.0[1].tap(d)] + } + pub fn clear(&mut self) { + self.0[0].clear(); + self.0[1].clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tap_reads_back_the_delayed_sample() { + let mut d = Delay::<8>::new(); + for i in 0..20 { + d.advance(); + d.put(i as f64); + assert_eq!(d.tap(0), i as f64); + if i >= 3 { + assert_eq!(d.tap(3), (i - 3) as f64); + } + } + } + + #[test] + fn advance_without_put_keeps_stale_value_in_place() { + let mut d = Delay::<8>::new(); + d.advance(); + d.put(5.0); + d.advance(); + d.advance(); + assert_eq!(d.tap(2), 5.0); + } +} diff --git a/rust/satcomp-dsp/src/engine.rs b/rust/satcomp-dsp/src/engine.rs index ce7fc1e..4e60223 100644 --- a/rust/satcomp-dsp/src/engine.rs +++ b/rust/satcomp-dsp/src/engine.rs @@ -1,14 +1,19 @@ -//! The SatComp signal path: sat (HP/LP split, shaper + optional oversampling, DC block, tone, sat mix, sat out) -//! -> EQ pre -> lookahead -> compressor -> makeup/mix -> EQ post -> out gain -> equal-loudness bypass -> delta. -//! Port of the JSFX `@block` / `@sample` sections. Names follow the JSFX variables where practical. - -use crate::biquad::{self, bq, Coef}; -use crate::eq::EqBank; -use crate::halfband::{Oversampler, Taps}; +//! The SatComp signal path, composed from the DSP blocks: saturator (HP/LP split, shaper + optional oversampling, DC block, +//! tone, sat mix, sat out) -> EQ pre -> lookahead -> compressor -> makeup/mix -> EQ post -> out gain -> output limiter -> +//! equal-loudness bypass blend -> delta. Port of the JSFX `@block` / `@sample` sections. The blocks (`saturator`, `compressor`, `keyinput`, +//! `eq::EqSection`, `delay`, `level`) hold the algorithms; this file wires them together, owns the output stage and +//! the level-match state machines, and publishes the meters the UI reads. + +use crate::compressor::Compressor; +use crate::delay::StereoDelay; +use crate::eq::EqSection; +use crate::keyinput::KeyInput; +use crate::level::{ms_step, one_pole, Matcher, DB_AMP, DB_POW, LN10_20}; +use crate::limiter::Limiter; use crate::params::Params; -use crate::shapers::ShaperLut; +use crate::saturator::Saturator; use crate::DENORM; -use std::f64::consts::PI; +pub use crate::compressor::GainComputer; use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; use std::sync::Arc; @@ -24,7 +29,7 @@ impl TapRing { Self { buf: (0..Self::LEN).map(|_| AtomicU32::new(0)).collect(), w: AtomicUsize::new(0) } } #[inline] - fn push(&self, v: f32) { + pub fn push(&self, v: f32) { let w = self.w.load(Ordering::Relaxed); self.buf[w & (Self::LEN - 1)].store(v.to_bits(), Ordering::Relaxed); self.w.store(w.wrapping_add(1), Ordering::Release); @@ -45,6 +50,8 @@ impl Default for TapRing { pub struct ScopeRing { out: Vec, pre: Vec, + /// peak between the output and `pre` (SatLim: after the clipper, before the limiter's gain); `push` makes it equal to `pre` + mid: Vec, w: AtomicUsize, } @@ -56,13 +63,20 @@ impl ScopeRing { Self { out: (0..Self::LEN).map(|_| AtomicU32::new(0)).collect(), pre: (0..Self::LEN).map(|_| AtomicU32::new(0)).collect(), + mid: (0..Self::LEN).map(|_| AtomicU32::new(0)).collect(), w: AtomicUsize::new(0), } } - fn push(&self, o: f32, p: f32) { + pub fn push(&self, o: f32, p: f32) { + self.push3(o, p, p); + } + /// Output peak, the peak with only the first removal added back (`m`), and the peak with everything added back (`p`). + pub fn push3(&self, o: f32, m: f32, p: f32) { let w = self.w.load(Ordering::Relaxed); - self.out[w & (Self::LEN - 1)].store(o.to_bits(), Ordering::Relaxed); - self.pre[w & (Self::LEN - 1)].store(p.to_bits(), Ordering::Relaxed); + let k = w & (Self::LEN - 1); + self.out[k].store(o.to_bits(), Ordering::Relaxed); + self.mid[k].store(m.to_bits(), Ordering::Relaxed); + self.pre[k].store(p.to_bits(), Ordering::Relaxed); self.w.store(w.wrapping_add(1), Ordering::Release); } /// number of buckets written so far (bucket `head - 1` is the newest) @@ -73,6 +87,15 @@ impl ScopeRing { let k = i & (Self::LEN - 1); (f32::from_bits(self.out[k].load(Ordering::Relaxed)), f32::from_bits(self.pre[k].load(Ordering::Relaxed))) } + /// (output, middle, pre) + pub fn get3(&self, i: usize) -> (f32, f32, f32) { + let k = i & (Self::LEN - 1); + ( + f32::from_bits(self.out[k].load(Ordering::Relaxed)), + f32::from_bits(self.mid[k].load(Ordering::Relaxed)), + f32::from_bits(self.pre[k].load(Ordering::Relaxed)), + ) + } } impl Default for ScopeRing { @@ -81,61 +104,6 @@ impl Default for ScopeRing { } } -const LN10_20: f64 = 0.11512925; // dB -> ln(gain) -const DB_POW: f64 = 4.3429448; // 10/ln(10) -const DB_AMP: f64 = 8.6858896; // 20/ln(10) - -/// Static gain computer: returns GR in dB (>= 0) for a level in dB. C1 knee, quad -> smoothstep -> smootherstep. -#[derive(Clone, Copy, Debug)] -pub struct GainComputer { - pub thr: f64, - pub knw: f64, - pub cslope: f64, - pub kc0: f64, - pub kc1: f64, - pub kc2: f64, -} - -impl Default for GainComputer { - fn default() -> Self { - Self { thr: -18.0, knw: 6.0, cslope: 0.75, kc0: 1.0, kc1: 0.0, kc2: 0.0 } - } -} - -impl GainComputer { - pub fn from_params(p: &Params) -> Self { - let inv_r = if p.ratio >= 19.9 { 0.0 } else { 1.0 / p.ratio }; - let sh2 = p.knee_shape * 0.02; - let (kc0, kc1, kc2) = if sh2 <= 1.0 { (1.0 - sh2, sh2, 0.0) } else { (0.0, 2.0 - sh2, sh2 - 1.0) }; - Self { thr: p.thresh, knw: p.knee, cslope: 1.0 - inv_r, kc0, kc1, kc2 } - } - - #[inline] - pub fn gr(&self, x: f64) -> f64 { - let d = x - self.thr; - if self.knw > 0.001 { - if d <= -self.knw * 0.5 { - 0.0 - } else if d >= self.knw * 0.5 { - d * self.cslope - } else { - let u = (d + self.knw * 0.5) / self.knw; - let (u2, u3) = (u * u, u * u * u); - let u4 = u2 * u2; - let g = self.kc0 * u2 * 0.5 + self.kc1 * (u3 - u4 * 0.5) + self.kc2 * (u4 * u2 - 3.0 * u4 * u + 2.5 * u4); - self.cslope * self.knw * g - } - } else if d > 0.0 { - d * self.cslope - } else { - 0.0 - } - } -} - -fn one_pole(sr: f64, secs: f64) -> f64 { - 1.0 - (-1.0 / (sr * secs)).exp() -} pub struct Engine { sr: f64, @@ -145,96 +113,31 @@ pub struct Engine { /// Smooth Drive/Bias/Makeup/Mix/Sat Mix (JSFX has none; set false for null tests against it). pub smoothing: bool, snap: bool, - - // ---- sat - lut: ShaperLut, - lut_cnt: u32, - taps: Taps, - ov: [Oversampler; 2], - pre: f64, - pre_t: f64, - bias: f64, - bias_t: f64, - sat_on: bool, - use_hp: bool, - use_lp: bool, - use_tone: bool, - hpc: Coef, - lpc: Coef, - tnc: Coef, - hps: [[f64; 2]; 2], - lps: [[f64; 2]; 2], - tns: [[f64; 2]; 2], - os: i32, - last_os: i32, - lat: usize, - la_s: usize, - dc_r: f64, - dcx: [f64; 2], - dcy: [f64; 2], - /// True until the first saturated sample: a fresh engine (REAPER rebuilds it on every FX enable) must start the - /// oversampler and DC blocker in their settled state, else the saturator's constant output (bias) leaks as a step. - dc_warm: bool, /// True until the first real `set_params`; `new()` derives from defaults, which would otherwise use up `snap`. first_set: bool, - dry: [[f64; 64]; 2], - res: [[f64; 64]; 2], - bd: [[f64; 64]; 2], - dw: [Vec; 2], - lk: [Vec; 2], - wp: usize, - dwp: usize, - lkw: usize, - smix: f64, - smix_t: f64, - sg: f64, - sg_t: f64, - sat_out_eff: f64, - sm_c: f64, - // ---- comp - gc: GainComputer, - a_att: f64, - auto_rel: bool, - a_rel_f: f64, - a_rel_s: f64, - rms_c: f64, - pk_d: f64, - ms_c: f64, - avg_c: f64, - det_m: f64, - use_dhp: bool, - dhc: Coef, - dhs: [[f64; 2]; 2], - fb: f64, - gdist: f64, - prev: [f64; 2], - rm: [f64; 2], - grf: [f64; 2], - grs: [f64; 2], - pk_env: f64, - ms_env: f64, - gavg: f64, + // ---- blocks + sat: Saturator, + comp: Compressor, + key: KeyInput, + eq: [EqSection; 2], + lim: Limiter, + /// delta / sidechain-solo monitor signals, delayed by the limiter latency so they line up with the limited path + mon_d: StereoDelay<1024>, + mon_s: StereoDelay<1024>, + + // ---- delay lines: input aligned with the (latency-delayed) wet path, and the compressor lookahead + dw: StereoDelay<4096>, + lk: StereoDelay<4096>, + la_s: usize, + sm_c: f64, // ---- sidechain /// Set by the shell per block: an aux input bus exists. Sidechain only takes over the detector when true. pub sc_avail: bool, /// Solo the (gain/HP/LP-filtered) sidechain signal to the output. UI monitor, not a stored parameter. pub sc_solo: bool, - sc_act: bool, - sc_g: f64, - sc_g_t: f64, - use_sc_hp: bool, - use_sc_lp: bool, - sc_hpc: Coef, - sc_lpc: Coef, - sc_hps: [[f64; 2]; 2], - sc_lps: [[f64; 2]; 2], - scd: [[f64; 64]; 2], sc_s: f64, - sc_mix: f64, - rm_k: [f64; 2], - dhs_k: [[f64; 2]; 2], // ---- out mk: f64, @@ -244,9 +147,6 @@ pub struct Engine { og: f64, og_t: f64, og_c: f64, - bg: f64, - bg_t: f64, - bg_c: f64, byp: bool, byp_s: f64, byp_c: f64, @@ -259,6 +159,7 @@ pub struct Engine { pub ims: f64, pub oms: f64, pub pms: f64, + /// mirror of the saturator's output level (see `Saturator::ms`) pub sms: f64, pub diff_db: f64, pub diff_disp: f64, @@ -266,26 +167,15 @@ pub struct Engine { gate_open: bool, match_on: bool, prev_match_on: bool, - meas: bool, - macc: f64, - mt: f64, + out_m: Matcher, pub match_trim: f64, match_req: bool, - sat_meas: bool, - sat_macc: f64, - sat_mt: f64, + sat_m: Matcher, sat_req: bool, sat_result: Option, - // ---- EQ - bank: EqBank, - eg: [f64; 2], - eg_t: [f64; 2], + // ---- EQ page tap + scope pub eq_act: [bool; 2], - eq_en: [f64; 2], - eq_pen: [bool; 2], - eq_bs: [f64; 2], - eq_run: [bool; 2], /// Set by the shell while the EQ page is visible; fills `tap` (mono, pre or post stage per `eq_vs`). pub eq_tap_on: bool, pub eq_vs: usize, @@ -302,89 +192,45 @@ pub struct Engine { pub clip_f: bool, pub gr_blk: f64, pub gr_pk: f64, + /// Peak limiter gain reduction (dB, positive) since the shell last took it. + pub lim_gr_pk: f64, pub vz_blk: f64, pub vz_lv: f64, /// Main-signal level at the compressor input (decaying peak), for the sidechain viewport. pub mn_blk: f64, pub mn_lv: f64, + /// mirror of the saturator's band peak (see `Saturator::blk`); reset with the other block meters pub sat_blk: f64, pub sat_vz: f64, + /// Post-saturator peak since the shell last took it (no decay, so a clip between UI frames is never missed). + pub sat_pk: f64, pub fms: f64, } impl Engine { pub fn new(sr: f64) -> Self { - let p = Params::default(); let mut e = Self { sr, sr_prev: 0.0, - p, + p: Params::default(), dirty: true, smoothing: true, snap: true, - lut: ShaperLut::new(0), - lut_cnt: 0, - taps: Taps::new(), - ov: [Oversampler::default(), Oversampler::default()], - pre: 1.0, - pre_t: 1.0, - bias: 0.0, - bias_t: 0.0, - sat_on: false, - use_hp: false, - use_lp: false, - use_tone: false, - hpc: biquad::IDENTITY, - lpc: biquad::IDENTITY, - tnc: biquad::IDENTITY, - hps: [[0.0; 2]; 2], - lps: [[0.0; 2]; 2], - tns: [[0.0; 2]; 2], - os: 0, - last_os: -1, - lat: 0, - la_s: 0, - dc_r: 1.0, - dcx: [0.0; 2], - dcy: [0.0; 2], - dc_warm: true, first_set: true, - dry: [[0.0; 64]; 2], - res: [[0.0; 64]; 2], - bd: [[0.0; 64]; 2], - dw: [vec![0.0; 4096], vec![0.0; 4096]], - lk: [vec![0.0; 4096], vec![0.0; 4096]], - wp: 0, - dwp: 0, - lkw: 0, - smix: 1.0, - smix_t: 1.0, - sg: 1.0, - sg_t: 1.0, - sat_out_eff: 0.0, + sat: Saturator::new(), + comp: Compressor::new(), + key: KeyInput::new(), + eq: [EqSection::default(), EqSection::default()], + lim: Limiter::new(sr), + mon_d: StereoDelay::new(), + mon_s: StereoDelay::new(), + dw: StereoDelay::new(), + lk: StereoDelay::new(), + la_s: 0, sm_c: 0.0, - gc: GainComputer::default(), - a_att: 0.0, - auto_rel: false, - a_rel_f: 0.0, - a_rel_s: 0.0, - rms_c: 0.0, - pk_d: 0.0, - ms_c: 0.0, - avg_c: 0.0, - det_m: 0.0, - use_dhp: false, - dhc: biquad::IDENTITY, - dhs: [[0.0; 2]; 2], - fb: 0.0, - gdist: 0.0, - prev: [0.0; 2], - rm: [0.0; 2], - grf: [0.0; 2], - grs: [0.0; 2], - pk_env: 0.0, - ms_env: 0.0, - gavg: 0.0, + sc_avail: false, + sc_solo: false, + sc_s: 0.0, mk: 1.0, mk_t: 1.0, mix: 1.0, @@ -392,9 +238,6 @@ impl Engine { og: 1.0, og_t: 1.0, og_c: 0.0, - bg: 1.0, - bg_t: 1.0, - bg_c: 0.0, byp: false, byp_s: 0.0, byp_c: 0.0, @@ -412,40 +255,13 @@ impl Engine { gate_open: false, match_on: false, prev_match_on: false, - meas: false, - macc: 0.0, - sc_avail: false, - sc_solo: false, - sc_act: false, - sc_g: 1.0, - sc_g_t: 1.0, - use_sc_hp: false, - use_sc_lp: false, - sc_hpc: biquad::IDENTITY, - sc_lpc: biquad::IDENTITY, - sc_hps: [[0.0; 2]; 2], - sc_lps: [[0.0; 2]; 2], - scd: [[0.0; 64]; 2], - sc_s: 0.0, - sc_mix: 1.0, - rm_k: [0.0; 2], - dhs_k: [[0.0; 2]; 2], - mt: 0.0, + out_m: Matcher::default(), match_trim: 0.0, match_req: false, - sat_meas: false, - sat_macc: 0.0, - sat_mt: 0.0, + sat_m: Matcher::default(), sat_req: false, sat_result: None, - bank: EqBank::default(), - eg: [1.0; 2], - eg_t: [1.0; 2], eq_act: [false; 2], - eq_en: [1.0; 2], - eq_pen: [true; 2], - eq_bs: [1.0; 2], - eq_run: [false; 2], eq_tap_on: false, eq_vs: 0, tap: Arc::new(TapRing::new()), @@ -458,12 +274,14 @@ impl Engine { clip_f: false, gr_blk: 0.0, gr_pk: 0.0, + lim_gr_pk: 0.0, vz_blk: 0.0, vz_lv: 0.0, mn_blk: 0.0, mn_lv: 0.0, sat_blk: 0.0, sat_vz: 0.0, + sat_pk: 0.0, fms: 1e-9, }; e.derive(); @@ -481,7 +299,8 @@ impl Engine { // thump when REAPER rebuilds the engine on every FX enable). self.first_set = false; self.p = *p; - self.sat_out_eff = p.sat_out; + self.sat.set_out_db(p.sat_out); + self.lim.snap_on(p.lim_on); self.snap = true; let sm = std::mem::replace(&mut self.smoothing, false); // shaper table commits at once, no morph from shape 0 self.derive(); @@ -490,16 +309,16 @@ impl Engine { } if *p != self.p { if p.sat_out != self.p.sat_out { - self.sat_out_eff = p.sat_out; + self.sat.set_out_db(p.sat_out); } self.p = *p; self.derive(); // applied immediately so latency() is valid before the first block } } - /// PDC latency to report (oversampling + lookahead). + /// PDC latency to report (oversampling + compressor lookahead + limiter lookahead, the last one always). pub fn latency(&self) -> u32 { - (self.lat + self.la_s) as u32 + (self.sat.latency() + self.la_s + self.lim.latency()) as u32 } pub fn request_match(&mut self) { @@ -509,29 +328,26 @@ impl Engine { self.sat_req = true; } pub fn sat_matching(&self) -> bool { - self.sat_meas + self.sat_m.active } pub fn out_matching(&self) -> bool { - self.meas + self.out_m.active } pub fn out_match_progress(&self) -> f64 { - self.mt + self.out_m.t } pub fn sat_match_progress(&self) -> f64 { - self.sat_mt + self.sat_m.t } /// A finished sat level-match (new Sat Out, dB); the shell should write it to the Sat Out parameter. pub fn take_sat_result(&mut self) -> Option { self.sat_result.take() } - pub fn bg_gain(&self) -> f64 { - self.bg - } pub fn gate_open(&self) -> bool { self.gate_open } pub fn gain_computer(&self) -> GainComputer { - self.gc + self.comp.gain_computer() } pub fn sample_rate(&self) -> f64 { self.sr @@ -543,146 +359,55 @@ impl Engine { let sr = self.sr; self.sr_prev = sr; self.dirty = false; + self.lim.set_sample_rate(sr); + let snap = self.snap; - // ---- SAT - self.lut.fade = self.smoothing; - self.lut.sync(p.shape, &p.curve); - self.pre_t = (p.drive * 0.01 * 36.0 * LN10_20).exp(); - self.bias_t = p.bias * 0.01; - self.sat_on = p.drive > 0.0 || p.bias != 0.0; - self.use_hp = p.sat_hp > 20.5; - if self.use_hp { - self.hpc = biquad::hp(p.sat_hp, 0.70710678, sr); - } - self.use_lp = p.sat_lp < 19900.0; - if self.use_lp { - self.lpc = biquad::lp(p.sat_lp, 0.70710678, sr); - } - self.use_tone = p.tone < 19900.0; - if self.use_tone { - self.tnc = biquad::lp(p.tone, 0.70710678, sr); - } - self.os = (p.os as f64 + 0.5).floor() as i32; - if self.os != self.last_os { - self.last_os = self.os; - self.ov[0].clear(); - self.ov[1].clear(); - self.res = [[0.0; 64]; 2]; - } - self.lat = match self.os { - 0 => 0, - 1 => 24, - _ => 28, - }; + self.sat.derive(&p.sat(), sr, snap, self.smoothing); self.la_s = ((p.lookahead_ms * 0.001 * sr + 0.5).floor().max(0.0) as usize).min(1900); - self.dc_r = 1.0 - 2.0 * PI * 5.0 / sr; - - // ---- COMP - self.gc = GainComputer::from_params(&p); - let spd = 4f64.powf((p.speed - 50.0) / 50.0); - self.a_att = 1.0 - (-1.0 / (sr * (p.attack * 0.001 * spd).max(0.00001))).exp(); - self.auto_rel = p.release >= 1990.0; - let a_rel = 1.0 - (-1.0 / (sr * (p.release * 0.001 * spd).max(0.00001))).exp(); - self.a_rel_f = if self.auto_rel { 1.0 - (-1.0 / (sr * 0.04 * spd)).exp() } else { a_rel }; - self.a_rel_s = 1.0 - (-1.0 / (sr * 0.6 * spd)).exp(); - self.rms_c = one_pole(sr, 0.01); - self.pk_d = (-1.0 / (sr * 0.05)).exp(); - self.ms_c = one_pole(sr, 0.3); - self.avg_c = one_pole(sr, 0.25); - self.det_m = p.detector * 0.01; - self.use_dhp = p.det_hp > 15.0; - if self.use_dhp { - self.dhc = biquad::hp(p.det_hp, 0.70710678, sr); - } - self.fb = p.ff_fb * 0.01; - self.sc_mix = (p.sc_mix * 0.01).clamp(0.0, 1.0); - self.sc_g_t = (p.sc_gain * LN10_20).exp(); - self.use_sc_hp = p.sc_hp > 20.5; - if self.use_sc_hp { - self.sc_hpc = biquad::hp(p.sc_hp, 0.70710678, sr); - } - self.use_sc_lp = p.sc_lp < 19900.0; - if self.use_sc_lp { - self.sc_lpc = biquad::lp(p.sc_lp, 0.70710678, sr); - } - self.gdist = p.gr_dist * 0.01; + self.comp.derive(&p.comp(), sr); + self.key.derive(p.sc_gain, p.sc_hp, p.sc_lp, sr); self.mk_t = (p.makeup * LN10_20).exp(); self.mix_t = p.mix * 0.01; self.match_on = p.gain_match; if self.match_on && !self.prev_match_on { - self.meas = true; - self.macc = 0.0; - self.mt = 0.0; + self.out_m.start(); } if !self.match_on { - self.meas = false; + self.out_m.stop(); } self.prev_match_on = self.match_on; self.rmsg_c = one_pole(sr, 0.5); self.og_c = one_pole(sr, 0.02); - self.smix_t = p.sat_mix * 0.01; self.byp = p.bypass; self.byp_c = one_pole(sr, 0.01); self.sc_len = ((sr * ScopeRing::BUCKET_S).round() as u32).max(1); - self.bg_c = one_pole(sr, 0.2); self.fms_c = one_pole(sr, 0.3); self.sm_c = one_pole(sr, 0.02); - // ---- EQ - for st in 0..2 { - let any = self.bank.setup_stage(st, &p.eq[st], sr); - let g2 = p.eq[st].out_gain.clamp(-12.0, 12.0); - self.eg_t[st] = (g2 * LN10_20).exp(); - self.eq_act[st] = any || g2 != 0.0; - } - self.eq_en[0] = if !p.eq_pre_bypass && !p.eq_module_bypass { 1.0 } else { 0.0 }; - self.eq_en[1] = if !p.eq_post_bypass && !p.eq_module_bypass { 1.0 } else { 0.0 }; + let en = [!p.eq_pre_bypass && !p.eq_module_bypass, !p.eq_post_bypass && !p.eq_module_bypass]; for st in 0..2 { - let en = self.eq_en[st] > 0.5; - if en && !self.eq_pen[st] { - self.bank.clear_stage(st); - self.eg[st] = self.eg_t[st]; - } - self.eq_pen[st] = en; + self.eq[st].derive(&p.eq[st], en[st], sr, snap); + self.eq_act[st] = self.eq[st].act; } - if self.snap { + if snap { self.snap = false; - self.pre = self.pre_t; - self.bias = self.bias_t; self.mk = self.mk_t; self.mix = self.mix_t; - self.smix = self.smix_t; - self.sat_out_eff = p.sat_out; - self.sg = (self.sat_out_eff * LN10_20).exp(); - self.sg_t = self.sg; - self.eg = self.eg_t; - self.eq_bs = self.eq_en; } } /// Per-block housekeeping (JSFX @block). Call once per host buffer with its length. pub fn begin_block(&mut self, n: usize) { if self.match_req { - self.meas = true; - self.macc = 0.0; - self.mt = 0.0; + self.out_m.start(); self.match_req = false; } if self.dirty || self.sr != self.sr_prev { self.derive(); } for s in 0..2 { - if (self.eq_bs[s] - self.eq_en[s]).abs() < 0.00001 { - self.eq_bs[s] = self.eq_en[s]; - } - } - self.bank.prep(n); - for s in 0..2 { - if (self.eg[s] - self.eg_t[s]).abs() < 0.0000001 { - self.eg[s] = self.eg_t[s]; - } - self.eq_run[s] = self.bank.stage_running(s) || self.eg[s] != 1.0 || self.eg_t[s] != 1.0; + self.eq[s].begin_block(n); } // ---- gain diff / match @@ -691,43 +416,43 @@ impl Engine { if self.gate_open { self.diff_db = DB_POW * (self.oms.max(1e-12) / self.ims.max(1e-12)).ln(); self.diff_disp = DB_POW * (self.pms.max(1e-12) / self.ims.max(1e-12)).ln(); - self.sat_db = DB_POW * (self.sms.max(1e-12) / self.ims.max(1e-12)).ln(); + self.sat_db = DB_POW * (self.sat.ms.max(1e-12) / self.ims.max(1e-12)).ln(); } if self.sat_req { - self.sat_meas = !self.sat_meas; - self.sat_macc = 0.0; - self.sat_mt = 0.0; + let was = self.sat_m.active; + self.sat_m.start(); + if was { + self.sat_m.stop(); + } self.sat_req = false; } - if self.sat_meas && self.gate_open { - self.sat_macc += self.sat_db * dt; - self.sat_mt += dt; - if self.sat_mt >= 3.0 { - let v = ((-self.sat_macc / self.sat_mt).clamp(-24.0, 12.0) * 10.0 + 0.5).floor() * 0.1; - self.sat_out_eff = v; + if self.sat_m.active && self.gate_open { + if let Some(avg) = self.sat_m.step(self.sat_db, dt) { + let v = (avg.clamp(-24.0, 12.0) * 10.0 + 0.5).floor() * 0.1; + self.sat.set_out_db(v); self.sat_result = Some(v); - self.sat_meas = false; } } - self.sg_t = (self.sat_out_eff * LN10_20).exp(); - if self.meas && self.gate_open { - self.macc += self.diff_db * dt; - self.mt += dt; - if self.mt >= 3.0 { - self.match_trim = (-self.macc / self.mt).clamp(-12.0, 12.0); - self.meas = false; + self.sat.begin_block(); + if self.out_m.active && self.gate_open { + if let Some(avg) = self.out_m.step(self.diff_db, dt) { + self.match_trim = avg.clamp(-12.0, 12.0); } } let trim = if self.match_on { self.match_trim } else { 0.0 }; self.og_t = ((self.p.out_gain + trim) * LN10_20).exp(); self.gr_pk = self.gr_pk.max(self.gr_blk); + self.lim_gr_pk = self.lim_gr_pk.max(-self.lim.gmin.max(1e-6).ln() * DB_AMP); + self.lim.gmin = 1.0; self.gr_blk = 0.0; let vz_d = (-(n as f64) / (self.sr * 0.15)).exp(); self.vz_lv = self.vz_blk.max(self.vz_lv * vz_d); self.vz_blk = 0.0; self.mn_lv = self.mn_blk.max(self.mn_lv * vz_d); self.mn_blk = 0.0; - self.sat_vz = self.sat_blk.max(self.sat_vz * vz_d); + self.sat_vz = self.sat.blk.max(self.sat_vz * vz_d); + self.sat_pk = self.sat_pk.max(self.sat.blk); + self.sat.blk = 0.0; self.sat_blk = 0.0; } @@ -762,208 +487,50 @@ impl Engine { #[inline] pub fn tick_sc(&mut self, in_l: f64, in_r: f64, sc_l: f64, sc_r: f64) -> (f64, f64) { let inp = [in_l, in_r]; - self.lut_cnt += 1; - if self.lut_cnt >= crate::shapers::FADE_EVERY { - self.lut_cnt = 0; - self.lut.step(); - } - self.ims += ((in_l * in_l + in_r * in_r) * 0.5 + DENORM - self.ims) * self.rmsg_c; + ms_step(&mut self.ims, in_l, in_r, self.rmsg_c); if self.smoothing { let c = self.sm_c; - self.pre += (self.pre_t - self.pre) * c; - self.bias += (self.bias_t - self.bias) * c; self.mk += (self.mk_t - self.mk) * c; self.mix += (self.mix_t - self.mix) * c; - self.smix += (self.smix_t - self.smix) * c; } else { - self.pre = self.pre_t; - self.bias = self.bias_t; self.mk = self.mk_t; self.mix = self.mix_t; - self.smix = self.smix_t; } - self.wp = (self.wp + 1) & 63; - let wp = self.wp; - for c in 0..2 { - self.dry[c][wp] = inp[c]; - } - let rd = (wp + 64 - self.lat) & 63; - let dl = [self.dry[0][rd], self.dry[1][rd]]; - self.dwp = (self.dwp + 1) & 4095; - for c in 0..2 { - self.dw[c][self.dwp] = inp[c]; - } - let ti = (self.dwp + 4096 - self.lat - self.la_s) & 4095; - let dt = [self.dw[0][ti], self.dw[1][ti]]; - - // ------------------------------------------------ SAT - let mut cc = [0.0f64; 2]; - if self.sat_on { - let mut bp = inp; - if self.use_hp { - for c in 0..2 { - bp[c] = bq(&mut self.hps[c], &self.hpc, bp[c]); - } - } - if self.use_lp { - for c in 0..2 { - bp[c] = bq(&mut self.lps[c], &self.lpc, bp[c]); - } - } - for c in 0..2 { - self.res[c][wp] = inp[c] - bp[c]; - self.bd[c][wp] = bp[c]; - } - self.sat_blk = self.sat_blk.max(bp[0].abs().max(bp[1].abs())); - for c in 0..2 { - let xin = bp[c] * self.pre + self.bias; - if self.dc_warm { - for _ in 0..256 { - self.ov[c].process(&self.taps, &self.lut, self.os, xin); - } - } - let sh = self.ov[c].process(&self.taps, &self.lut, self.os, xin); - if self.dc_warm { - self.dcx[c] = sh; - self.dcy[c] = 0.0; - } - let mut y = sh - self.dcx[c] + self.dc_r * self.dcy[c] + DENORM; - self.dcx[c] = sh; - self.dcy[c] = y; - if self.use_tone { - y = bq(&mut self.tns[c], &self.tnc, y); - } - if self.smix < 0.999 { - y = self.bd[c][rd] + (y - self.bd[c][rd]) * self.smix; - } - cc[c] = self.res[c][rd] + y; - } - self.dc_warm = false; - } else { - self.res[0][wp] = 0.0; - self.res[1][wp] = 0.0; - cc = dl; - } + // input aligned with the wet path (sat latency + lookahead), for the parallel dry mix + self.dw.advance(); + self.dw.put(inp); + let lat = self.sat.latency(); + let ll = self.lim.latency(); + let dt = self.dw.tap(lat + self.la_s); + // the untouched input again, a limiter latency later: lines up with the limited path for the bypass blend + let db = self.dw.tap(lat + self.la_s + ll); - // SAT OUT - self.sms += ((cc[0] * cc[0] + cc[1] * cc[1]) * 0.5 + DENORM - self.sms) * self.rmsg_c; - self.sg += (self.sg_t - self.sg) * self.og_c; - cc[0] *= self.sg; - cc[1] *= self.sg; + // ------------------------------------------------ SAT (+ SAT OUT) + let mut cc = self.sat.tick(inp, self.smoothing); + self.sms = self.sat.ms; + self.sat_blk = self.sat.blk; // ------------------------------------------------ EQ PRE if self.eq_tap_on && self.eq_vs == 0 { self.tap.push(((cc[0] + cc[1]) * 0.5) as f32); } - self.eq_bs[0] += (self.eq_en[0] - self.eq_bs[0]) * self.byp_c; - if self.eq_run[0] && self.eq_bs[0] > 0.0 { - let (mut xl, mut xr) = (cc[0], cc[1]); - self.bank.process(0, &mut xl, &mut xr); - self.eg[0] += (self.eg_t[0] - self.eg[0]) * self.og_c; - if self.eq_bs[0] >= 1.0 { - cc = [xl * self.eg[0], xr * self.eg[0]]; - } else { - let b = self.eq_bs[0]; - cc[0] += (xl * self.eg[0] - cc[0]) * b; - cc[1] += (xr * self.eg[0] - cc[1]) * b; - } - } + cc = self.eq[0].tick(cc); // ------------------------------------------------ LOOKAHEAD - self.lkw = (self.lkw + 1) & 4095; - for c in 0..2 { - self.lk[c][self.lkw] = cc[c]; - } - let cd = if self.la_s > 0 { - let i = (self.lkw + 4096 - self.la_s) & 4095; - [self.lk[0][i], self.lk[1][i]] - } else { - cc - }; + self.lk.advance(); + self.lk.put(cc); + let cd = if self.la_s > 0 { self.lk.tap(self.la_s) } else { cc }; // ------------------------------------------------ SIDECHAIN (gain > HP > LP), aligned with `cc` (delayed by the sat latency) - self.sc_act = self.p.sc_on && self.sc_avail; - self.sc_g += (self.sc_g_t - self.sc_g) * self.og_c; - let mut scv = [0.0f64; 2]; - if self.sc_act { - let s_in = [sc_l, sc_r]; - for c in 0..2 { - let mut v = s_in[c] * self.sc_g; - if self.use_sc_hp { - v = bq(&mut self.sc_hps[c], &self.sc_hpc, v); - } - if self.use_sc_lp { - v = bq(&mut self.sc_lps[c], &self.sc_lpc, v); - } - self.scd[c][wp] = v; - scv[c] = self.scd[c][rd]; - } - } + let sc_act = self.p.sc_on && self.sc_avail; + let scv = self.key.tick(if sc_act { Some([sc_l, sc_r]) } else { None }, lat); self.mn_blk = self.mn_blk.max(cc[0].abs().max(cc[1].abs())); // ------------------------------------------------ COMP - let mut lv = [0.0f64; 2]; - for c in 0..2 { - // KEY MIX: detector level = (1-m) * main + m * key (levels, not audio, so the two never phase-interact). - // Without an active sidechain m = 0. With one, FF>FB is not applied (it is replaced by KEY MIX). - let km = if self.sc_act { self.sc_mix } else { 0.0 }; - let mut l = 0.0; - if km < 1.0 { - let xd = if self.sc_act { cc[c] } else { cc[c] + self.fb * (self.prev[c] - cc[c]) }; - l += (1.0 - km) - * det_level(xd, &mut self.rm[c], &mut self.dhs[c], self.use_dhp, &self.dhc, self.det_m, self.rms_c); - } - if km > 0.0 { - l += km - * det_level(scv[c], &mut self.rm_k[c], &mut self.dhs_k[c], self.use_dhp, &self.dhc, self.det_m, self.rms_c); - } - lv[c] = l; - } - let lmx = lv[0].max(lv[1]); - self.vz_blk = self.vz_blk.max(lmx); - - let mut tg = [0.0f64; 2]; - for c in 0..2 { - tg[c] = self.gc.gr(DB_AMP * lv[c].max(0.000001).ln()); - } - let mut g = [0.0f64; 2]; - for c in 0..2 { - let k = if tg[c] > self.grf[c] { self.a_att } else { self.a_rel_f }; - self.grf[c] += (tg[c] - self.grf[c]) * k; - if self.grf[c] < 0.000000001 { - self.grf[c] = 0.0; - } - } - if self.auto_rel { - for c in 0..2 { - let k = if tg[c] > self.grs[c] { self.a_att } else { self.a_rel_s }; - self.grs[c] += (tg[c] - self.grs[c]) * k; - if self.grs[c] < 0.000000001 { - self.grs[c] = 0.0; - } - } - self.pk_env = lmx.max(self.pk_env * self.pk_d); - self.ms_env += (lmx * lmx + DENORM - self.ms_env) * self.ms_c; - let crest = self.pk_env / (self.ms_env.sqrt() + 0.000000001); - let cn = ((crest - 1.5) * 0.2857).clamp(0.0, 1.0); - self.gavg += (self.grf[0].max(self.grf[1]) - self.gavg) * self.avg_c; - let wgt = 0.1 + 0.75 * (self.gavg * 0.1111).min(1.0) * (1.0 - cn); - for c in 0..2 { - g[c] = self.grf[c] + wgt * (self.grs[c] - self.grf[c]); - } - } else { - g = self.grf; - } - - let mut y = [cd[0] * (-g[0] * LN10_20).exp(), cd[1] * (-g[1] * LN10_20).exp()]; - if self.gdist > 0.0 { - for c in 0..2 { - let dd = self.gdist * (g[c] * 0.0833333).min(1.0); - y[c] += dd * (y[c] / (1.0 + 0.5 * y[c].abs()) - y[c]); - } - } - self.prev = y; + let co = self.comp.tick(cc, cd, if sc_act { Some(scv) } else { None }); + self.vz_blk = self.vz_blk.max(co.level); + let (y, g) = (co.y, co.g); // ------------------------------------------------ OUT let mut o = [0.0f64; 2]; @@ -975,42 +542,34 @@ impl Engine { if self.eq_tap_on && self.eq_vs == 1 { self.tap.push(((o[0] + o[1]) * 0.5) as f32); } - self.eq_bs[1] += (self.eq_en[1] - self.eq_bs[1]) * self.byp_c; - if self.eq_run[1] && self.eq_bs[1] > 0.0 { - let (mut xl, mut xr) = (o[0], o[1]); - self.bank.process(1, &mut xl, &mut xr); - self.eg[1] += (self.eg_t[1] - self.eg[1]) * self.og_c; - if self.eq_bs[1] >= 1.0 { - o = [xl * self.eg[1], xr * self.eg[1]]; - } else { - let b = self.eq_bs[1]; - o[0] += (xl * self.eg[1] - o[0]) * b; - o[1] += (xr * self.eg[1] - o[1]) * b; - } - } - self.oms += ((o[0] * o[0] + o[1] * o[1]) * 0.5 + DENORM - self.oms) * self.rmsg_c; + o = self.eq[1].tick(o); + ms_step(&mut self.oms, o[0], o[1], self.rmsg_c); self.og += (self.og_t - self.og) * self.og_c; let pp = [o[0] * self.og, o[1] * self.og]; - self.pms += ((pp[0] * pp[0] + pp[1] * pp[1]) * 0.5 + DENORM - self.pms) * self.rmsg_c; - // equal-loudness bypass + ms_step(&mut self.pms, pp[0], pp[1], self.rmsg_c); + // bypass self.byp_s += ((if self.byp { 1.0 } else { 0.0 }) - self.byp_s) * self.byp_c; - if self.gate_open { - self.bg_t = (self.pms / self.ims).sqrt().clamp(0.0631, 15.85); - } - self.bg += (self.bg_t - self.bg) * self.bg_c; - let mut out = [pp[0] + (dt[0] * self.bg - pp[0]) * self.byp_s, pp[1] + (dt[1] * self.bg - pp[1]) * self.byp_s]; + // output limiter (processed path only: bypass, delta and solo are monitors / the untouched input) + let lo = self.lim.tick(pp, self.p.lim_on); + let mut out = [lo[0] + (db[0] - lo[0]) * self.byp_s, lo[1] + (db[1] - lo[1]) * self.byp_s]; // delta monitor self.d_s += ((if self.delta_on { 1.0 } else { 0.0 }) - self.d_s) * self.byp_c; + self.mon_d.advance(); + self.mon_d.put([cd[0] - y[0], cd[1] - y[1]]); if self.d_s > 0.0001 { + let dd = self.mon_d.tap(ll); for c in 0..2 { - out[c] += ((cd[c] - y[c]) - out[c]) * self.d_s; + out[c] += (dd[c] - out[c]) * self.d_s; } } // sidechain solo: what the detector hears (post gain/HP/LP), replaces the output - self.sc_s += ((if self.sc_solo && self.sc_act { 1.0 } else { 0.0 }) - self.sc_s) * self.byp_c; + self.sc_s += ((if self.sc_solo && sc_act { 1.0 } else { 0.0 }) - self.sc_s) * self.byp_c; + self.mon_s.advance(); + self.mon_s.put(scv); if self.sc_s > 0.0001 { + let sv = self.mon_s.tap(ll); for c in 0..2 { - out[c] += (scv[c] - out[c]) * self.sc_s; + out[c] += (sv[c] - out[c]) * self.sc_s; } } // meters @@ -1037,24 +596,10 @@ impl Engine { } } -/// Detector level of one source: optional low cut, then peak/RMS blend. -#[inline] -fn det_level(mut xd: f64, rm: &mut f64, hs: &mut [f64; 2], use_hp: bool, hc: &Coef, det_m: f64, rms_c: f64) -> f64 { - if use_hp { - xd = bq(hs, hc, xd); - } - let a = xd.abs(); - *rm += (xd * xd + DENORM - *rm) * rms_c; - if det_m > 0.0 { - a + det_m * (1.41421356 * rm.sqrt() - a) - } else { - a - } -} - #[cfg(test)] mod tests { use super::*; + use std::f64::consts::PI; const SR: f64 = 48000.0; @@ -1094,16 +639,20 @@ mod tests { (0..n).map(|i| a * (2.0 * PI * f * i as f64 / SR).sin()).collect() } + /// The limiter's constant delay at 48 kHz (always reported, limiter on or off). + const LIM_LAT: usize = 32 + 72; + #[test] fn neutral_settings_are_bit_transparent() { let mut e = Engine::new(SR); e.set_params(&neutral()); let x = noise(4800, 1); let y = run(&mut e, &x, 256); - for (a, b) in x.iter().zip(&y) { - assert!((a - b).abs() < 1e-12); + let ll = LIM_LAT; + for i in ll..x.len() { + assert!((x[i - ll] - y[i]).abs() < 1e-12); } - assert_eq!(e.latency(), 0); + assert_eq!(e.latency() as usize, ll); } #[test] @@ -1116,8 +665,9 @@ mod tests { let mut e = Engine::new(SR); e.smoothing = false; e.set_params(&p); + let lat = lat + LIM_LAT; assert_eq!(e.latency() as usize, lat); - let mut x = vec![0.0; 200]; + let mut x = vec![0.0; 400]; x[10] = 1.0; let y = run(&mut e, &x, 64); let peak = y.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0; @@ -1132,11 +682,63 @@ mod tests { p.lookahead_ms = 1.0; let mut e = Engine::new(SR); e.set_params(&p); - let mut x = vec![0.0; 200]; + let mut x = vec![0.0; 400]; x[5] = 1.0; let y = run(&mut e, &x, 64); - assert_eq!(e.latency(), 48); - assert!((y[5 + 48] - 1.0).abs() < 1e-9); + let lat = 48 + LIM_LAT; + assert_eq!(e.latency() as usize, lat); + assert!((y[5 + lat] - 1.0).abs() < 1e-9); + } + + #[test] + fn limiter_latency_is_reported_on_or_off() { + let mut p = neutral(); + let mut e = Engine::new(SR); + e.set_params(&p); + let off = e.latency(); + p.lim_on = true; + e.set_params(&p); + assert_eq!(e.latency(), off); + assert_eq!(off as usize, LIM_LAT); + } + + #[test] + fn limiter_holds_hot_output_at_the_ceiling_and_reports_reduction() { + let mut p = neutral(); + p.lim_on = true; + let mut e = Engine::new(SR); + e.set_params(&p); + let hot = sine(24000, 440.0, 2.0); + let y = run(&mut e, &hot, 256); + let pk = y[12000..].iter().fold(0.0f64, |m, v| m.max(v.abs())); + assert!(pk <= 0.9773 && pk > 0.95, "peak {pk}"); + assert!(e.lim_gr_pk > 5.0, "gr {}", e.lim_gr_pk); + // off: same engine settings pass the signal through untouched (apart from the delay) + p.lim_on = false; + let mut e = Engine::new(SR); + e.set_params(&p); + let y = run(&mut e, &hot, 256); + assert!((y[12000..].iter().fold(0.0f64, |m, v| m.max(v.abs())) - 2.0).abs() < 0.01); + assert_eq!(e.lim_gr_pk, 0.0); + } + + #[test] + fn limiter_does_not_touch_bypass_or_misalign_it() { + // bypass returns the dry input, delayed like the processed path, unlimited + let mut p = neutral(); + p.lim_on = true; + p.bypass = true; + let mut e = Engine::new(SR); + e.smoothing = false; + e.set_params(&p); + let hot = sine(24000, 440.0, 2.0); + let y = run(&mut e, &hot, 256); + let lat = e.latency() as usize; + let x = &hot[12000 - lat..24000 - lat]; + let o = &y[12000..24000]; + let (px, po) = (x.iter().fold(0.0f64, |m, v| m.max(v.abs())), o.iter().fold(0.0f64, |m, v| m.max(v.abs()))); + assert!(po > 1.5, "bypass output was limited: {po}"); + assert!((po / px - 1.0).abs() < 0.05, "gain {}", po / px); } #[test] @@ -1164,11 +766,11 @@ mod tests { p.knee = 0.0; p.thresh = -20.0; p.ratio = 4.0; - let g = GainComputer::from_params(&p); + let g = GainComputer::from_params(&p.comp()); assert_eq!(g.gr(-30.0), 0.0); assert!((g.gr(-8.0) - 12.0 * 0.75).abs() < 1e-12); p.knee = 6.0; - let g = GainComputer::from_params(&p); + let g = GainComputer::from_params(&p.comp()); assert_eq!(g.gr(-24.0), 0.0); assert!((g.gr(-17.0) - 3.0 * 0.75).abs() < 1e-12); // at knee top: full slope assert!(g.gr(-20.0) > 0.0 && g.gr(-20.0) < 3.0 * 0.75); // continuous inside @@ -1282,14 +884,19 @@ mod tests { } #[test] - fn bypass_equal_loudness_returns_dry_level() { + fn bypass_returns_the_dry_input_unchanged() { let mut p = neutral(); + p.drive = 80.0; // a hot saturator must not change what bypass returns p.bypass = true; let mut e = Engine::new(SR); e.set_params(&p); let x = noise(48000, 3); let y = run(&mut e, &x, 256); - assert!((rms(&y[24000..]) / rms(&x[24000..]) - 1.0).abs() < 0.02); + let lat = e.latency() as usize; + // sample-exact (delayed) copy of the input, whatever the chain does to the level + for i in 24000..48000 { + assert!((y[i] - x[i - lat]).abs() < 1e-9, "sample {i}"); + } } #[test] diff --git a/rust/satcomp-dsp/src/eq.rs b/rust/satcomp-dsp/src/eq.rs index 8570a6b..d5708d2 100644 --- a/rust/satcomp-dsp/src/eq.rs +++ b/rust/satcomp-dsp/src/eq.rs @@ -1,5 +1,5 @@ -//! EQ decode (stored slider values -> filter kind/freq/gain/Q) and the 10-filter bank -//! (2 stages x [3 bands + tilt low shelf + tilt high shelf]) with per-block coefficient ramps. +//! EQ decode (stored slider values -> filter kind/freq/gain/Q), the 5-filter stage bank +//! ([3 bands + tilt low shelf + tilt high shelf]) with per-block coefficient ramps, and `EqSection`, the stage as a block. use crate::biquad::{bq, eq_coef, Coef, IDENTITY}; use crate::params::EqStageParams; @@ -51,31 +51,32 @@ pub fn decode_tilt(st: &EqStageParams) -> (f64, f64) { (t, p) } -pub struct EqBank { - pub cur: [Coef; 10], - pub tgt: [Coef; 10], - pub delta: [Coef; 10], - pub sl: [[f64; 2]; 10], - pub sr: [[f64; 2]; 10], - pub active: [bool; 10], - pub running: [bool; 10], +/// One EQ stage: 3 bands + tilt low shelf + tilt high shelf (5 filters), with per-block coefficient ramps. +pub struct EqBank { + pub cur: [Coef; N], + pub tgt: [Coef; N], + pub delta: [Coef; N], + pub sl: [[f64; 2]; N], + pub sr: [[f64; 2]; N], + pub active: [bool; N], + pub running: [bool; N], } -impl Default for EqBank { +impl Default for EqBank { fn default() -> Self { Self { - cur: [[0.0; 5]; 10], - tgt: [[0.0; 5]; 10], - delta: [[0.0; 5]; 10], - sl: [[0.0; 2]; 10], - sr: [[0.0; 2]; 10], - active: [false; 10], - running: [false; 10], + cur: [[0.0; 5]; N], + tgt: [[0.0; 5]; N], + delta: [[0.0; 5]; N], + sl: [[0.0; 2]; N], + sr: [[0.0; 2]; N], + active: [false; N], + running: [false; N], } } } -impl EqBank { +impl EqBank { /// Set filter f's target (identity when inactive); wake a sleeping filter from its target with clean state. pub fn target(&mut self, f: usize, coef: Option, on: bool) { self.tgt[f] = if on { coef.unwrap_or(IDENTITY) } else { IDENTITY }; @@ -88,26 +89,8 @@ impl EqBank { self.active[f] = on; } - /// Returns (any filter of the stage active). Mirrors eq_setup() minus the output gain. - pub fn setup_stage(&mut self, st: usize, p: &EqStageParams, sr: f64) -> bool { - let mut any = false; - for b in 0..3 { - let d = decode_band(p, b); - let c = if d.on { Some(eq_coef(d.kind, d.freq, d.gain, d.q, sr)) } else { None }; - self.target(st * 5 + b, c, d.on); - any |= d.on; - } - let (t, pv) = decode_tilt(p); - let on = t != 0.0; - let ls = if on { Some(eq_coef(2, pv, -t * 0.5, 0.4, sr)) } else { None }; - let hs = if on { Some(eq_coef(3, pv, t * 0.5, 0.4, sr)) } else { None }; - self.target(st * 5 + 3, ls, on); - self.target(st * 5 + 4, hs, on); - any || on - } - - pub fn clear_stage(&mut self, st: usize) { - for f in st * 5..st * 5 + 5 { + pub fn clear(&mut self) { + for f in 0..N { self.sl[f] = [0.0; 2]; self.sr[f] = [0.0; 2]; } @@ -116,7 +99,7 @@ impl EqBank { /// Per block: ramp deltas so a coefficient change glides over one block; retire settled identity filters. pub fn prep(&mut self, block_len: usize) { let rn = 1.0 / block_len.max(1) as f64; - for f in 0..10 { + for f in 0..N { if !self.running[f] { continue; } @@ -132,13 +115,13 @@ impl EqBank { } } - pub fn stage_running(&self, st: usize) -> bool { - self.running[st * 5..st * 5 + 5].iter().any(|&r| r) + pub fn is_running(&self) -> bool { + self.running.iter().any(|&r| r) } #[inline] - pub fn process(&mut self, st: usize, xl: &mut f64, xr: &mut f64) { - for f in st * 5..st * 5 + 5 { + pub fn process(&mut self, xl: &mut f64, xr: &mut f64) { + for f in 0..N { if self.running[f] { for i in 0..5 { self.cur[f][i] += self.delta[f][i]; @@ -151,6 +134,105 @@ impl EqBank { } } +impl EqBank<5> { + /// Returns (any filter of the stage active). Mirrors eq_setup() minus the output gain. + pub fn setup(&mut self, p: &EqStageParams, sr: f64) -> bool { + let mut any = false; + for b in 0..3 { + let d = decode_band(p, b); + let c = if d.on { Some(eq_coef(d.kind, d.freq, d.gain, d.q, sr)) } else { None }; + self.target(b, c, d.on); + any |= d.on; + } + let (t, pv) = decode_tilt(p); + let on = t != 0.0; + let ls = if on { Some(eq_coef(2, pv, -t * 0.5, 0.4, sr)) } else { None }; + let hs = if on { Some(eq_coef(3, pv, t * 0.5, 0.4, sr)) } else { None }; + self.target(3, ls, on); + self.target(4, hs, on); + any || on + } +} + +/// An EQ stage as a signal block: the filter bank, a smoothed output gain and a smoothed enable crossfade. +pub struct EqSection { + pub bank: EqBank, + g: f64, + g_t: f64, + /// any band, the tilt or the output gain does something + pub act: bool, + en: f64, + prev_en: bool, + bs: f64, + run: bool, + bs_c: f64, + g_c: f64, +} + +impl Default for EqSection { + fn default() -> Self { + Self { bank: EqBank::default(), g: 1.0, g_t: 1.0, act: false, en: 1.0, prev_en: true, bs: 1.0, run: false, bs_c: 0.0, g_c: 0.0 } + } +} + +impl EqSection<5> { + /// SatComp stage: 3 bands + tilt from the stored parameters. + pub fn derive(&mut self, p: &EqStageParams, enabled: bool, sr: f64, snap: bool) { + let any = self.bank.setup(p, sr); + self.derive_gain(any, p.out_gain, enabled, sr, snap); + } +} + +impl EqSection { + /// After the caller set the bank's targets (`any` = some filter does something): output gain, enable crossfade and + /// smoothing. `enabled` = not bypassed. `snap` jumps the smoothed values to their targets (first parameter set). + pub fn derive_gain(&mut self, any: bool, out_gain_db: f64, enabled: bool, sr: f64, snap: bool) { + let g2 = out_gain_db.clamp(-12.0, 12.0); + self.g_t = (g2 * crate::level::LN10_20).exp(); + self.act = any || g2 != 0.0; + self.en = if enabled { 1.0 } else { 0.0 }; + if enabled && !self.prev_en { + self.bank.clear(); + self.g = self.g_t; + } + self.prev_en = enabled; + self.bs_c = crate::level::one_pole(sr, 0.01); + self.g_c = crate::level::one_pole(sr, 0.02); + if snap { + self.g = self.g_t; + self.bs = self.en; + } + } + + /// Per host block (before its samples). + pub fn begin_block(&mut self, n: usize) { + if (self.bs - self.en).abs() < 0.00001 { + self.bs = self.en; + } + self.bank.prep(n); + if (self.g - self.g_t).abs() < 0.0000001 { + self.g = self.g_t; + } + self.run = self.bank.is_running() || self.g != 1.0 || self.g_t != 1.0; + } + + #[inline] + pub fn tick(&mut self, x: [f64; 2]) -> [f64; 2] { + self.bs += (self.en - self.bs) * self.bs_c; + if self.run && self.bs > 0.0 { + let (mut xl, mut xr) = (x[0], x[1]); + self.bank.process(&mut xl, &mut xr); + self.g += (self.g_t - self.g) * self.g_c; + if self.bs >= 1.0 { + return [xl * self.g, xr * self.g]; + } + let b = self.bs; + return [x[0] + (xl * self.g - x[0]) * b, x[1] + (xr * self.g - x[1]) * b]; + } + x + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/rust/satcomp-dsp/src/halfband.rs b/rust/satcomp-dsp/src/halfband.rs index a96f19f..ae3257c 100644 --- a/rust/satcomp-dsp/src/halfband.rs +++ b/rust/satcomp-dsp/src/halfband.rs @@ -1,5 +1,5 @@ -//! Kaiser halfband filters + the shaper oversampling wrapper (x2: K=24 / x4: +K=8). -//! Port of mk_taps / hb_up / hb_down / sh_proc; latency 24 (x2) / 28 (x4) samples. +//! Kaiser halfband filters + the shaper oversampling wrapper (x2: K=24 / x4: +K=8 / x8: +K=8 again). +//! Port of mk_taps / hb_up / hb_down / sh_proc; latency 24 (x2) / 28 (x4) / 30 (x8, SatLim only) samples. use crate::shapers::ShaperLut; @@ -77,11 +77,22 @@ impl Hb { } } -/// Per-channel oversampling state (A = x2 stage, B = x4 stage). +/// Per-channel oversampling state (A = x2 stage, B = x4 stage, C = x8 stage). #[derive(Clone, Default)] pub struct Oversampler { a: Hb, b: Hb, + c: Hb, +} + +/// PDC latency (base-rate samples) of the oversampling chain for `os`: 0 off, 1 x2, 2 x4, 3 x8. +pub fn latency(os: i32) -> usize { + match os { + 0 => 0, + 1 => 24, + 2 => 28, + _ => 30, + } } pub struct Taps { @@ -106,22 +117,99 @@ impl Oversampler { *self = Self::default(); } - /// os: 0 off, 1 x2, 2 x4. + /// os: 0 off, 1 x2, 2 x4, 3 x8. #[inline] pub fn process(&mut self, taps: &Taps, lut: &ShaperLut, os: i32, x: f64) -> f64 { + self.process_fn(taps, os, x, |v| lut.eval(v)) + } + + /// As `process`, with any memoryless nonlinearity `f` run at the oversampled rate. + #[inline] + pub fn process_fn(&mut self, taps: &Taps, os: i32, x: f64, f: impl Fn(f64) -> f64) -> f64 { match os { - 0 => lut.eval(x), + 0 => f(x), 1 => { let (a0, a1) = self.a.up(&taps.a, 24, 31, x); - self.a.down(&taps.a, 24, 63, lut.eval(a0), lut.eval(a1)) + self.a.down(&taps.a, 24, 63, f(a0), f(a1)) + } + 2 => { + let (a0, a1) = self.a.up(&taps.a, 24, 31, x); + let (b0, b1) = self.b.up(&taps.b, 8, 7, a0); + let (b2, b3) = self.b.up(&taps.b, 8, 7, a1); + let c0 = self.b.down(&taps.b, 8, 15, f(b0), f(b1)); + let c1 = self.b.down(&taps.b, 8, 15, f(b2), f(b3)); + self.a.down(&taps.a, 24, 63, c0, c1) } _ => { + let (a0, a1) = self.a.up(&taps.a, 24, 31, x); + let (b0, b1) = self.b.up(&taps.b, 8, 7, a0); + let (b2, b3) = self.b.up(&taps.b, 8, 7, a1); + let (c0, c1) = self.c.up(&taps.b, 8, 7, b0); + let (c2, c3) = self.c.up(&taps.b, 8, 7, b1); + let (c4, c5) = self.c.up(&taps.b, 8, 7, b2); + let (c6, c7) = self.c.up(&taps.b, 8, 7, b3); + let d0 = self.c.down(&taps.b, 8, 15, f(c0), f(c1)); + let d1 = self.c.down(&taps.b, 8, 15, f(c2), f(c3)); + let d2 = self.c.down(&taps.b, 8, 15, f(c4), f(c5)); + let d3 = self.c.down(&taps.b, 8, 15, f(c6), f(c7)); + let e0 = self.b.down(&taps.b, 8, 15, d0, d1); + let e1 = self.b.down(&taps.b, 8, 15, d2, d3); + self.a.down(&taps.a, 24, 63, e0, e1) + } + } + } +} + +impl Oversampler { + /// Like `process`, plus the even part e(x) = (f(x) + f(-x)) / 2 of the shaper through the same up / down filters + /// (so the two are sample-aligned and `f - e` is the odd part). Returns (f, e). + #[inline] + pub fn process_fe(&mut self, taps: &Taps, lut: &ShaperLut, os: i32, x: f64, eb: &mut Oversampler) -> (f64, f64) { + let ev = |v: f64| 0.5 * (lut.eval(v) + lut.eval(-v)); + match os { + 0 => (lut.eval(x), ev(x)), + 1 => { + let (a0, a1) = self.a.up(&taps.a, 24, 31, x); + let f = self.a.down(&taps.a, 24, 63, lut.eval(a0), lut.eval(a1)); + let e = eb.a.down(&taps.a, 24, 63, ev(a0), ev(a1)); + (f, e) + } + 2 => { let (a0, a1) = self.a.up(&taps.a, 24, 31, x); let (b0, b1) = self.b.up(&taps.b, 8, 7, a0); let (b2, b3) = self.b.up(&taps.b, 8, 7, a1); let c0 = self.b.down(&taps.b, 8, 15, lut.eval(b0), lut.eval(b1)); let c1 = self.b.down(&taps.b, 8, 15, lut.eval(b2), lut.eval(b3)); - self.a.down(&taps.a, 24, 63, c0, c1) + let f = self.a.down(&taps.a, 24, 63, c0, c1); + let d0 = eb.b.down(&taps.b, 8, 15, ev(b0), ev(b1)); + let d1 = eb.b.down(&taps.b, 8, 15, ev(b2), ev(b3)); + let e = eb.a.down(&taps.a, 24, 63, d0, d1); + (f, e) + } + _ => { + let (a0, a1) = self.a.up(&taps.a, 24, 31, x); + let (b0, b1) = self.b.up(&taps.b, 8, 7, a0); + let (b2, b3) = self.b.up(&taps.b, 8, 7, a1); + let u = [b0, b1, b2, b3]; + let mut c = [0.0f64; 8]; + for (i, v) in u.iter().enumerate() { + let (p, q) = self.c.up(&taps.b, 8, 7, *v); + c[2 * i] = p; + c[2 * i + 1] = q; + } + let mut d = [0.0f64; 4]; + let mut de = [0.0f64; 4]; + for i in 0..4 { + d[i] = self.c.down(&taps.b, 8, 15, lut.eval(c[2 * i]), lut.eval(c[2 * i + 1])); + de[i] = eb.c.down(&taps.b, 8, 15, ev(c[2 * i]), ev(c[2 * i + 1])); + } + let e0 = self.b.down(&taps.b, 8, 15, d[0], d[1]); + let e1 = self.b.down(&taps.b, 8, 15, d[2], d[3]); + let f = self.a.down(&taps.a, 24, 63, e0, e1); + let g0 = eb.b.down(&taps.b, 8, 15, de[0], de[1]); + let g1 = eb.b.down(&taps.b, 8, 15, de[2], de[3]); + let e = eb.a.down(&taps.a, 24, 63, g0, g1); + (f, e) } } } @@ -148,7 +236,8 @@ mod tests { } lut.periodic = false; let taps = Taps::new(); - for (os, lat) in [(1, 24usize), (2, 28usize)] { + for (os, lat) in [(1, 24usize), (2, 28usize), (3, 30usize)] { + assert_eq!(latency(os), lat); let mut ov = Oversampler::default(); let n = 400; // 300 Hz-ish sine at 48k, well inside the passband diff --git a/rust/satcomp-dsp/src/keyinput.rs b/rust/satcomp-dsp/src/keyinput.rs new file mode 100644 index 0000000..5726b9b --- /dev/null +++ b/rust/satcomp-dsp/src/keyinput.rs @@ -0,0 +1,79 @@ +//! External key conditioning for a detector: gain, then high-pass, then low-pass, then a delay so the key lines up with a +//! signal that was delayed by an upstream block (the saturator's oversampling latency). + +use crate::biquad::{self, bq, Coef}; +use crate::delay::StereoDelay; +use crate::level::{one_pole, LN10_20}; + +pub struct KeyInput { + g: f64, + g_t: f64, + g_c: f64, + use_hp: bool, + use_lp: bool, + hpc: Coef, + lpc: Coef, + hps: [[f64; 2]; 2], + lps: [[f64; 2]; 2], + ring: StereoDelay<64>, +} + +impl Default for KeyInput { + fn default() -> Self { + Self::new() + } +} + +impl KeyInput { + pub fn new() -> Self { + Self { + g: 1.0, + g_t: 1.0, + g_c: 0.0, + use_hp: false, + use_lp: false, + hpc: biquad::IDENTITY, + lpc: biquad::IDENTITY, + hps: [[0.0; 2]; 2], + lps: [[0.0; 2]; 2], + ring: StereoDelay::new(), + } + } + + /// `gain_db`, `hp` (<= 20.5 = off) and `lp` (>= 19900 = off) in Hz. + pub fn derive(&mut self, gain_db: f64, hp: f64, lp: f64, sr: f64) { + self.g_t = (gain_db * LN10_20).exp(); + self.use_hp = hp > 20.5; + if self.use_hp { + self.hpc = biquad::hp(hp, 0.70710678, sr); + } + self.use_lp = lp < 19900.0; + if self.use_lp { + self.lpc = biquad::lp(lp, 0.70710678, sr); + } + self.g_c = one_pole(sr, 0.02); + } + + /// Call every sample. `key` is the raw key input while a key is active, `None` otherwise (the delay ring keeps + /// moving either way so it stays aligned). Returns the conditioned key delayed by `delay` samples, or zeros. + #[inline] + pub fn tick(&mut self, key: Option<[f64; 2]>, delay: usize) -> [f64; 2] { + self.g += (self.g_t - self.g) * self.g_c; + self.ring.advance(); + let mut out = [0.0f64; 2]; + if let Some(s_in) = key { + for c in 0..2 { + let mut v = s_in[c] * self.g; + if self.use_hp { + v = bq(&mut self.hps[c], &self.hpc, v); + } + if self.use_lp { + v = bq(&mut self.lps[c], &self.lpc, v); + } + self.ring.0[c].put(v); + out[c] = self.ring.0[c].tap(delay); + } + } + out + } +} diff --git a/rust/satcomp-dsp/src/level.rs b/rust/satcomp-dsp/src/level.rs new file mode 100644 index 0000000..1abeff8 --- /dev/null +++ b/rust/satcomp-dsp/src/level.rs @@ -0,0 +1,57 @@ +//! Level measurement helpers: one-pole mean-square meters and the 3-second gain-match accumulator. + +use crate::DENORM; + +/// One-pole smoothing coefficient for a time constant, `1 - exp(-1/(sr*secs))`. +pub fn one_pole(sr: f64, secs: f64) -> f64 { + 1.0 - (-1.0 / (sr * secs)).exp() +} + +/// Smoothed stereo mean-square level: `v += ((l^2 + r^2)/2 + DENORM - v) * c`. +#[inline] +pub fn ms_step(v: &mut f64, l: f64, r: f64, c: f64) { + *v += ((l * l + r * r) * 0.5 + DENORM - *v) * c; +} + +/// `10/ln(10)`: ln of a power ratio to dB. +pub const DB_POW: f64 = 4.3429448; +/// `20/ln(10)`: ln of an amplitude ratio to dB. +pub const DB_AMP: f64 = 8.6858896; +/// dB to ln(gain). +pub const LN10_20: f64 = 0.11512925; + +/// Time-average of a dB difference over `LEN` seconds of gated signal (the level-match measurement). +#[derive(Clone, Copy, Default)] +pub struct Matcher { + pub active: bool, + acc: f64, + /// seconds measured so far + pub t: f64, +} + +impl Matcher { + pub const LEN: f64 = 3.0; + + pub fn start(&mut self) { + self.active = true; + self.acc = 0.0; + self.t = 0.0; + } + + pub fn stop(&mut self) { + self.active = false; + } + + /// Feed `diff_db` for `dt` seconds. Returns the negated average once `LEN` seconds are collected (the measurement + /// ends); the caller clamps / rounds it. + pub fn step(&mut self, diff_db: f64, dt: f64) -> Option { + self.acc += diff_db * dt; + self.t += dt; + if self.t >= Self::LEN { + self.active = false; + Some(-self.acc / self.t) + } else { + None + } + } +} diff --git a/rust/satcomp-dsp/src/lib.rs b/rust/satcomp-dsp/src/lib.rs index 2021f2b..21df9f2 100644 --- a/rust/satcomp-dsp/src/lib.rs +++ b/rust/satcomp-dsp/src/lib.rs @@ -3,13 +3,22 @@ //! against JSFX renders (EEL2 is f64 as well). pub mod biquad; +pub mod compressor; +pub mod delay; pub mod engine; pub mod eq; pub mod halfband; +pub mod keyinput; +pub mod level; +pub mod limiter; pub mod params; +pub mod saturator; pub mod shapers; -pub use engine::{Engine, GainComputer, ScopeRing, TapRing}; +pub use compressor::{CompParams, Compressor, GainComputer}; +pub use engine::{Engine, ScopeRing, TapRing}; +pub use limiter::{Limiter, TruePeak}; +pub use saturator::{SatParams, Saturator}; pub use params::{EqBandParams, EqStageParams, Params}; /// dB (amplitude) to linear gain, same constant as the JSFX (`exp(db*0.11512925)`). diff --git a/rust/satcomp-dsp/src/limiter.rs b/rust/satcomp-dsp/src/limiter.rs new file mode 100644 index 0000000..7c1ab26 --- /dev/null +++ b/rust/satcomp-dsp/src/limiter.rs @@ -0,0 +1,846 @@ +//! True-peak brickwall limiter: the last stage of the processed path. +//! +//! * Detection: the stereo-linked peak of the input, including the inter-sample peaks found by a 4x polyphase +//! interpolator (2x at 96 kHz-class rates, plain sample peak above that: inter-sample overs vanish at high rates). +//! `set_hi(true)` (SatLim) doubles each of those (8x / 4x / 2x) for material that is all inter-sample peaks: clipped, +//! heavily shaped programme, where a 4x grid under-reads by a few tenths of a dB. +//! * Hard clip: every sample is clipped at `CLIP_OVER_DB` above the ceiling before detection and again on the delayed +//! audio, so a tall transient is shaved off clean and the gain stage only ever has to find the small remainder (a limiter +//! alone would duck the whole body for the length of its release after an 8 dB spike). Faded in with the limiter. +//! * Gain: the gain needed to hold the ceiling, a sliding minimum over the lookahead, then a boxcar of the lookahead +//! length. The result ramps down so that it reaches the full reduction exactly when the peak leaves the delay line. +//! Release is program dependent (fast for isolated peaks, slow under sustained reduction) and can only make the gain +//! *lower* than the attack ramp, never higher, so the brickwall guarantee holds. +//! * The audio is delayed by `latency()` samples whether or not the limiter is engaged (constant PDC); the detector +//! keeps running while it is off so switching it on is click-free (the engagement is a 10 ms linear fade). +//! +//! The ceiling is -0.2 dBTP unless the owner sets it (`set_ceiling_db`; SatLim): the interpolator is not an ideal +//! reconstruction filter and the gain changes between samples, so that margin keeps the true peak of the output at or +//! below 0 dBTP. With the lookahead off (`set_lookahead(false)`, SatLim) the limiter has no delay and no interpolator: the +//! gain follows the *sample* peak instantly (attack 0) and releases as usual, so inter-sample overs can pass. + +use crate::delay::StereoDelay; +use std::collections::VecDeque; + +/// Interpolator taps per phase (delay = TAPS / 2 samples). 64 keeps white noise at Nyquist within ~0.1 dB of true. +const TAPS: usize = 64; +/// Output ceiling, dBTP. +pub const CEILING_DB: f64 = -0.2; +/// Dev-only tuning hook (feature `tune`): an environment variable overrides a constant, for offline sweeps. +#[cfg(feature = "tune")] +fn tune(k: &str, d: f64) -> f64 { + std::env::var(k).ok().and_then(|v| v.parse().ok()).unwrap_or(d) +} +#[cfg(not(feature = "tune"))] +fn tune(_k: &str, d: f64) -> f64 { + d +} +/// The hard clip sits this far above the ceiling (dB). At 0 the clip does the bulk of the work (peaks are shaved off clean, +/// like a clipper in front of a brickwall limiter) and the gain stage only has to catch the inter-sample excess of the +/// clipped waveform, so its release never rides a big spike. Raising it trades clip distortion for gain-stage ducking: +/// measured on a hot preset, +2 dB ducked the body in 19 % of 10 ms windows (>1 dB), 0 dB in 5 %. +const CLIP_OVER_DB: f64 = 0.0; +/// Release time constant range, seconds: fast for isolated peaks, slow under sustained reduction. +const TAU_MIN: f64 = 0.015; +const TAU_MAX: f64 = 0.080; +/// Lookahead / attack ramp, seconds. +const LOOKAHEAD_S: f64 = 0.0015; +/// Capacity of the delay line and of the min / boxcar buffers (samples). +const CAP: usize = 1024; + +fn i0(x: f64) -> f64 { + let (mut sm, mut t) = (1.0, 1.0); + for k in 1..40 { + let h = x * 0.5 / k as f64; + t *= h * h; + sm += t; + } + sm +} + +/// Kaiser-windowed sinc phases: for `r` x oversampling, `r - 1` filters that interpolate at `(i + 1) / r` between the +/// two centre samples of the `TAPS`-sample window. +/// Most interpolated points per sample (8x oversampling). +const PH: usize = 7; + +/// Oversampling factor of the detector for a sample rate; `hi` doubles it. +fn factor(sr: f64, hi: bool) -> usize { + let r = if sr <= 50_000.0 { + 4 + } else if sr <= 100_000.0 { + 2 + } else { + 1 + }; + if hi { + r * 2 + } else { + r + } +} + +fn phase_taps(r: usize) -> [[f64; TAPS]; PH] { + let mut c = [[0.0; TAPS]; PH]; + let beta = 5.0; + let half = TAPS as f64 * 0.5; + for ph in 0..r.saturating_sub(1) { + let f = (ph + 1) as f64 / r as f64; + let mut sum = 0.0; + for (j, w) in c[ph].iter_mut().enumerate() { + let t = j as f64 - (half - 1.0 + f); + let s = if t.abs() < 1e-12 { 1.0 } else { (std::f64::consts::PI * t).sin() / (std::f64::consts::PI * t) }; + let r2 = (t / half).powi(2).min(1.0); + let v = s * i0(beta * (1.0 - r2).sqrt()) / i0(beta); + *w = v; + sum += v; + } + for w in c[ph].iter_mut() { + *w /= sum; + } + } + c +} + +/// True-peak meter: the limiter's own interpolator (4x at 48 kHz-class rates, 2x at 96 kHz-class, sample peak above), +/// running every sample. Reads `TAPS / 2` samples late, which a meter does not mind. +pub struct TruePeak { + r: usize, + coef: [[f64; TAPS]; PH], + hist: [[f64; 2 * TAPS]; 2], + pos: usize, +} + +impl TruePeak { + pub fn new(sr: f64) -> Self { + Self::with_precision(sr, false) + } + + /// `hi` doubles the oversampling (8x at 48 kHz-class rates, 4x at 96 kHz-class, 2x above): see `Limiter::set_hi`. + pub fn with_precision(sr: f64, hi: bool) -> Self { + let r = factor(sr, hi); + Self { r, coef: phase_taps(r), hist: [[0.0; 2 * TAPS]; 2], pos: 0 } + } + + /// Peak (linear, both channels) of this sample and the inter-sample points around it. + pub fn tick(&mut self, x: [f64; 2]) -> f64 { + let p = self.pos; + for c in 0..2 { + self.hist[c][p] = x[c]; + self.hist[c][p + TAPS] = x[c]; + } + self.pos = (p + 1) % TAPS; + let mut pk = x[0].abs().max(x[1].abs()); + if self.r == 1 { + return pk; + } + let q = self.pos; + for c in 0..2 { + let win = &self.hist[c][q..q + TAPS]; + for ph in 0..self.r - 1 { + let acc: f64 = win.iter().zip(self.coef[ph].iter()).map(|(a, b)| a * b).sum(); + pk = pk.max(acc.abs()); + } + } + pk + } +} + +pub struct Limiter { + sr: f64, + r: usize, + d: usize, + l: usize, + ceil: f64, + coef: [[f64; TAPS]; PH], + /// largest sum of |tap| over the phases: an interpolated point can't exceed `lam * max|window|`, so a quiet + /// window needs no interpolation at all (exactly the same result, far less work on quiet programme) + lam: f64, + /// samples left until the last loud one leaves the interpolator window + hot: usize, + // interpolator history (double-written ring so the window is contiguous) + hist: [[f64; 2 * TAPS]; 2], + hpos: usize, + need_prev: f64, + // min over the last l + 1 targets + dq: VecDeque<(u64, f64)>, + n: u64, + // boxcar over the last l minima + ring: Vec, + rpos: usize, + sum: f64, + resync: u32, + // release + g: f64, + avg: f64, + avg_c: f64, + rc: f64, + rc_n: u32, + // engagement fade + on_s: f64, + on_step: f64, + delay: StereoDelay, + clipv: f64, + tau0: f64, + tau1: f64, + /// internal hard clip at the ceiling (on by default; SatLim does its own, oversampled) + clip_en: bool, + /// lookahead + true-peak detection (on by default); off = zero latency, sample-peak, instant attack + look: bool, + /// detector oversampling doubled (off by default; SatLim) + hi: bool, + /// after the lookahead is switched on: for `seed_n` more samples no target may be above `seed_g` (the audio already in + /// the delay line was never seen by the detector) + seed_n: usize, + seed_g: f64, + /// The input sample that `tick` just returned the limited version of (the delayed input), for a delta monitor. + pub last_in: [f64; 2], + /// Smallest applied gain since the engine last reset it (linear, 1.0 = no reduction). + pub gmin: f64, +} + +impl Limiter { + pub fn new(sr: f64) -> Self { + let mut s = Self { + sr: 0.0, + r: 1, + d: 0, + l: 4, + ceil: 10f64.powf(CEILING_DB / 20.0), + coef: [[0.0; TAPS]; PH], + lam: 1.0, + hot: 0, + hist: [[0.0; 2 * TAPS]; 2], + hpos: 0, + need_prev: 1.0, + dq: VecDeque::with_capacity(CAP + 2), + n: 0, + ring: vec![1.0; CAP], + rpos: 0, + sum: 4.0, + resync: 0, + g: 1.0, + avg: 0.0, + avg_c: 0.0, + rc: 0.0, + rc_n: 0, + on_s: 0.0, + on_step: 0.0, + delay: StereoDelay::new(), + clipv: 10f64.powf((CEILING_DB + tune("LIM_CLIP", CLIP_OVER_DB)) / 20.0), + tau0: tune("LIM_TAU0", TAU_MIN), + tau1: tune("LIM_TAU1", TAU_MAX), + clip_en: true, + look: true, + hi: false, + seed_n: 0, + seed_g: 1.0, + last_in: [0.0; 2], + gmin: 1.0, + }; + s.set_sample_rate(sr); + s + } + + /// Re-derive everything that depends on the sample rate. A no-op while the rate is unchanged. + pub fn set_sample_rate(&mut self, sr: f64) { + if sr == self.sr { + return; + } + self.sr = sr; + self.seed_n = 0; + self.r = factor(sr, self.hi); + self.d = if self.r > 1 { TAPS / 2 } else { 0 }; + self.l = ((LOOKAHEAD_S * sr).round() as usize).clamp(4, CAP - TAPS - 8); + self.coef = phase_taps(self.r); + self.lam = self.coef.iter().map(|c| c.iter().map(|v| v.abs()).sum::()).fold(1.0, f64::max); + self.hot = 0; + self.hist = [[0.0; 2 * TAPS]; 2]; + self.need_prev = 1.0; + self.dq.clear(); + self.ring.iter_mut().for_each(|v| *v = 1.0); + self.rpos = 0; + self.sum = self.l as f64; + self.g = 1.0; + self.avg = 0.0; + self.avg_c = 1.0 - (-1.0 / (sr * 0.4)).exp(); + self.rc_n = 0; + self.on_step = 1.0 / (0.01 * sr); + self.delay.0.iter_mut().for_each(|d| d.clear()); + self.gmin = 1.0; + } + + /// Ceiling in dB (the hard clip follows it). Cheap: call it whenever the parameter moves. + pub fn set_ceiling_db(&mut self, db: f64) { + self.ceil = 10f64.powf(db / 20.0); + self.clipv = 10f64.powf((db + tune("LIM_CLIP", CLIP_OVER_DB)) / 20.0); + } + + /// Release: the slow end of the program-dependent time constant, ms (the fast end stays at 15 ms or below it). + pub fn set_release_ms(&mut self, ms: f64) { + self.tau1 = (ms * 0.001).max(0.001); + self.tau0 = self.tau1.min(TAU_MIN); + } + + /// Double the detector's oversampling (8x at 48 kHz-class rates, 4x at 96 kHz-class, 2x above, where the latency + /// then grows by the interpolator's `TAPS / 2`). For programme that is mostly inter-sample peaks. Resets the state. + pub fn set_hi(&mut self, hi: bool) { + if hi == self.hi { + return; + } + self.hi = hi; + let sr = std::mem::replace(&mut self.sr, 0.0); + self.set_sample_rate(sr); + } + + /// The internal hard clip at the ceiling. + pub fn set_clip(&mut self, on: bool) { + self.clip_en = on; + } + + /// Lookahead on = true-peak brickwall with `latency()` delay; off = zero latency (see the module docs). + /// Changing it resets the gain state (the delay the host compensates for changes with it). + pub fn set_lookahead(&mut self, on: bool) { + if on == self.look { + return; + } + self.look = on; + // Switching on: the delay line already holds the last `d + l` samples, which the detector never saw. Start from + // the gain that keeps the loudest of them at the ceiling (and from the gain in force), and hold every target at + // or below it until they have left the line: no burst of unlimited audio. Switching off needs nothing (instant). + let mut seed = 1.0f64; + if on { + let mut pk = 0.0f64; + for k in 0..self.d + self.l { + let y = self.delay.tap(k); + pk = pk.max(y[0].abs()).max(y[1].abs()); + } + seed = self.g.min(if pk > self.ceil { self.ceil / pk } else { 1.0 }); + } + self.seed_g = seed; + self.seed_n = if on && seed < 1.0 { self.d + self.l } else { 0 }; + self.hot = 0; + self.hist = [[0.0; 2 * TAPS]; 2]; + self.need_prev = 1.0; + self.dq.clear(); + self.ring.iter_mut().for_each(|v| *v = seed); + self.rpos = 0; + self.sum = self.l as f64 * seed; + self.g = seed; + self.avg = 0.0; + self.rc_n = 0; + } + + pub fn lookahead(&self) -> bool { + self.look + } + + /// Jump the engagement fade to its end state (a fresh engine must limit from its first sample). + pub fn snap_on(&mut self, on: bool) { + self.on_s = if on { 1.0 } else { 0.0 }; + } + + /// Samples the audio is delayed by (detector + lookahead; 0 with the lookahead off), always. + pub fn latency(&self) -> usize { + if self.look { + self.d + self.l + } else { + 0 + } + } + + /// Current applied gain (1.0 = idle). + pub fn gain(&self) -> f64 { + self.g + } + + /// Peak (linear) of the input sample `D` samples ago and the inter-sample points after it. + #[inline] + fn detect(&mut self, x: [f64; 2]) -> f64 { + let p = self.hpos; + let mut pk = 0.0f64; + for c in 0..2 { + self.hist[c][p] = x[c]; + self.hist[c][p + TAPS] = x[c]; + } + self.hpos = (p + 1) % TAPS; + if self.r == 1 { + return x[0].abs().max(x[1].abs()); + } + if x[0].abs().max(x[1].abs()) * self.lam > self.ceil { + self.hot = TAPS; + } + if self.hot == 0 { + return 0.0; + } + self.hot -= 1; + let q = self.hpos; + for c in 0..2 { + let win = &self.hist[c][q..q + TAPS]; + pk = pk.max(win[TAPS / 2 - 1].abs()); + for ph in 0..self.r - 1 { + let acc: f64 = win.iter().zip(self.coef[ph].iter()).map(|(a, b)| a * b).sum(); + pk = pk.max(acc.abs()); + } + } + pk + } + + /// One stereo sample in -> the same sample `latency()` later, limited when `on`. + #[inline] + pub fn tick(&mut self, x: [f64; 2], on: bool) -> [f64; 2] { + self.delay.advance(); + self.delay.put(x); + let l = self.l; + let cv = if self.clip_en { self.clipv } else { f64::INFINITY }; + + if !self.look { + return self.tick_instant(x, on, cv); + } + + // ---- target gain for the sample the detector is looking at + let xc = [x[0].clamp(-cv, cv), x[1].clamp(-cv, cv)]; + let pk = self.detect(xc); + let need = if pk > self.ceil { self.ceil / pk } else { 1.0 }; + let mut t = need.min(self.need_prev); + self.need_prev = need; + if self.seed_n > 0 { + self.seed_n -= 1; + t = t.min(self.seed_g); + } + + // ---- sliding minimum over the last l + 1 targets + self.n += 1; + while let Some(&(_, v)) = self.dq.back() { + if v >= t { + self.dq.pop_back(); + } else { + break; + } + } + self.dq.push_back((self.n, t)); + while let Some(&(i, _)) = self.dq.front() { + if self.n - i > l as u64 { + self.dq.pop_front(); + } else { + break; + } + } + let s = self.dq.front().map(|e| e.1).unwrap_or(1.0); + + // ---- boxcar over the last l minima + self.sum += s - self.ring[self.rpos]; + self.ring[self.rpos] = s; + self.rpos += 1; + if self.rpos >= l { + self.rpos = 0; + } + self.resync += 1; + if self.resync >= 32768 { + self.resync = 0; + self.sum = self.ring[..l].iter().sum(); + } + let a = (self.sum / l as f64).min(1.0); + + // ---- program-dependent release, never above the attack ramp + // how long the signal has been demanding reduction (the attack ramp, not the gain after release: that would + // feed back and slow every release) + self.avg += ((1.0 - a) - self.avg) * self.avg_c; + if self.rc_n == 0 { + let tau = self.tau0 + (self.tau1 - self.tau0) * (self.avg / 0.25).min(1.0); + self.rc = 1.0 - (-1.0 / (self.sr * tau)).exp(); + self.rc_n = 16; + } + self.rc_n -= 1; + let rel = 1.0 - (1.0 - self.g) * (1.0 - self.rc); + let mut g = a.min(rel); + if g > 1.0 - 1e-7 { + g = 1.0; + } + self.g = g; + + // ---- engagement fade (linear, exact at both ends) + let target = if on { 1.0 } else { 0.0 }; + if self.on_s < target { + self.on_s = (self.on_s + self.on_step).min(target); + } else if self.on_s > target { + self.on_s = (self.on_s - self.on_step).max(target); + } + let ge = 1.0 + (g - 1.0) * self.on_s; + let y = self.delay.tap(self.d + l); + // the reduction readout counts the clip too: gain the output sample lost against the unclipped one + self.last_in = y; + let pk = y[0].abs().max(y[1].abs()); + let clip_g = if pk > cv { 1.0 + (cv / pk - 1.0) * self.on_s } else { 1.0 }; + if ge * clip_g < self.gmin { + self.gmin = ge * clip_g; + } + // the hard clip is part of the engaged path (faded in with it) + let yc = [y[0].clamp(-cv, cv), y[1].clamp(-cv, cv)]; + let yo = [y[0] + (yc[0] - y[0]) * self.on_s, y[1] + (yc[1] - y[1]) * self.on_s]; + [yo[0] * ge, yo[1] * ge] + } + + /// Lookahead off: no delay, gain from this sample's own (sample) peak, so the output never exceeds the ceiling at the + /// sample points; release as in the lookahead path. + #[inline] + fn tick_instant(&mut self, x: [f64; 2], on: bool, cv: f64) -> [f64; 2] { + self.last_in = x; + let xc = [x[0].clamp(-cv, cv), x[1].clamp(-cv, cv)]; + let pk = xc[0].abs().max(xc[1].abs()); + let need = if pk > self.ceil { self.ceil / pk } else { 1.0 }; + self.avg += ((1.0 - need) - self.avg) * self.avg_c; + if self.rc_n == 0 { + let tau = self.tau0 + (self.tau1 - self.tau0) * (self.avg / 0.25).min(1.0); + self.rc = 1.0 - (-1.0 / (self.sr * tau)).exp(); + self.rc_n = 16; + } + self.rc_n -= 1; + let rel = 1.0 - (1.0 - self.g) * (1.0 - self.rc); + let mut g = need.min(rel); + if g > 1.0 - 1e-7 { + g = 1.0; + } + self.g = g; + let target = if on { 1.0 } else { 0.0 }; + if self.on_s < target { + self.on_s = (self.on_s + self.on_step).min(target); + } else if self.on_s > target { + self.on_s = (self.on_s - self.on_step).max(target); + } + let ge = 1.0 + (g - 1.0) * self.on_s; + let pk0 = x[0].abs().max(x[1].abs()); + let clip_g = if pk0 > cv { 1.0 + (cv / pk0 - 1.0) * self.on_s } else { 1.0 }; + if ge * clip_g < self.gmin { + self.gmin = ge * clip_g; + } + let yo = [x[0] + (xc[0] - x[0]) * self.on_s, x[1] + (xc[1] - x[1]) * self.on_s]; + [yo[0] * ge, yo[1] * ge] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f64::consts::PI; + + fn lcg(s: &mut u64) -> f64 { + *s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((*s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0 + } + + /// True peak by brute force: 16x Kaiser-sinc reconstruction (64 taps each side), independent of the limiter's own. + fn true_peak(x: &[f64]) -> f64 { + let beta = 9.0; + let half = 48i64; + // coefficient table per phase, computed once + let w: Vec> = (1..8) + .map(|k| { + let f = k as f64 / 8.0; + (-half + 1..=half) + .map(|j| { + let t = j as f64 - f; + (PI * t).sin() / (PI * t) * i0(beta * (1.0 - (t / half as f64).powi(2)).max(0.0).sqrt()) / i0(beta) + }) + .collect() + }) + .collect(); + let mut pk = 0.0f64; + for n in (half as usize)..x.len() - half as usize { + pk = pk.max(x[n].abs()); + for wk in &w { + let acc: f64 = wk.iter().enumerate().map(|(i, c)| c * x[n + i + 1 - half as usize]).sum(); + pk = pk.max(acc.abs()); + } + } + pk + } + + fn run(lim: &mut Limiter, l: &[f64], r: &[f64], on: bool) -> (Vec, Vec) { + let (mut a, mut b) = (Vec::new(), Vec::new()); + for i in 0..l.len() { + let y = lim.tick([l[i], r[i]], on); + a.push(y[0]); + b.push(y[1]); + } + (a, b) + } + + fn db(x: f64) -> f64 { + 20.0 * x.log10() + } + + #[test] + fn quiet_signal_is_an_exact_delayed_copy() { + for sr in [44100.0, 48000.0, 96000.0, 192000.0] { + let mut lim = Limiter::new(sr); + let mut s = 7; + let x: Vec = (0..20000).map(|_| lcg(&mut s) * 0.5).collect(); + let (y, _) = run(&mut lim, &x, &x, true); + let lat = lim.latency(); + for i in lat..x.len() { + assert_eq!(y[i], x[i - lat], "sr {sr} sample {i}"); + } + assert_eq!(lim.gmin, 1.0); + } + } + + #[test] + fn off_is_a_pure_delay_even_on_hot_signals() { + let mut lim = Limiter::new(48000.0); + let x: Vec = (0..8000).map(|i| 3.0 * (i as f64 * 0.05).sin()).collect(); + let (y, _) = run(&mut lim, &x, &x, false); + let lat = lim.latency(); + for i in lat..x.len() { + assert_eq!(y[i], x[i - lat]); + } + assert_eq!(lim.gmin, 1.0); + } + + fn stress(sr: f64) -> (Vec, Vec) { + let n = (sr * 0.4) as usize; + let mut s = 1; + let (mut l, mut r) = (vec![0.0; n], vec![0.0; n]); + for i in 0..n { + let t = i as f64 / sr; + // hot noise bed, an fs/4-ish tone whose samples straddle the peaks (classic inter-sample over), + // a 10 kHz resonant-style burst, and isolated spike clicks + let bed = lcg(&mut s) * 0.5; + // 2 ms raised-cosine fades: a tone gated hard at exactly fs/4 is not programme material (the splatter alone + // is beyond any short interpolator), a faded one is a synth note + let fade = ((t - 0.1) / 0.002).clamp(0.0, 1.0).min(((0.2 - t) / 0.002).clamp(0.0, 1.0)); + let fs4 = if (0.1..0.2).contains(&t) { 1.4 * 0.5 * (1.0 - (PI * fade).cos()) * (2.0 * PI * sr * 0.25 * t + 0.7854).sin() } else { 0.0 }; + let burst = if (0.25..0.35).contains(&t) { 1.8 * (2.0 * PI * 10000.0 * t).sin() * (-(t - 0.25) * 30.0).exp() } else { 0.0 }; + let click = if i % 4800 == 100 { 2.5 } else { 0.0 }; + l[i] = bed + fs4 + burst + click; + r[i] = bed * 0.7 - fs4 * 0.9 + burst * 0.5 - click * 0.3; + } + (l, r) + } + + #[test] + fn output_true_peak_stays_under_the_ceiling() { + for sr in [44100.0, 48000.0, 96000.0] { + let mut lim = Limiter::new(sr); + let (l, r) = stress(sr); + let (yl, yr) = run(&mut lim, &l, &r, true); + let skip = lim.latency() + 200; + for (name, y) in [("L", &yl), ("R", &yr)] { + let tp = db(true_peak(&y[skip..])); + // The ceiling is -0.2. Full-band white noise on top of a hot tone near Nyquist is the worst case for any + // finite interpolator (it under-reads content right at fs/2 by a few hundredths of a dB), so the stress + // may touch 0 dBTP but must not go meaningfully over it. Programme material stays well below. + assert!(tp <= 0.1, "sr {sr} {name}: true peak {tp:.3} dBTP"); + assert!(lim.gmin < 0.5, "limiter never engaged"); + } + } + } + + #[test] + fn a_tall_spike_does_not_duck_the_body_after_it() { + // a steady -10 dB tone with one 1 ms spike at +12 dB: 30 ms later the tone must be back within 1 dB + let sr = 48000.0; + let mut lim = Limiter::new(sr); + let n = 24000; + let x: Vec = (0..n).map(|i| { + let t = i as f64 / sr; + let tone = 0.316 * (2.0 * PI * 200.0 * t).sin(); + if (12000..12048).contains(&i) { tone + 4.0 * (PI * (i - 12000) as f64 / 48.0).sin() } else { tone } + }).collect(); + let (y, _) = run(&mut lim, &x, &x, true); + let lat = lim.latency(); + let from = 12000 + lat + (0.03 * sr) as usize; + let rms = |v: &[f64]| (v.iter().map(|a| a * a).sum::() / v.len() as f64).sqrt(); + let g = db(rms(&y[from..from + 4800]) / rms(&x[from - lat..from - lat + 4800])); + assert!(g > -1.0, "body still ducked {g:.2} dB, 30 ms after the spike"); + } + + #[test] + fn it_actually_limits_close_to_the_ceiling() { + // a loud steady sine: the output should sit near the ceiling, not far below it + let sr = 48000.0; + let mut lim = Limiter::new(sr); + let x: Vec = (0..48000).map(|i| 2.0 * (2.0 * PI * 1000.0 * i as f64 / sr).sin()).collect(); + let (y, _) = run(&mut lim, &x, &x, true); + let pk = y[24000..].iter().fold(0.0f64, |m, v| m.max(v.abs())); + assert!(db(pk) > -0.4 && db(pk) < -0.1, "{} dB", db(pk)); + } + + #[test] + fn releases_back_to_unity() { + let sr = 48000.0; + let mut lim = Limiter::new(sr); + let mut x: Vec = (0..4800).map(|i| 4.0 * (i as f64 * 0.1).sin()).collect(); + x.extend(vec![0.1; 48000 * 3]); + run(&mut lim, &x, &x, true); + assert_eq!(lim.gain(), 1.0); + } + + #[test] + fn release_is_faster_for_a_blip_than_for_sustained_reduction() { + let sr = 48000.0; + let recovery = |hot_ms: usize| { + let mut lim = Limiter::new(sr); + let mut x: Vec = (0..(sr as usize * hot_ms / 1000)).map(|i| 4.0 * (i as f64 * 0.1).sin()).collect(); + let hot = x.len(); + x.extend(vec![0.05; 48000 * 3]); + let mut n = 0; + for (i, v) in x.iter().enumerate() { + lim.tick([*v, *v], true); + if i > hot + 200 && lim.gain() > 0.97 { + n = i - hot; + break; + } + } + n + }; + let (blip, long) = (recovery(3), recovery(1000)); + assert!(blip > 0 && long > 0); + // the clip takes most of a hot signal, so the gain stage's 'time under reduction' (and the release range, 15-80 ms) is modest + assert!(long as f64 > blip as f64 * 1.3, "blip {blip} samples, sustained {long}"); + } + + #[test] + fn toggling_on_fades_in_without_a_step() { + let sr = 48000.0; + let mut lim = Limiter::new(sr); + let x: Vec = (0..48000).map(|i| 2.0 * (2.0 * PI * 200.0 * i as f64 / sr).sin()).collect(); + let mut prev = 0.0; + let mut worst = 0.0f64; + for (i, v) in x.iter().enumerate() { + let y = lim.tick([*v, *v], i >= 12000)[0]; + if i > 12000 { + worst = worst.max((y - prev).abs()); + } + prev = y; + } + // a 200 Hz sine at amplitude 2 moves at most 2 * 2pi * 200 / sr = 0.052 per sample; the fade must not add a jump + assert!(worst < 0.07, "step {worst}"); + } + + #[test] + fn latency_is_constant_per_rate() { + let a = Limiter::new(48000.0).latency(); + assert_eq!(a, 32 + 72); + assert_eq!(Limiter::new(96000.0).latency(), 32 + 144); + assert_eq!(Limiter::new(192000.0).latency(), 288); + } + + #[test] + fn interpolator_reads_inter_sample_peaks() { + // fs/4 sine sampled 45 degrees off the crest: sample peak = 0.707, true peak = 1.0 + let mut lim = Limiter::new(48000.0); + let mut worst = 0.0f64; + for i in 0..200 { + let v = (PI * 0.5 * i as f64 + PI / 4.0).sin(); + let p = lim.detect([v, v]); + if i > 40 { + worst = worst.max(p); + } + } + assert!((worst - 1.0).abs() < 0.01, "detected {worst}"); + } + + #[test] + fn ceiling_release_and_clip_are_settable_and_defaults_are_unchanged() { + let sr = 48000.0; + let x: Vec = (0..48000).map(|i| 3.0 * (2.0 * PI * 1000.0 * i as f64 / sr).sin()).collect(); + let mut a = Limiter::new(sr); + let mut b = Limiter::new(sr); + b.set_ceiling_db(CEILING_DB); + b.set_release_ms(TAU_MAX * 1000.0); + b.set_clip(true); + b.set_lookahead(true); + let (ya, _) = run(&mut a, &x, &x, true); + let (yb, _) = run(&mut b, &x, &x, true); + assert_eq!(ya, yb); + let mut c = Limiter::new(sr); + c.set_ceiling_db(-6.0); + let (yc, _) = run(&mut c, &x, &x, true); + let pk = yc[24000..].iter().fold(0.0f64, |m, v| m.max(v.abs())); + assert!(db(pk) > -6.3 && db(pk) < -5.9, "{} dB", db(pk)); + } + + #[test] + fn lookahead_off_has_no_latency_and_holds_the_sample_ceiling() { + let sr = 48000.0; + let mut lim = Limiter::new(sr); + lim.set_lookahead(false); + lim.snap_on(true); + assert_eq!(lim.latency(), 0); + let (l, r) = stress(sr); + let (yl, yr) = run(&mut lim, &l, &r, true); + let ceil = 10f64.powf(CEILING_DB / 20.0); + for y in [&yl, &yr] { + assert!(y.iter().all(|v| v.abs() <= ceil + 1e-12), "a sample went over the ceiling"); + } + assert!(lim.gmin < 0.5); + // quiet material passes through bit-exactly, with no delay + let mut q = Limiter::new(sr); + q.set_lookahead(false); + q.snap_on(true); + let x: Vec = (0..5000).map(|i| 0.4 * (i as f64 * 0.03).sin()).collect(); + let (y, _) = run(&mut q, &x, &x, true); + assert_eq!(y, x); + } + + #[test] + fn switching_the_lookahead_on_mid_stream_lets_nothing_over_the_ceiling() { + let sr = 48000.0; + let mut lim = Limiter::new(sr); + lim.set_lookahead(false); + lim.snap_on(true); + let ceil = 10f64.powf(CEILING_DB / 20.0); + let mut worst = 0.0f64; + for i in 0..24000 { + if i == 12000 { + lim.set_lookahead(true); + } + let v = 3.0 * (2.0 * PI * 1000.0 * i as f64 / sr).sin(); + let y = lim.tick([v, -v * 0.5], true); + worst = worst.max(y[0].abs()).max(y[1].abs()); + } + assert!(worst <= ceil + 1e-9, "peak {:.2} dB", db(worst)); + assert_eq!(lim.latency(), 104); + } + + #[test] + fn hi_precision_doubles_the_detector_grid_and_reads_closer() { + // a tone whose crest falls between the 4x points: the 8x grid reads it closer to its true peak of 1.0 + let read = |hi: bool| { + let mut lim = Limiter::new(48000.0); + lim.set_hi(hi); + let mut worst = 0.0f64; + for i in 0..400 { + let v = (2.0 * PI * 0.45 * i as f64 + 0.3).sin(); + let p = lim.detect([v, v]); + if i > 80 { + worst = worst.max(p); + } + } + worst + }; + let (lo, hi) = (read(false), read(true)); + assert!(hi >= lo && hi <= 1.0 + 1e-3 && hi > 0.99, "4x {lo} 8x {hi}"); + // the latency only grows where the plain detector has no interpolator (192 kHz-class) + let lat = |sr: f64| { + let mut l = Limiter::new(sr); + l.set_hi(true); + l.latency() + }; + assert_eq!((lat(48000.0), lat(96000.0), lat(192000.0)), (104, 176, 320)); + } + + #[test] + fn internal_clip_off_leaves_a_spike_to_the_gain_stage() { + // without the clip the gain stage has to take the whole spike (it ducks); with it the clip takes it + let sr = 48000.0; + let x: Vec = (0..24000).map(|i| if (12000..12048).contains(&i) { 4.0 * (PI * (i - 12000) as f64 / 48.0).sin() } else { 0.1 }).collect(); + let mut a = Limiter::new(sr); + a.set_clip(false); + run(&mut a, &x, &x, true); + let mut b = Limiter::new(sr); + run(&mut b, &x, &x, true); + assert!(a.gmin < 0.4, "{}", a.gmin); + assert!(b.gmin <= a.gmin + 1e-9 && b.gmin > 0.0); + } +} diff --git a/rust/satcomp-dsp/src/params.rs b/rust/satcomp-dsp/src/params.rs index 027b563..04e8f80 100644 --- a/rust/satcomp-dsp/src/params.rs +++ b/rust/satcomp-dsp/src/params.rs @@ -1,6 +1,8 @@ //! Parameter set, mirroring the JSFX sliders (see docs/PARAMETERS.md). Slider numbers in comments. -use crate::shapers::Curve; +use crate::compressor::CompParams; +use crate::saturator::SatParams; +use crate::shapers::{Curve, SHAPER_COUNT}; #[derive(Clone, Copy, PartialEq, Debug)] pub struct EqBandParams { @@ -31,6 +33,8 @@ pub struct Params { // SAT pub shape: i32, // 1 0..14 (14 = custom curve, Rust only) pub curve: Curve, // user-drawn transfer curve, used when shape == 14 + /// ASYM per shaper, 0..100 %: how much of the shaper's even part is kept (the part that carries DC / sub-audio pulses) + pub asym: [f64; SHAPER_COUNT], pub drive: f64, // 2 0..100 % pub bias: f64, // 3 -100..100 % pub sat_hp: f64, // 4 20..2000 Hz (<=20.5 = off) @@ -69,6 +73,49 @@ pub struct Params { pub sc_hp: f64, // 65 20..2000 Hz (<=20.5 = off) pub sc_lp: f64, // 66 200..20000 Hz (>=19900 = off) pub sc_mix: f64, // 67 0..100 % key mix (0 = main detector only, 100 = key only) + // OUTPUT LIMITER (true-peak brickwall at -0.2 dBTP; the delay is always reported, this only engages the gain) + pub lim_on: bool, // 68 +} + +impl Params { + /// The saturator block's slice of the parameter set. + pub fn sat(&self) -> SatParams { + SatParams { + shape: self.shape, + curve: self.curve, + drive: self.drive, + bias: self.bias, + hp: self.sat_hp, + lp: self.sat_lp, + tone: self.tone, + os: self.os, + mix: self.sat_mix, + out_db: self.sat_out, + asym: Some(self.asym[(self.shape.max(0) as usize).min(SHAPER_COUNT - 1)]), + steep: false, + } + } + + /// The compressor block's slice of the parameter set. + pub fn comp(&self) -> CompParams { + CompParams { + thresh: self.thresh, + ratio: self.ratio, + attack: self.attack, + release: self.release, + speed: self.speed, + knee: self.knee, + knee_shape: self.knee_shape, + detector: self.detector, + det_hp: self.det_hp, + ff_fb: self.ff_fb, + gr_dist: self.gr_dist, + key_mix: self.sc_mix, + up: false, + down: true, + up_range: 12.0, + } + } } impl Default for Params { @@ -76,13 +123,14 @@ impl Default for Params { Self { shape: 0, curve: Curve::linear(), - drive: 25.0, + asym: [100.0; SHAPER_COUNT], + drive: 0.0, bias: 0.0, sat_hp: 20.0, sat_lp: 20000.0, tone: 20000.0, os: 0, - thresh: -18.0, + thresh: 0.0, ratio: 4.0, attack: 10.0, release: 150.0, @@ -110,6 +158,7 @@ impl Default for Params { sc_hp: 20.0, sc_lp: 20000.0, sc_mix: 100.0, + lim_on: false, // the plug-in's own default is on; the engine default stays off so bare-engine renders are untouched } } } diff --git a/rust/satcomp-dsp/src/saturator.rs b/rust/satcomp-dsp/src/saturator.rs new file mode 100644 index 0000000..4d1622a --- /dev/null +++ b/rust/satcomp-dsp/src/saturator.rs @@ -0,0 +1,391 @@ +//! The saturator block: optional HP/LP split (only the middle band is shaped, the rest is added back), drive + bias into a +//! waveshaper LUT (optionally 2x/4x oversampled), DC blocker, tone low-pass, dry/wet mix, then SAT OUT gain. +//! Reports its latency and a smoothed output mean-square level (for the level match). Stereo, f64. + +use crate::biquad::{self, bq, Coef}; +use crate::delay::StereoDelay; +use crate::halfband::{Oversampler, Taps}; +use crate::level::{ms_step, one_pole, LN10_20}; +use crate::shapers::{Curve, ShaperLut}; +use crate::DENORM; +use std::f64::consts::PI; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct SatParams { + pub shape: i32, + /// user curve, used when `shape` is the custom shaper + pub curve: Curve, + /// 0..100 % + pub drive: f64, + /// -100..100 % + pub bias: f64, + /// 20..2000 Hz (<= 20.5 = off) + pub hp: f64, + /// 200..20000 Hz (>= 19900 = off) + pub lp: f64, + /// 1000..20000 Hz (>= 19900 = off) + pub tone: f64, + /// 0 off, 1 x2, 2 x4 (3 = x8, SatLim only) + pub os: i32, + /// 0..100 % + pub mix: f64, + /// dB + pub out_db: f64, + /// Even / odd split of the shaper: `None` = the plain shaper (legacy). `Some(a)`, a in 0..100 %: output = odd part + + /// a * (even part high-passed at `EVEN_HP_HZ`). The even part of an asymmetric curve is what carries DC and + /// envelope-following sub-audio pulses (they sink the waveform into the headroom); 0 % drops it altogether. + pub asym: Option, + /// HP / LP as 48 dB/oct Butterworth (8th order, flat passband, no corner peak) instead of the legacy 12 dB biquad. + pub steep: bool, +} + +/// Section Qs of an 8th-order Butterworth (48 dB/oct): maximally flat, the high-Q sections cancel each other's peaks. +const BUTTER8_Q: [f64; 4] = [0.509_795_579_104_159_3, 0.601_344_886_935_045_2, 0.899_976_223_136_415_6, 2.562_915_447_741_505]; + +/// Corner of the high-pass on the even part of the shaper (2nd order), Hz. +pub const EVEN_HP_HZ: f64 = 25.0; + +impl Default for SatParams { + fn default() -> Self { + Self { shape: 0, curve: Curve::linear(), drive: 25.0, bias: 0.0, hp: 20.0, lp: 20000.0, tone: 20000.0, os: 0, mix: 100.0, out_db: 0.0, asym: None, steep: false } + } +} + +pub struct Saturator { + lut: ShaperLut, + lut_cnt: u32, + taps: Taps, + ov: [Oversampler; 2], + /// down-filter state of the even part (see `Oversampler::process_fe`) + ove: [Oversampler; 2], + asym_k: Option, + evc: Coef, + evs: [[f64; 2]; 2], + pre: f64, + pre_t: f64, + bias: f64, + bias_t: f64, + on: bool, + use_hp: bool, + use_lp: bool, + use_tone: bool, + hpc: [Coef; 4], + lpc: [Coef; 4], + /// sections used by the HP / LP: 1 (12 dB) or 4 (48 dB) + n_filt: usize, + tnc: Coef, + hps: [[[f64; 2]; 4]; 2], + lps: [[[f64; 2]; 4]; 2], + tns: [[f64; 2]; 2], + os: i32, + last_os: i32, + lat: usize, + dc_r: f64, + dcx: [f64; 2], + dcy: [f64; 2], + /// True until the first saturated sample: a fresh engine (REAPER rebuilds it on every FX enable) must start the + /// oversampler and DC blocker in their settled state, else the saturator's constant output (bias) leaks as a step. + dc_warm: bool, + dry: StereoDelay<64>, + res: StereoDelay<64>, + band: StereoDelay<64>, + mix: f64, + mix_t: f64, + gain: f64, + gain_t: f64, + out_db: f64, + sm_c: f64, + gain_c: f64, + ms_c: f64, + /// Smoothed mean-square level of the stage output before SAT OUT (reference for the sat level-match). + pub ms: f64, + /// Peak of the shaped band since the owner last cleared it (UI meter). + pub blk: f64, +} + +impl Default for Saturator { + fn default() -> Self { + Self::new() + } +} + +impl Saturator { + pub fn new() -> Self { + Self { + lut: ShaperLut::new(0), + lut_cnt: 0, + taps: Taps::new(), + ov: [Oversampler::default(), Oversampler::default()], + ove: [Oversampler::default(), Oversampler::default()], + asym_k: None, + evc: biquad::IDENTITY, + evs: [[0.0; 2]; 2], + pre: 1.0, + pre_t: 1.0, + bias: 0.0, + bias_t: 0.0, + on: false, + use_hp: false, + use_lp: false, + use_tone: false, + hpc: [biquad::IDENTITY; 4], + lpc: [biquad::IDENTITY; 4], + n_filt: 1, + tnc: biquad::IDENTITY, + hps: [[[0.0; 2]; 4]; 2], + lps: [[[0.0; 2]; 4]; 2], + tns: [[0.0; 2]; 2], + os: 0, + last_os: -1, + lat: 0, + dc_r: 1.0, + dcx: [0.0; 2], + dcy: [0.0; 2], + dc_warm: true, + dry: StereoDelay::new(), + res: StereoDelay::new(), + band: StereoDelay::new(), + mix: 1.0, + mix_t: 1.0, + gain: 1.0, + gain_t: 1.0, + out_db: 0.0, + sm_c: 0.0, + gain_c: 0.0, + ms_c: 0.0, + ms: 1e-9, + blk: 0.0, + } + } + + /// PDC latency of the oversampler, samples. + pub fn latency(&self) -> usize { + self.lat + } + + /// Effective SAT OUT in dB (the parameter, or a finished level match). + pub fn out_db(&self) -> f64 { + self.out_db + } + + pub fn set_out_db(&mut self, db: f64) { + self.out_db = db; + } + + /// `snap` jumps the smoothed drive / bias / mix / out gain to their targets. `smoothing` false also commits the shaper + /// table at once (no morph) and disables the per-sample glide. + pub fn derive(&mut self, p: &SatParams, sr: f64, snap: bool, smoothing: bool) { + self.lut.fade = smoothing; + self.lut.sync(p.shape, &p.curve); + self.pre_t = (p.drive * 0.01 * 36.0 * LN10_20).exp(); + self.bias_t = p.bias * 0.01; + self.on = p.drive > 0.0 || p.bias != 0.0; + self.use_hp = p.hp > 20.5; + self.n_filt = if p.steep { 4 } else { 1 }; + if self.use_hp { + for k in 0..self.n_filt { + self.hpc[k] = biquad::hp(p.hp, if p.steep { BUTTER8_Q[k] } else { 0.70710678 }, sr); + } + } + self.use_lp = p.lp < 19900.0; + if self.use_lp { + for k in 0..self.n_filt { + self.lpc[k] = biquad::lp(p.lp, if p.steep { BUTTER8_Q[k] } else { 0.70710678 }, sr); + } + } + self.use_tone = p.tone < 19900.0; + if self.use_tone { + self.tnc = biquad::lp(p.tone, 0.70710678, sr); + } + self.asym_k = p.asym.map(|a| (a * 0.01).clamp(0.0, 1.0)); + if self.asym_k.is_some() { + self.evc = biquad::hp(EVEN_HP_HZ, 0.70710678, sr); + } + self.os = (p.os as f64 + 0.5).floor() as i32; + if self.os != self.last_os { + self.last_os = self.os; + self.ov[0].clear(); + self.ov[1].clear(); + self.ove[0].clear(); + self.ove[1].clear(); + self.res.clear(); + } + self.lat = crate::halfband::latency(self.os); + self.dc_r = 1.0 - 2.0 * PI * 5.0 / sr; + self.mix_t = p.mix * 0.01; + self.gain_c = one_pole(sr, 0.02); + self.sm_c = one_pole(sr, 0.02); + self.ms_c = one_pole(sr, 0.5); + if snap { + self.pre = self.pre_t; + self.bias = self.bias_t; + self.mix = self.mix_t; + self.out_db = p.out_db; + self.gain = (self.out_db * LN10_20).exp(); + self.gain_t = self.gain; + } + } + + /// Per host block. + pub fn begin_block(&mut self) { + self.gain_t = (self.out_db * LN10_20).exp(); + } + + /// One stereo sample in -> shaped stereo sample out (after SAT OUT), delayed by `latency()`. + #[inline] + pub fn tick(&mut self, inp: [f64; 2], smoothing: bool) -> [f64; 2] { + let (cc, _) = self.tick_split(inp, smoothing); + let g = self.gain_step(); + [cc[0] * g, cc[1] * g] + } + + /// The SAT OUT gain for this sample (smoothed). `tick` = `tick_split` then this. + #[inline] + pub fn gain_step(&mut self) -> f64 { + self.gain += (self.gain_t - self.gain) * self.gain_c; + self.gain + } + + /// As `tick`, but before SAT OUT and also returning the clean (unsaturated) input delayed by `latency()`: + /// `(shaped, clean)`. Their difference is the content the saturator added (the owner may filter it). + #[inline] + pub fn tick_split(&mut self, inp: [f64; 2], smoothing: bool) -> ([f64; 2], [f64; 2]) { + self.lut_cnt += 1; + if self.lut_cnt >= crate::shapers::FADE_EVERY { + self.lut_cnt = 0; + self.lut.step(); + } + if smoothing { + let c = self.sm_c; + self.pre += (self.pre_t - self.pre) * c; + self.bias += (self.bias_t - self.bias) * c; + self.mix += (self.mix_t - self.mix) * c; + } else { + self.pre = self.pre_t; + self.bias = self.bias_t; + self.mix = self.mix_t; + } + + self.dry.advance(); + self.res.advance(); + self.band.advance(); + self.dry.put(inp); + let dl = self.dry.tap(self.lat); + + let mut cc = [0.0f64; 2]; + if self.on { + let mut bp = inp; + if self.use_hp { + for c in 0..2 { + for k in 0..self.n_filt { + bp[c] = bq(&mut self.hps[c][k], &self.hpc[k], bp[c]); + } + } + } + if self.use_lp { + for c in 0..2 { + for k in 0..self.n_filt { + bp[c] = bq(&mut self.lps[c][k], &self.lpc[k], bp[c]); + } + } + } + self.res.put([inp[0] - bp[0], inp[1] - bp[1]]); + self.band.put(bp); + self.blk = self.blk.max(bp[0].abs().max(bp[1].abs())); + let rd_band = self.band.tap(self.lat); + let rd_res = self.res.tap(self.lat); + for c in 0..2 { + let xin = bp[c] * self.pre + self.bias; + let sh = if let Some(k) = self.asym_k { + if self.dc_warm { + for _ in 0..256 { + self.ov[c].process_fe(&self.taps, &self.lut, self.os, xin, &mut self.ove[c]); + } + } + let (f, e) = self.ov[c].process_fe(&self.taps, &self.lut, self.os, xin, &mut self.ove[c]); + if self.dc_warm { + // settle the even-part high-pass on its constant input (output 0) + for _ in 0..16384 { + bq(&mut self.evs[c], &self.evc, e); + } + } + f - e + k * bq(&mut self.evs[c], &self.evc, e) + } else { + if self.dc_warm { + for _ in 0..256 { + self.ov[c].process(&self.taps, &self.lut, self.os, xin); + } + } + self.ov[c].process(&self.taps, &self.lut, self.os, xin) + }; + if self.dc_warm { + self.dcx[c] = sh; + self.dcy[c] = 0.0; + } + let mut y = sh - self.dcx[c] + self.dc_r * self.dcy[c] + DENORM; + self.dcx[c] = sh; + self.dcy[c] = y; + if self.use_tone { + y = bq(&mut self.tns[c], &self.tnc, y); + } + if self.mix < 0.999 { + y = rd_band[c] + (y - rd_band[c]) * self.mix; + } + cc[c] = rd_res[c] + y; + } + self.dc_warm = false; + } else { + self.res.put([0.0, 0.0]); + cc = dl; + } + + ms_step(&mut self.ms, cc[0], cc[1], self.ms_c); + (cc, dl) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::shapers::CUSTOM; + + /// Kick-like loop through the user's zig-zag custom curve: (min of the 20 Hz low-passed output, peak) per ASYM setting. + fn run(asym: Option, os: i32) -> (f64, f64, f64) { + let sr = 48000.0; + let curve = Curve::from_points(&[(-1.0, -1.0), (-0.6, -0.2), (-0.35, -0.8), (0.0, 0.1), (0.3, 0.7), (0.5, 0.1), (0.8, 0.8), (1.0, 0.9)]); + let p = SatParams { shape: CUSTOM, curve, drive: 16.0, bias: 0.0, os, mix: 100.0, asym, ..SatParams::default() }; + let mut s = Saturator::new(); + s.derive(&p, sr, true, false); + let lp = biquad::lp(6.0, 0.70710678, sr); + let (mut st, mut lo, mut hi, mut pk) = ([0.0; 2], 0.0f64, 0.0f64, 0.0f64); + let n = (sr * 2.0) as usize; + for i in 0..n { + let t = (i as f64 / sr) % 0.345; + let f = 55.0 + 90.0 * (-t / 0.02).exp(); + let ph = 2.0 * PI * (55.0 * t + 90.0 * 0.02 * (1.0 - (-t / 0.02).exp())); + let _ = f; + let x = 0.9 * (-t / 0.08).exp() * ph.sin() + 0.1 * (2.0 * PI * 3000.0 * i as f64 / sr).sin() * (-t / 0.1).exp(); + let y = if asym == Some(-1.0) { x } else { s.tick([x, x], false)[0] }; + let l = bq(&mut st, &lp, y); + if i > n / 2 { + lo = lo.min(l); + hi = hi.max(l); + pk = pk.max(y.abs()); + } + } + (lo, hi, pk) + } + + #[test] + fn asym_tames_sub_audio_offset_of_a_lopsided_curve() { + for os in [0, 2] { + let legacy = run(None, os); + let full = run(Some(100.0), os); + let none = run(Some(0.0), os); + eprintln!("input only {:?}", run(Some(-1.0), os)); + eprintln!("os {os}: legacy {legacy:?} asym100 {full:?} asym0 {none:?}"); + let swing = |r: (f64, f64, f64)| r.1 - r.0; + assert!(swing(full) < 0.5 * swing(legacy), "asym 100 low-passed swing {full:?} vs legacy {legacy:?}"); + } + } +} diff --git a/rust/satcomp-dsp/src/shapers.rs b/rust/satcomp-dsp/src/shapers.rs index dd12890..b9e8887 100644 --- a/rust/satcomp-dsp/src/shapers.rs +++ b/rust/satcomp-dsp/src/shapers.rs @@ -5,6 +5,20 @@ pub const SHAPER_NAMES: [&str; 15] = [ "Tube", "Soft", "Rational", "Atan", "Hard", "Tri Fold", "Sine Fold", "Crossover", "Cheby", "Wrap", "Rectify", "Bitcrush", "Asym Fold", "Diode", "Custom", ]; +/// Number of waveshapers (14 built-in + custom). +pub const SHAPER_COUNT: usize = SHAPER_NAMES.len(); + +/// Persisted per-shaper ASYM values (0..100 %) -> the DSP array (missing / non-finite entries = 100 %, clamped). +pub fn asym_from(v: &[f32]) -> [f64; SHAPER_COUNT] { + let mut a = [100.0; SHAPER_COUNT]; + for (d, s) in a.iter_mut().zip(v) { + if s.is_finite() { + *d = (*s as f64).clamp(0.0, 100.0); + } + } + a +} + /// Shaper index of the user-drawn curve. pub const CUSTOM: i32 = 14; @@ -77,6 +91,37 @@ impl Curve { c } + /// True when the curve is (nearly) odd, `f(-x) = -f(x)`: the symmetry tool can edit it without changing it. + pub fn is_odd(&self) -> bool { + (0..=20).all(|i| { + let x = i as f64 * 0.05; + (self.eval(x) + self.eval(-x)).abs() < 0.02 + }) + } + + /// The right half of the curve's odd part: points at the |x| of its interior points (at most `MAX_PTS / 2 - 1`) and at + /// x = 1, with y = (f(x) - f(-x)) / 2. Feed it to `from_odd_half`. + pub fn odd_half(&self) -> Vec<(f32, f32)> { + let mut xs: Vec = self.pts().iter().filter(|p| p.0 > -1.0 && p.0 < 1.0).map(|p| p.0.abs()).filter(|x| *x >= MIN_GAP).collect(); + xs.sort_by(|a, b| a.total_cmp(b)); + let mut keep: Vec = Vec::new(); + for x in xs { + if keep.last().map_or(true, |l| x - l >= MIN_GAP) && x <= 1.0 - MIN_GAP { + keep.push(x); + } + } + keep.truncate(MAX_PTS / 2 - 1); + keep.push(1.0); + keep.into_iter().map(|x| (x, ((self.eval(x as f64) - self.eval(-x as f64)) * 0.5) as f32)).collect() + } + + /// The full odd curve of a right half (x > 0, ending at x = 1): the left half is the point-mirror image. + pub fn from_odd_half(h: &[(f32, f32)]) -> Self { + let mut v: Vec<(f32, f32)> = h.iter().rev().map(|&(x, y)| (-x, -y)).collect(); + v.extend_from_slice(h); + Self::from_points(&v) + } + /// Value of the monotone cubic (Fritsch-Carlson) through the points; flat beyond the ends. /// Never overshoots between points, so the transfer curve stays single-valued and tame. pub fn eval(&self, x: f64) -> f64 { @@ -379,4 +424,16 @@ mod tests { let soft = ShaperLut::new(1); assert!((soft.eval(50.0) - shaper(1, 7.999)).abs() < 1e-3); // clamped, not folded } + + #[test] + fn odd_half_round_trips_and_folds_a_lopsided_curve() { + let lop = Curve::from_points(&[(-1.0, -0.6), (-0.4, -0.1), (0.5, 0.8), (1.0, 1.0)]); + assert!(!lop.is_odd()); + let odd = Curve::from_odd_half(&lop.odd_half()); + assert!(odd.is_odd(), "{:?}", odd.pts()); + // the odd part is what the fold keeps: f(1) = (1.0 + 0.6) / 2 + assert!((odd.eval(1.0) - 0.8).abs() < 1e-6 && (odd.eval(-1.0) + 0.8).abs() < 1e-6); + assert!(Curve::linear().is_odd()); + assert_eq!(Curve::from_odd_half(&Curve::linear().odd_half()).pts(), Curve::linear().pts()); + } } diff --git a/rust/satcomp-dsp/tests/golden.rs b/rust/satcomp-dsp/tests/golden.rs new file mode 100644 index 0000000..56e9ed5 --- /dev/null +++ b/rust/satcomp-dsp/tests/golden.rs @@ -0,0 +1,42 @@ +//! Regression net for the engine: every scenario in `golden/scen.rs` must reproduce the committed fixture. +//! Bit-exact where the platform's maths library matches the recording machine; otherwise the RMS and peak must agree to +//! 1e-9 relative (a different libm can move the last bits of exp/ln/sin). Re-record deliberately with +//! `cargo run --release -p satcomp-dsp --example golden -- record` when the sound is *meant* to change. + +#[path = "golden/scen.rs"] +mod scen; + +#[test] +fn engine_matches_golden_fixture() { + let fixture = include_str!("golden/golden.txt"); + let mut checked = 0; + let mut loose = Vec::new(); + for sc in scen::scenarios() { + let line = fixture + .lines() + .find(|l| l.split(' ').next() == Some(sc.name.as_str())) + .unwrap_or_else(|| panic!("scenario {} missing from golden.txt (re-record)", sc.name)); + let f: Vec<&str> = line.split(' ').collect(); + let (ha, ht, rms, pk) = scen::summarize(&scen::render(&sc)); + let (fa, ft) = (u64::from_str_radix(f[1], 16).unwrap(), u64::from_str_radix(f[2], 16).unwrap()); + let (frms, fpk): (f64, f64) = (f[3].parse().unwrap(), f[4].parse().unwrap()); + if ha != fa || ht != ft { + let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.abs().max(1e-12); + assert!(close(rms, frms) && close(pk, fpk), "{}: output changed (rms {rms:e} vs {frms:e}, peak {pk:e} vs {fpk:e})", sc.name); + loose.push(sc.name.clone()); + } + checked += 1; + } + assert!(checked >= 100, "expected the full scenario list, ran {checked}"); + if !loose.is_empty() { + eprintln!("note: {} scenarios matched to 1e-9 but not bit-exactly on this platform", loose.len()); + } +} + +#[test] +fn render_is_deterministic() { + let sc = &scen::scenarios()[1]; + let a = scen::summarize(&scen::render(sc)); + let b = scen::summarize(&scen::render(sc)); + assert_eq!((a.0, a.1), (b.0, b.1)); +} diff --git a/rust/satcomp-dsp/tests/golden/golden.txt b/rust/satcomp-dsp/tests/golden/golden.txt new file mode 100644 index 0000000..703a5be --- /dev/null +++ b/rust/satcomp-dsp/tests/golden/golden.txt @@ -0,0 +1,102 @@ +# name audio-hash telemetry-hash rms peak (cargo run --release -p satcomp-dsp --example golden -- record) +default 6aeb3ec9d1e92aa9 ee4696044342bd71 1.255891786604e-1 9.986183047295e-1 +base 1e58d980cc06fd5e e0d079136fab6e84 1.171079373163e-1 1.145338654518e0 +shaper0_os0 1e58d980cc06fd5e e0d079136fab6e84 1.171079373163e-1 1.145338654518e0 +shaper0_os1 a0f599cd04a0fd28 b1a49300d9b821da 1.166269427542e-1 1.160877943039e0 +shaper0_os2 17546a58df22b5bf e617bcc649b8a333 1.166285906841e-1 1.160601258278e0 +shaper1_os0 6a5b9f8f0b08a441 07aadbac3b7f8a2e 1.119259701222e-1 1.068216562271e0 +shaper1_os1 0f21e379bf20fca1 43502688dac995f5 1.110791997538e-1 1.079494595528e0 +shaper1_os2 14c07670d112dc23 9a3c16151a45f4f1 1.110862687573e-1 1.079584002495e0 +shaper2_os0 5229995a7ac07ae6 0976c8e9c2ff9338 9.228459934909e-2 6.409381628036e-1 +shaper2_os1 d450ebbfc49bbb6d d1f100642d09aead 9.145250190794e-2 6.425662040710e-1 +shaper2_os2 e1d502dd754f480f 1301d8c65aad67c4 9.148101760274e-2 6.425537467003e-1 +shaper3_os0 338a6f187e47cee8 14ab60dcd7f33a22 1.067324766731e-1 9.501905441284e-1 +shaper3_os1 813291eb5a8710d2 84bacf448a0374aa 1.058834832806e-1 9.524192810059e-1 +shaper3_os2 86bd6dcf561eea73 31cc1e747e32ebcc 1.058992613118e-1 9.524003863335e-1 +shaper4_os0 d9f947ed4c763be6 bfbf0c08815d59a3 1.155153519507e-1 1.091685891151e0 +shaper4_os1 32557864e96d8b02 e3ab16759f357b03 1.143858003192e-1 1.128047347069e0 +shaper4_os2 802a3580ba58fabe 082022e14dfcfb68 1.143766067312e-1 1.130104064941e0 +shaper5_os0 7b466647423f7abd 981a2b5d4c01ca9c 9.857360372452e-2 1.063256382942e0 +shaper5_os1 cfd977092e12b99a bd59923ee2142534 9.698474793434e-2 1.045004963875e0 +shaper5_os2 1163145d5b097c3d ac1212e117d2e6f0 9.693882917707e-2 1.051306366920e0 +shaper6_os0 959e603a02e6aa54 86d412add25d96c1 9.355188963655e-2 7.296273112297e-1 +shaper6_os1 2ceeef4b2e7dbb0a 0b2ecd73134d5869 9.103874077485e-2 8.414021730423e-1 +shaper6_os2 96d4cab343c4c006 86e89311823b5004 9.105186225199e-2 8.391151428223e-1 +shaper7_os0 a8b0858ce48abfbf dcbcf67f4e077b1f 2.020552107596e-1 6.156131267548e0 +shaper7_os1 7f2fb9452f577fac 75eebdef7a23ff19 2.017935818233e-1 6.165238380432e0 +shaper7_os2 e3b39ea5ed3a818b bcc1faa1f32bd9ca 2.017833569901e-1 6.164651870728e0 +shaper8_os0 743258849ec0e1ce 672f15c05fce67ce 1.390199204181e-1 2.371922492981e0 +shaper8_os1 d5f45ddee9910567 91c1dcc592ebea6f 1.385754819018e-1 2.409894227982e0 +shaper8_os2 4518f88da4dfd814 a93fd317e7ebebf1 1.385683147163e-1 2.410303831100e0 +shaper9_os0 9bc96c0fa7fc3765 4d924d1e46b1e5fb 9.857907456549e-2 1.020616650581e0 +shaper9_os1 233552e0b8c22412 3ea3017e137dfbd5 8.883024995407e-2 1.098868250847e0 +shaper9_os2 1f6563b220fb0d1b b0ac2da607963733 8.637582913005e-2 1.117571711540e0 +shaper10_os0 6e18f88c44419bb7 6e2db49237c9cfc5 8.272089720217e-2 9.126034379005e-1 +shaper10_os1 692a5f58cf5d5445 61e4dd502511bfa3 8.136198575958e-2 9.274603128433e-1 +shaper10_os2 e61e6b2ac7f961a8 fdbfa0ef67909e4d 8.135974366853e-2 9.281194210052e-1 +shaper11_os0 40610eb87b861182 fd383d3746b3de7a 1.160007708969e-1 1.116426110268e0 +shaper11_os1 dc69383ff5422cfa 6943f18c87c3a908 1.147695124778e-1 1.153355836868e0 +shaper11_os2 af1ef2ceffd6bbd0 83b5a400408d5ed1 1.147336508932e-1 1.158767342567e0 +shaper12_os0 66fbe1e6b6c825d0 af66514418cb7012 9.755888775901e-2 1.161674141884e0 +shaper12_os1 805b1f94406477e0 02879681eacb2ec9 9.487580835205e-2 1.193065404892e0 +shaper12_os2 ee432d1afc77c354 889ef904cac18cc3 9.488419210569e-2 1.192290902138e0 +shaper13_os0 f1c1bd1f626e3fd5 384a993a63547058 1.029123309029e-1 1.000185251236e0 +shaper13_os1 e6b2f15a43a1e036 452dbb66ae09d14b 1.021453835747e-1 1.000948429108e0 +shaper13_os2 5217ebc078d54356 b406ab0f019ffbe7 1.021611548950e-1 1.000940084457e0 +shaper14_os0 e98d63e04a8ddf17 539c441769ed7a5b 1.153262019957e-1 1.304023265839e0 +shaper14_os1 7a19a584d0c856fd f7c1485b578c6709 1.134377685510e-1 1.516716480255e0 +shaper14_os2 02bed3dc4420aa3b 8624616472fa326b 1.135006536148e-1 1.528183698654e0 +sat_filters 58be4166371a966f 1a1944268d2e4511 9.988425740102e-2 1.263525128365e0 +sat_mix_out_os2 87f89928903b9865 0f5ca378ec7250cc 8.190342228190e-2 5.609739422798e-1 +sat_off 319618532b26ad9e e402a8b882aa1d48 7.034772897872e-2 7.379158735275e-1 +bias_only 13dbbbd115287db5 ca1f079ae487f58e 6.681832188583e-2 6.144409179688e-1 +comp_ratio_inf 202dddbbb70bc4fe 9a0df3f80b51a8c0 7.136897568334e-2 1.065849781036e0 +comp_ratio_2 058102de29f4edf5 8e4c323cf6c89180 2.108864066191e-1 1.298601150513e0 +comp_release_auto 9d7293fbdf1d2ead 54d73f2d366bd4d7 1.123707381873e-1 1.145338654518e0 +comp_release_fast_attack_fast 2f61df0066dfbae7 856e74f998ef28ea 9.888284299259e-2 9.132338762283e-1 +comp_knee_hard cebb46a0261b3aab 06662fba76ad134c 1.171174103532e-1 1.145338654518e0 +comp_knee_wide_shape 2f080aaba91b9523 e1ac2fe358ba358b 1.170760003651e-1 1.145331263542e0 +comp_speed_fast 6323b04ccbb1211d 1cfe26f05854b8ad 1.411101036152e-1 1.458116292953e0 +comp_speed_slow 4280dcac6cead799 166c354c5f144155 1.088848614499e-1 1.041705489159e0 +comp_detector_peak 5a9b7013c49f65cf 87593b24a1ef31cb 1.222252182123e-1 1.116731762886e0 +comp_detector_rms 7c4475b101ebaa8f 95f2e564c4db5027 1.094478834356e-1 1.269704699516e0 +comp_det_hp 7fda371e50687f1d 917da5e5be3b7d90 1.297859920168e-1 1.376447200775e0 +comp_ff_fb_half 27488f45f2f53c0b 9f265ccc2aeafd8a 1.644637471366e-1 1.168160200119e0 +comp_ff_fb_full 95caf842dd8819ce cf1407da35b90959 2.472768823118e-1 1.183071613312e0 +comp_gr_dist 58e6dfb767e9d3b2 25c1d207ce385983 1.120063250149e-1 1.077096819878e0 +comp_lookahead af7d3d62956c6ff7 5cdde976e8cc2bc0 1.072916850572e-1 6.074009537697e-1 +comp_lookahead_os4 3e5b03be71f95d7c 9d34b99eb918efe6 1.091975862190e-1 7.634724974632e-1 +comp_makeup_mix 91845facea5d321a d4792313230a756b 1.733279709150e-1 1.282019495964e0 +comp_out_gain cdb526d27c359edb e4f3f912fac65280 7.331245528138e-2 1.074545145035e0 +comp_comp_extreme da22b0af00d76391 7cea3719bcb356e2 2.412313278116e-3 2.796314656734e-1 +eq_all_bands 7471f66e94a30a7d d2104d950a3ce199 1.185797215874e-1 1.768406271935e0 +eq_tilt_gain f8c4ad4b3d35afc0 a035930d306e36a1 1.505115305058e-1 1.391764521599e0 +eq_types0 6766529fa930e618 fdbe03cb2a57951d 2.150379287789e-1 2.564634561539e0 +eq_types1 1f4c91711f68ee76 f3419272f898e8b1 1.231318575620e-1 2.469392061234e0 +eq_types2 2391347a9d340a31 fd0efdff7ca71116 2.970423807526e-2 2.313274443150e-1 +eq_pre_bypass d1670cf5d6625f82 0fcb753ce9d7c6d3 1.411704233073e-1 1.709550142288e0 +eq_post_bypass c82c7b0b2331156f cec68f006d7f78a9 1.202425171624e-1 1.215193629265e0 +eq_module_bypass 1e58d980cc06fd5e 59b588c8bc49b79c 1.171079373163e-1 1.145338654518e0 +eq_tap_pre 90889a8f1dfbbcca 5cd2b4df19cf2f71 2.540569718687e-1 3.572150468826e0 +eq_tap_post 6f540cb566da377d 0269d4d26927059a 1.886900573714e-1 2.114521026611e0 +sc_key_only 89468da6c93c11fa c18c432356dfd88a 3.671061152896e-1 1.314647793770e0 +sc_key_half e6d121238409ca9c ac4b2f5cafb581c9 1.603761248798e-1 1.199905753136e0 +sc_key_zero 1e58d980cc06fd5e e0d079136fab6e84 1.171079373163e-1 1.145338654518e0 +sc_key_filtered 845ee13645155b5f 8c9788badc42e532 6.284209340616e-1 1.607291936874e0 +sc_solo de71c3fe73e5f3b8 891d6aede5b42ecd 1.863344561568e-1 9.049944877625e-1 +sc_on_no_bus 1e58d980cc06fd5e e0d079136fab6e84 1.171079373163e-1 1.145338654518e0 +sc_os4_lookahead e82ed7bda768570a e2461fb9d0d48c54 3.626320054524e-1 1.189119100571e0 +bypass c80298c5ace862fc fe50700eeeb6f111 1.719574254795e-1 9.261925220490e-1 +delta 3b91f4236ca5892c ed8107b7ab28f7eb 6.600975068152e-1 1.394904136658e0 +gain_match 5a6ff5b9e3c19d3f 272840c3d92e874d 1.148729540199e-1 1.145338654518e0 +sat_match 3f3f7182b6a9ec0d 77d25866cd625cb8 1.044851923252e-1 1.145338654518e0 +match_request_midrun 1341d9e803ef7efc e5fc988fa1774de1 1.049032857030e-1 1.145338654518e0 +no_smoothing_automation 71654210a3d9c836 7a5aacb68abc3c29 1.629749046898e-1 1.140715241432e0 +sr0 5c8dcda93a5eae4d adbfaf98c6f61b82 1.109836658214e-1 8.447418808937e-1 +sr1 442c860bc9712893 78d91757fdbc3088 1.110130239760e-1 8.372079133987e-1 +sr2 77c257ec50c7b05e 1a7e93a4eda668f9 1.109310253364e-1 8.439946770668e-1 +blocks_ragged d6acf00fa3f89beb 488aede22988ca0b 1.105454515351e-1 7.983468770981e-1 +tick_api 2c8eb210ecf8ed04 b3dd33d49dca301a 1.347222256262e-1 1.145338654518e0 +automation 44fce2cb3a895d5e d20b7d628b31d482 1.630173887332e-1 1.202045798302e0 +automation_os4_sc 512cb03fd0d50291 0e7b71b138ba22f4 3.752552511601e-1 1.465106010437e0 +kitchen_sink db31e3f3a1275016 29094ae61efe5c0e 4.756489414572e-1 1.994436383247e0 diff --git a/rust/satcomp-dsp/tests/golden/scen.rs b/rust/satcomp-dsp/tests/golden/scen.rs new file mode 100644 index 0000000..2ec4641 --- /dev/null +++ b/rust/satcomp-dsp/tests/golden/scen.rs @@ -0,0 +1,516 @@ +//! Golden-render scenarios for the 0.5.2 refactor safety net. +//! +//! Only the public `Engine` / `Params` API is used, so this exact file compiles against v0.5.1 (the baseline) and against +//! the refactored tree. `examples/golden.rs` renders every scenario to disk (`render`) and diffs two render folders +//! (`diff`); `tests/golden.rs` checks the current build against the committed `tests/golden/golden.txt` fixture. + +use satcomp_dsp::eq::decode_band; +use satcomp_dsp::shapers::Curve; +use satcomp_dsp::{Engine, Params}; + +pub struct Scn { + pub name: String, + pub sr: f64, + pub secs: f64, + /// 0 = fixed 256, 1 = ragged mix of block sizes, 2 = one sample at a time through `tick` + pub blocks: u8, + pub p: Params, + /// change parameters between blocks (automation) using `vary` + pub vary: bool, + pub smoothing: bool, + pub key: bool, + pub solo: bool, + pub delta: bool, + /// EQ page tap on: 0 = pre, 1 = post + pub tap: Option, + pub match_req: bool, + pub sat_req: bool, +} + +impl Scn { + fn new(name: String, p: Params) -> Self { + Self { + name, + sr: 48000.0, + secs: 1.5, + blocks: 0, + p, + vary: false, + smoothing: true, + key: false, + solo: false, + delta: false, + tap: None, + match_req: false, + sat_req: false, + } + } +} + +fn lcg(s: &mut u64) -> f64 { + *s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((*s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0 +} + +/// Deterministic programme: noise bed + decaying 220 Hz hits every 0.5 s + a 3 kHz tone, with a quiet stretch in the +/// last quarter (exercises release, the level gate and auto-release). +pub fn input(n: usize, sr: f64, seed: u64) -> (Vec, Vec) { + let mut s = seed; + let (mut l, mut r) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for i in 0..n { + let t = i as f64 / sr; + let hit = (-(t % 0.5) * 9.0).exp(); + let quiet = if (i as f64) > n as f64 * 0.75 { 0.05 } else { 1.0 }; + let body = (t * 220.0 * 6.283185307).sin() * 0.7 * hit + (t * 3000.0 * 6.283185307).sin() * 0.08; + l.push(((body + lcg(&mut s) * 0.12) * quiet) as f32); + r.push(((body * 0.8 + (t * 1700.0 * 6.283185307).sin() * 0.1 + lcg(&mut s) * 0.12) * quiet) as f32); + } + (l, r) +} + +/// Sidechain key: a different rhythm (pulses every 0.3 s). +fn key(n: usize, sr: f64) -> (Vec, Vec) { + let mut s = 99u64; + let (mut l, mut r) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for i in 0..n { + let t = i as f64 / sr; + let env = (-(t % 0.3) * 14.0).exp(); + let v = (t * 90.0 * 6.283185307).sin() * 0.8 * env + lcg(&mut s) * 0.05; + l.push(v as f32); + r.push((v * 0.9) as f32); + } + (l, r) +} + +fn custom_curve() -> Curve { + Curve::from_points(&[(-1.0, -1.0), (-0.45, -0.6), (-0.1, 0.1), (0.3, 0.95), (1.0, 0.7)]) +} + +fn base() -> Params { + let mut p = Params::default(); + p.drive = 55.0; + p.bias = 8.0; + p.thresh = -22.0; + p.ratio = 4.0; + p +} + +pub fn scenarios() -> Vec { + let mut v: Vec = Vec::new(); + + // the v0.5.1 defaults, pinned (INIT now starts with drive 0 / threshold 0) + let mut p = Params::default(); + p.drive = 25.0; + p.thresh = -18.0; + v.push(Scn::new("default".into(), p)); + v.push(Scn::new("base".into(), base())); + + // every shaper x every oversampling mode + for sh in 0..15 { + for os in 0..3 { + let mut p = base(); + p.shape = sh; + p.os = os; + if sh == 14 { + p.curve = custom_curve(); + } + v.push(Scn::new(format!("shaper{sh}_os{os}"), p)); + } + } + + // saturator filters, mixes, outs + let mut p = base(); + p.sat_hp = 300.0; + p.sat_lp = 4000.0; + p.tone = 2500.0; + v.push(Scn::new("sat_filters".into(), p)); + let mut p = base(); + p.sat_mix = 40.0; + p.sat_out = -3.5; + p.os = 1; + v.push(Scn::new("sat_mix_out_os2".into(), p)); + let mut p = base(); + p.drive = 0.0; + p.bias = 0.0; + v.push(Scn::new("sat_off".into(), p)); + let mut p = base(); + p.drive = 0.0; + p.bias = 30.0; + v.push(Scn::new("bias_only".into(), p)); + + // compressor + for (n, f) in [ + ("ratio_inf", (|p: &mut Params| p.ratio = 20.0) as fn(&mut Params)), + ("ratio_2", |p| p.ratio = 2.0), + ("release_auto", |p| p.release = 2000.0), + ("release_fast_attack_fast", |p| { + p.release = 30.0; + p.attack = 0.5; + }), + ("knee_hard", |p| p.knee = 0.0), + ("knee_wide_shape", |p| { + p.knee = 18.0; + p.knee_shape = 70.0; + }), + ("speed_fast", |p| p.speed = 90.0), + ("speed_slow", |p| p.speed = 10.0), + ("detector_peak", |p| p.detector = 0.0), + ("detector_rms", |p| p.detector = 100.0), + ("det_hp", |p| p.det_hp = 200.0), + ("ff_fb_half", |p| p.ff_fb = 50.0), + ("ff_fb_full", |p| p.ff_fb = 100.0), + ("gr_dist", |p| p.gr_dist = 60.0), + ("lookahead", |p| p.lookahead_ms = 5.0), + ("lookahead_os4", |p| { + p.lookahead_ms = 3.0; + p.os = 2; + }), + ("makeup_mix", |p| { + p.makeup = 4.0; + p.mix = 60.0; + }), + ("out_gain", |p| p.out_gain = -6.0), + ("comp_extreme", |p| { + p.thresh = -50.0; + p.ratio = 20.0; + p.attack = 0.1; + p.release = 5.0; + p.gr_dist = 100.0; + }), + ] { + let mut p = base(); + f(&mut p); + v.push(Scn::new(format!("comp_{n}"), p)); + } + + // EQ stages + let mut p = base(); + for st in 0..2 { + p.eq[st].bands[0].gain = 5.0; + p.eq[st].bands[1].gain = -4.0; + p.eq[st].bands[2].gain = 3.0; + } + v.push(Scn::new("eq_all_bands".into(), p)); + let mut p = base(); + p.eq[0].tilt = 3.0; + p.eq[1].tilt = -2.0; + p.eq[0].out_gain = -2.0; + p.eq[1].out_gain = 3.0; + v.push(Scn::new("eq_tilt_gain".into(), p)); + for ty in 0..3 { + let mut p = base(); + for st in 0..2 { + for b in 0..3 { + p.eq[st].bands[b].ty = ty as f64; + p.eq[st].bands[b].gain = 4.0; + } + } + v.push(Scn::new(format!("eq_types{ty}"), p)); + } + let mut p = base(); + p.eq[0].bands[0].gain = 6.0; + p.eq[1].bands[2].gain = 6.0; + p.eq_pre_bypass = true; + v.push(Scn::new("eq_pre_bypass".into(), p.clone())); + p.eq_pre_bypass = false; + p.eq_post_bypass = true; + v.push(Scn::new("eq_post_bypass".into(), p.clone())); + p.eq_post_bypass = false; + p.eq_module_bypass = true; + v.push(Scn::new("eq_module_bypass".into(), p)); + let mut p = base(); + p.eq[0].bands[1].gain = 6.0; + p.eq[1].bands[1].gain = 6.0; + let mut s = Scn::new("eq_tap_pre".into(), p); + s.tap = Some(0); + v.push(s); + let mut p = base(); + p.eq[1].bands[1].gain = 6.0; + let mut s = Scn::new("eq_tap_post".into(), p); + s.tap = Some(1); + v.push(s); + + // sidechain + for (n, mix, hp, lp, gain) in [ + ("key_only", 100.0, 20.0, 20000.0, 0.0), + ("key_half", 50.0, 20.0, 20000.0, 3.0), + ("key_zero", 0.0, 20.0, 20000.0, 0.0), + ("key_filtered", 100.0, 150.0, 5000.0, -2.0), + ] { + let mut p = base(); + p.sc_on = true; + p.sc_mix = mix; + p.sc_hp = hp; + p.sc_lp = lp; + p.sc_gain = gain; + let mut s = Scn::new(format!("sc_{n}"), p); + s.key = true; + v.push(s); + } + let mut p = base(); + p.sc_on = true; + let mut s = Scn::new("sc_solo".into(), p.clone()); + s.key = true; + s.solo = true; + v.push(s); + let mut s = Scn::new("sc_on_no_bus".into(), p.clone()); + s.key = false; + v.push(s); + p.os = 2; + p.lookahead_ms = 4.0; + let mut s = Scn::new("sc_os4_lookahead".into(), p); + s.key = true; + v.push(s); + + // bypass / delta / match + let mut p = base(); + p.bypass = true; + v.push(Scn::new("bypass".into(), p)); + let mut s = Scn::new("delta".into(), base()); + s.delta = true; + v.push(s); + let mut p = base(); + p.gain_match = true; + let mut s = Scn::new("gain_match".into(), p); + s.secs = 4.2; + v.push(s); + let mut s = Scn::new("sat_match".into(), base()); + s.secs = 4.2; + s.sat_req = true; + v.push(s); + let mut p = base(); + p.gain_match = true; + let mut s = Scn::new("match_request_midrun".into(), p); + s.secs = 4.2; + s.match_req = true; + s.sat_req = true; + v.push(s); + + // engine-level behaviours + let mut s = Scn::new("no_smoothing_automation".into(), base()); + s.smoothing = false; + s.vary = true; + s.blocks = 1; + v.push(s); + for (i, sr) in [44100.0, 96000.0, 22050.0].iter().enumerate() { + let mut s = Scn::new(format!("sr{i}"), base()); + s.sr = *sr; + s.p.os = 1; + s.p.lookahead_ms = 2.0; + v.push(s); + } + let mut s = Scn::new("blocks_ragged".into(), base()); + s.blocks = 1; + s.p.lookahead_ms = 2.5; + v.push(s); + let mut s = Scn::new("tick_api".into(), base()); + s.blocks = 2; + s.secs = 0.6; + v.push(s); + let mut s = Scn::new("automation".into(), base()); + s.vary = true; + s.blocks = 1; + v.push(s); + let mut s = Scn::new("automation_os4_sc".into(), base()); + s.vary = true; + s.p.os = 2; + s.p.sc_on = true; + s.key = true; + v.push(s); + let mut s = Scn::new("kitchen_sink".into(), base()); + s.vary = true; + s.blocks = 1; + s.key = true; + s.p.sc_on = true; + s.p.os = 1; + s.p.lookahead_ms = 3.0; + s.p.release = 2000.0; + s.p.gain_match = true; + s.secs = 4.2; + s.sat_req = true; + for st in 0..2 { + for b in 0..3 { + s.p.eq[st].bands[b].gain = 2.5 - b as f64; + } + s.p.eq[st].tilt = 1.0; + } + v.push(s); + v +} + +const RAGGED: [usize; 8] = [1, 7, 64, 100, 333, 480, 1024, 31]; + +/// Deterministic parameter "automation" applied before block `k`. +fn vary(p: &mut Params, base: &Params, k: usize) { + p.thresh = base.thresh + (k % 7) as f64 * 1.5; + p.drive = base.drive + (k % 5) as f64 * 4.0; + p.bias = base.bias + ((k % 3) as f64 - 1.0) * 6.0; + p.makeup = (k % 4) as f64 * 0.7; + p.mix = 100.0 - (k % 6) as f64 * 5.0; + p.sat_mix = 100.0 - (k % 4) as f64 * 10.0; + p.sat_hp = if k % 9 < 3 { 20.0 } else { 120.0 }; + p.eq[0].bands[1].gain = ((k % 8) as f64 - 4.0) * 0.8; + p.eq[1].bands[0].gain = ((k % 5) as f64 - 2.0) * 1.0; + p.eq[1].bands[0].freq = 100.0 + (k % 11) as f64 * 20.0; + p.shape = if k % 40 < 20 { base.shape } else { (base.shape + 3) % 14 }; +} + +pub struct Out { + pub audio: Vec, + pub telem: Vec<(String, u64)>, +} + +pub fn render(sc: &Scn) -> Out { + let n = (sc.sr * sc.secs) as usize; + let (xl, xr) = input(n, sc.sr, 1); + let (kl, kr) = key(n, sc.sr); + let mut e = Engine::new(sc.sr); + e.smoothing = sc.smoothing; + e.set_params(&sc.p); + e.sc_solo = sc.solo; + e.delta_on = sc.delta; + if let Some(t) = sc.tap { + e.eq_tap_on = true; + e.eq_vs = t; + } + if sc.match_req { + e.request_match(); + } + if sc.sat_req { + e.request_sat_match(); + } + let mut l = xl.clone(); + let mut r = xr.clone(); + let mut p = sc.p; + let mut audio = Vec::with_capacity(n * 2); + let mut sat_results: Vec = Vec::new(); + let mut lat_trace: Vec = Vec::new(); + let mut pos = 0usize; + let mut k = 0usize; + if sc.blocks == 2 { + for i in 0..n { + if sc.vary && i % 480 == 0 { + vary(&mut p, &sc.p, i / 480); + e.set_params(&p); + } + let (a, b) = e.tick(xl[i] as f64, xr[i] as f64); + audio.push(a as f32); + audio.push(b as f32); + } + } else { + while pos < n { + let len = if sc.blocks == 1 { RAGGED[k % RAGGED.len()] } else { 256 }.min(n - pos); + if sc.vary { + vary(&mut p, &sc.p, k); + e.set_params(&p); + } + if k == 40 && sc.match_req { + e.request_match(); + } + let (ls, rs) = (&mut l[pos..pos + len], &mut r[pos..pos + len]); + if sc.key { + e.process_sc(ls, rs, Some((&kl[pos..pos + len], &kr[pos..pos + len]))); + } else { + e.process(ls, rs); + } + for i in 0..len { + audio.push(l[pos + i]); + audio.push(r[pos + i]); + } + if let Some(v) = e.take_sat_result() { + sat_results.push(v); + } + if k % 16 == 0 { + lat_trace.push(e.latency()); + } + pos += len; + k += 1; + } + } + + let mut t: Vec<(String, u64)> = Vec::new(); + let mut f = |name: &str, v: f64| t.push((name.to_string(), v.to_bits())); + f("latency", e.latency() as f64); + for (i, v) in lat_trace.iter().enumerate() { + f(&format!("lat_trace{i}"), *v as f64); + } + f("opk0", e.opk[0]); + f("opk1", e.opk[1]); + f("clip", e.clip_f as u8 as f64); + f("gr_blk", e.gr_blk); + f("gr_pk", e.gr_pk); + f("vz_blk", e.vz_blk); + f("vz_lv", e.vz_lv); + f("mn_blk", e.mn_blk); + f("mn_lv", e.mn_lv); + f("sat_blk", e.sat_blk); + f("sat_vz", e.sat_vz); + f("fms", e.fms); + f("ims", e.ims); + f("oms", e.oms); + f("pms", e.pms); + f("sms", e.sms); + f("diff_db", e.diff_db); + f("diff_disp", e.diff_disp); + f("sat_db", e.sat_db); + f("match_trim", e.match_trim); + f("gate_open", e.gate_open() as u8 as f64); + f("out_matching", e.out_matching() as u8 as f64); + f("sat_matching", e.sat_matching() as u8 as f64); + f("out_prog", e.out_match_progress()); + f("sat_prog", e.sat_match_progress()); + f("eq_act0", e.eq_act[0] as u8 as f64); + f("eq_act1", e.eq_act[1] as u8 as f64); + for (i, v) in sat_results.iter().enumerate() { + f(&format!("sat_result{i}"), *v); + } + let gc = e.gain_computer(); + f("gc_thr", gc.thr); + f("gc_knw", gc.knw); + f("gc_cslope", gc.cslope); + f("gc_kc0", gc.kc0); + f("gc_kc1", gc.kc1); + f("gc_kc2", gc.kc2); + let head = e.scope.head(); + f("scope_head", head as f64); + for i in 0..head.min(200) { + let (o, pr) = e.scope.get(head - 1 - i); + f(&format!("scope{i}o"), o as f64); + f(&format!("scope{i}p"), pr as f64); + } + let th = e.tap.w.load(std::sync::atomic::Ordering::Acquire); + f("tap_head", th as f64); + for i in 0..th.min(300) { + f(&format!("tap{i}"), e.tap.get(th - 1 - i) as f64); + } + // parameters decode as the UI sees them (keeps eq decode in the net) + for b in 0..3 { + let d = decode_band(&sc.p.eq[0], b); + f(&format!("dec{b}"), d.freq + d.gain + d.q + d.kind as f64); + } + Out { audio, telem: t } +} + +pub fn fnv(h: &mut u64, bytes: &[u8]) { + for b in bytes { + *h ^= *b as u64; + *h = h.wrapping_mul(0x100000001b3); + } +} + +/// (audio hash, telemetry hash, rms, peak) +pub fn summarize(o: &Out) -> (u64, u64, f64, f64) { + let mut ha = 0xcbf29ce484222325u64; + let (mut sq, mut pk) = (0.0f64, 0.0f64); + for s in &o.audio { + fnv(&mut ha, &s.to_bits().to_le_bytes()); + sq += (*s as f64) * (*s as f64); + pk = pk.max((*s as f64).abs()); + } + let mut ht = 0xcbf29ce484222325u64; + for (k, v) in &o.telem { + fnv(&mut ht, k.as_bytes()); + fnv(&mut ht, &v.to_le_bytes()); + } + (ha, ht, (sq / o.audio.len().max(1) as f64).sqrt(), pk) +} diff --git a/rust/satcomp-plugin/Cargo.toml b/rust/satcomp-plugin/Cargo.toml index 9f9bf36..577af14 100644 --- a/rust/satcomp-plugin/Cargo.toml +++ b/rust/satcomp-plugin/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "satcomp" -version = "0.5.1" +version = "0.5.2" edition = "2021" license = "GPL-3.0-or-later" publish = false @@ -11,6 +11,7 @@ crate-type = ["cdylib", "lib"] [dependencies] nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", features = ["vst3"] } satcomp-dsp = { path = "../satcomp-dsp" } +satcomp-ui = { path = "../satcomp-ui" } nih_plug_egui = { path = "../vendor/nih_plug_egui" } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/rust/satcomp-plugin/src/gui/golden.rs b/rust/satcomp-plugin/src/gui/golden.rs new file mode 100644 index 0000000..957d35b --- /dev/null +++ b/rust/satcomp-plugin/src/gui/golden.rs @@ -0,0 +1,427 @@ +//! Headless UI regression net. Runs the real editor frame function in an egui context against a fake host, drives it with a +//! scripted mouse (no private state is touched), and hashes the draw commands of every frame. The recorded hashes live in +//! `golden.txt`; any visual or interaction change shows up as a different hash at a named step. +//! +//! Re-record deliberately (only when the UI is *meant* to change): +//! UI_GOLDEN_OUT=$PWD/satcomp-plugin/src/gui/golden.txt cargo test --release -p satcomp ui_matches_golden_fixture + +use super::ui::State; +use crate::params::SatCompParams; +use crate::Shared; +use nih_plug::prelude::*; +use nih_plug_egui::egui::{self, Event, Modifiers, MouseWheelUnit, PointerButton, Pos2, RawInput, Rect, Vec2}; +use std::sync::Arc; + +/// Fake host: records every parameter write. (nih-plug keeps its parameter setters crate-private, so values cannot be +/// echoed back; parameters stay at their defaults while the script runs, and the write log is hashed with each frame.) +#[derive(Default)] +struct FakeHost { + log: parking_lot::Mutex>, +} + +impl GuiContext for FakeHost { + fn plugin_api(&self) -> PluginApi { + PluginApi::Vst3 + } + fn request_resize(&self) -> bool { + true + } + unsafe fn raw_begin_set_parameter(&self, param: ParamPtr) { + self.log.lock().push(format!("begin {}", param.name())); + } + unsafe fn raw_set_parameter_normalized(&self, param: ParamPtr, normalized: f32) { + self.log.lock().push(format!("set {} {:.6}", param.name(), normalized)); + } + unsafe fn raw_end_set_parameter(&self, param: ParamPtr) { + self.log.lock().push(format!("end {}", param.name())); + } + fn get_state(&self) -> nih_plug::wrapper::state::PluginState { + nih_plug::wrapper::state::PluginState { version: String::new(), params: Default::default(), fields: Default::default() } + } + fn set_state(&self, _state: nih_plug::wrapper::state::PluginState) {} +} + +struct Rig { + ctx: egui::Context, + host: Arc, + params: Arc, + shared: Arc, + st: State, + t: f64, + /// screen points per logical unit (window 700x420 = scale 1.25 at ppp 1, scaled with `zoom`) + k: f32, + size: Vec2, + pos: Option, + down: bool, + rdown: bool, + out: Vec<(String, u64)>, + /// every host parameter write so far (the frame hash drains the log; tests want to read it) + writes: Vec, + /// tests that drive `sat_pk` themselves + manual_sat: bool, +} + +fn fnv(s: &str) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for b in s.bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + h +} + +impl Rig { + fn new(zoom: f32) -> Self { + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(zoom); + satcomp_ui::init_ctx(&ctx); + let params = Arc::new(SatCompParams::from_defaults(None)); + let shared = Arc::new(Shared::new()); + let (pal, light) = super::ui::initial_palette(¶ms); + let mut st = State::new(pal, light, 0, ¶ms); + st.app.themes.clear(); // never depend on the machine's themes.json + Self { + ctx, + host: Arc::new(FakeHost::default()), + params, + shared, + st, + t: 1.0, + k: 1.25, + size: Vec2::new(700.0, 420.0), + pos: None, + down: false, + rdown: false, + out: Vec::new(), + writes: Vec::new(), + manual_sat: false, + } + } + + /// Deterministic audio-side telemetry so the meters, readouts and spectrum draw something. + fn feed(&self) { + use std::sync::atomic::Ordering::Relaxed; + let n = self.out.len() as f32; + let w = (n * 0.07).sin().abs(); + let sh = &self.shared; + sh.opk[0].store(0.15 + 0.8 * w, Relaxed); + sh.opk[1].store(0.1 + 0.7 * (n * 0.05).cos().abs(), Relaxed); + sh.gr_pk.store(8.0 * w, Relaxed); + sh.fms.store(0.002 + 0.05 * w, Relaxed); + sh.vz_lv.store(0.05 + 0.6 * w, Relaxed); + sh.sat_vz.store(0.1 + 0.5 * (n * 0.03).sin().abs(), Relaxed); + sh.lim_gr_pk.store(4.0 * (n * 0.045).sin().abs(), Relaxed); + if !self.manual_sat { + sh.sat_pk.store(0.1 + 0.7 * (n * 0.03).sin().abs(), Relaxed); + } + sh.mn_lv.store(0.05 + 0.5 * (n * 0.02).cos().abs(), Relaxed); + sh.diff_disp.store(6.0 * (n * 0.04).sin(), Relaxed); + sh.sat_db.store(3.0 * (n * 0.06).sin(), Relaxed); + sh.sc_bus.store(self.out.len() % 97 < 60, Relaxed); + for i in 0..crate::TapRing::LEN { + let t = (i as f32 + n * 37.0) * 0.001; + let v = 0.3 * (t * 211.0).sin() + 0.2 * (t * 1733.0).sin() + 0.1 * (t * 7919.0).sin(); + sh.tap.buf[i].store(v.to_bits(), Relaxed); + } + sh.tap.w.store(crate::TapRing::LEN * 3, Relaxed); + } + + fn frame(&mut self, label: &str, events: Vec, dt: f64) { + self.feed(); + self.t += dt; + let raw = RawInput { + time: Some(self.t), + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, self.size)), + events, + ..Default::default() + }; + let setter = ParamSetter::new(&*self.host); + let (params, shared) = (self.params.clone(), self.shared.clone()); + let st = &mut self.st; + let full = self.ctx.run(raw, |ctx| super::run_frame(ctx, &setter, st, ¶ms, &shared)); + let writes: Vec = self.host.log.lock().drain(..).collect(); + self.writes.extend(writes.iter().cloned()); + self.out.push((label.to_string(), fnv(&format!("{:?}|{:?}", full.shapes, writes)))); + } + + fn p(&self, x: f32, y: f32) -> Pos2 { + Pos2::new(x * self.k, y * self.k) + } + + fn mv(&mut self, label: &str, x: f32, y: f32) { + let pos = self.p(x, y); + self.pos = Some(pos); + self.frame(label, vec![Event::PointerMoved(pos)], 0.03); + } + + fn button(&mut self, label: &str, b: PointerButton, pressed: bool) { + let pos = self.pos.unwrap_or(Pos2::ZERO); + match b { + PointerButton::Primary => self.down = pressed, + _ => self.rdown = pressed, + } + self.frame(label, vec![Event::PointerButton { pos, button: b, pressed, modifiers: Modifiers::NONE }], 0.03); + } + + /// move + press + release at a logical position + fn click(&mut self, label: &str, x: f32, y: f32) { + self.mv(&format!("{label}/move"), x, y); + self.button(&format!("{label}/down"), PointerButton::Primary, true); + self.button(&format!("{label}/up"), PointerButton::Primary, false); + self.frame(&format!("{label}/settle"), vec![], 0.05); + } + + fn rclick(&mut self, label: &str, x: f32, y: f32) { + self.mv(&format!("{label}/move"), x, y); + self.button(&format!("{label}/down"), PointerButton::Secondary, true); + self.button(&format!("{label}/up"), PointerButton::Secondary, false); + self.frame(&format!("{label}/settle"), vec![], 0.05); + } + + /// press at (x, y0), move to y1 in `n` steps, release + fn drag(&mut self, label: &str, x: f32, y0: f32, y1: f32, n: usize) { + self.mv(&format!("{label}/move"), x, y0); + self.button(&format!("{label}/down"), PointerButton::Primary, true); + for i in 1..=n { + let y = y0 + (y1 - y0) * i as f32 / n as f32; + self.mv(&format!("{label}/drag{i}"), x, y); + } + self.button(&format!("{label}/up"), PointerButton::Primary, false); + self.frame(&format!("{label}/settle"), vec![], 0.05); + } + + fn wheel(&mut self, label: &str, x: f32, y: f32, dy: f32) { + self.mv(&format!("{label}/move"), x, y); + let pos = self.pos.unwrap_or(Pos2::ZERO); + let _ = pos; + self.frame( + &format!("{label}/wheel"), + vec![Event::MouseWheel { unit: MouseWheelUnit::Point, delta: Vec2::new(0.0, dy), modifiers: Modifiers::NONE }], + 0.03, + ); + self.frame(&format!("{label}/settle"), vec![], 0.05); + } + + fn idle(&mut self, label: &str, n: usize, dt: f64) { + for i in 0..n { + self.frame(&format!("{label}{i}"), vec![], dt); + } + } +} + +fn script() -> Vec<(String, u64)> { + let mut r = Rig::new(1.0); + r.idle("boot", 4, 0.016); + + // sliders: drag, wheel, double-click reset + r.drag("drive_drag", 41.0, 215.0, 190.0, 6); + r.wheel("thresh_wheel", 183.0, 215.0, 20.0); + r.wheel("thresh_wheel_dn", 183.0, 215.0, -20.0); + r.drag("ratio_drag", 251.0, 215.0, 240.0, 5); + r.click("drive_dbl_a", 41.0, 215.0); + r.click("drive_dbl_b", 41.0, 215.0); + r.drag("hp_drag", 41.0, 250.0, 225.0, 4); + r.drag("lp_drag", 41.0, 270.0, 250.0, 4); + r.drag("makeup_drag", 507.0, 215.0, 200.0, 4); + r.idle("idle_a", 10, 0.05); + + // saturator shape selector: step, then open its menu and pick an item + r.click("shape_next", 132.0, 42.0); + r.click("shape_next2", 132.0, 42.0); + r.click("shape_menu_open", 75.0, 42.0); + r.idle("shape_menu_idle", 2, 0.05); + r.click("shape_menu_pick", 75.0, 92.0); + r.click("shape_prev", 18.0, 42.0); + + // oversampling, sidechain, bypass, delta, gain match + r.click("os_x2", 192.0, 42.0); + r.click("os_x4", 232.0, 42.0); + r.click("os_x1", 172.0, 42.0); + r.click("sidechain_on", 314.0, 42.0); + r.idle("sidechain_idle", 3, 0.05); + r.drag("sc_gain_drag", 190.0, 175.0, 160.0, 3); + r.click("sidechain_off", 314.0, 42.0); + r.click("delta_on", 460.0, 42.0); + r.click("delta_off", 460.0, 42.0); + r.click("bypass_on", 520.0, 42.0); + r.idle("bypass_idle", 3, 0.05); + r.click("bypass_off", 520.0, 42.0); + r.click("lim_off", 445.0, 16.0); + r.idle("lim_off_idle", 3, 0.05); + r.click("lim_on", 445.0, 16.0); + r.click("gain_match", 507.0, 135.0); + r.idle("gain_match_idle", 6, 0.1); + r.click("gain_match_off", 507.0, 135.0); + + // sat plot: pencil (custom curve draw view), draw points, leave + r.click("pencil_on", 130.0, 66.0); + r.idle("pencil_idle", 3, 0.05); + r.click("curve_pt_add", 60.0, 100.0); + r.drag("curve_pt_drag", 80.0, 120.0, 90.0, 4); + r.click("curve_pt_add2", 110.0, 80.0); + r.click("pencil_off", 130.0, 66.0); + + // scope icon: on, drag the view, off + r.click("scope_on", 410.0, 64.0); + r.idle("scope_idle", 4, 0.05); + r.drag("scope_drag", 280.0, 110.0, 130.0, 4); + r.click("scope_off", 410.0, 64.0); + + // compressor plot interaction + r.drag("ccurve_drag", 200.0, 120.0, 100.0, 4); + + // EQ page + r.click("eq_on", 387.0, 42.0); + r.idle("eq_idle", 4, 0.05); + r.drag("eq_band_drag", 190.0, 130.0, 100.0, 5); + r.drag("eq_band2_drag", 260.0, 130.0, 150.0, 5); + r.wheel("eq_band_wheel", 190.0, 100.0, 20.0); + r.click("eq_band_dbl_a", 190.0, 100.0); + r.click("eq_band_dbl_b", 190.0, 100.0); + r.click("eq_type_icon", 160.0, 207.0); + r.click("eq_type_icon2", 200.0, 220.0); + r.drag("eq_freq_cell", 183.0, 260.0, 240.0, 4); + r.drag("eq_gain_cell", 183.0, 300.0, 280.0, 4); + r.drag("eq_tilt_cell", 387.0, 260.0, 240.0, 4); + r.click("eq_stage_toggle", 300.0, 177.0); + r.idle("eq_stage_idle", 3, 0.05); + r.click("eq_stage_toggle2", 160.0, 177.0); + r.click("eq_module_byp", 370.0, 42.0); + r.idle("eq_byp_idle", 2, 0.05); + r.click("eq_module_byp_off", 370.0, 42.0); + r.click("eq_off", 400.0, 42.0); + + // presets: next / previous (applies factory presets through the host) + r.click("preset_next", 332.0, 16.0); + r.idle("preset_next_idle", 3, 0.05); + r.click("preset_next2", 332.0, 16.0); + r.click("preset_prev", 332.0 - 25.0, 16.0); + r.idle("preset_idle", 8, 0.1); + + // colour scheme: single click cycles (after the double-click window), right-click menu, double-click toggles light + r.click("logo_single", 20.0, 15.0); + r.idle("logo_single_wait", 8, 0.05); + r.rclick("logo_menu", 20.0, 15.0); + r.idle("logo_menu_idle", 2, 0.05); + r.click("logo_menu_pick", 60.0, 80.0); + r.click("logo_dbl_a", 20.0, 15.0); + r.click("logo_dbl_b", 20.0, 15.0); + r.idle("light_idle", 3, 0.05); + r.click("logo_dbl2_a", 20.0, 15.0); + r.click("logo_dbl2_b", 20.0, 15.0); + + // About / Appearance / Changelog + r.click("about_open", 80.0, 15.0); + r.idle("about_idle", 3, 0.05); + r.wheel("about_scroll", 200.0, 250.0, 40.0); + r.wheel("about_scroll2", 200.0, 250.0, 40.0); + r.click("about_tab_appearance", 180.0, 42.0); + r.idle("appearance_idle", 2, 0.05); + r.wheel("appearance_scroll", 100.0, 150.0, 40.0); + r.click("appearance_scheme_pick", 80.0, 100.0); + r.click("appearance_font_pick", 330.0, 100.0); + r.click("appearance_font_pick2", 330.0, 140.0); + r.click("about_tab_changelog", 300.0, 42.0); + r.idle("changelog_idle", 2, 0.05); + r.wheel("changelog_scroll", 200.0, 200.0, 40.0); + r.drag("changelog_thumb", 414.0, 100.0, 200.0, 4); + r.click("about_tab_about", 60.0, 42.0); + r.click("about_close", 387.0, 42.0); + r.idle("closed_idle", 3, 0.05); + + // window scale button + a different pixel density + r.click("scale_menu_open", 397.0, 16.0); + r.idle("scale_menu_idle", 2, 0.05); + r.click("scale_menu_close", 300.0, 300.0); + + let mut r2 = Rig::new(2.0); + r2.size = Vec2::new(1400.0 / 2.0 * 2.0, 840.0); + r2.k = 2.5; + r2.idle("hidpi_boot", 4, 0.016); + r2.drag("hidpi_drive", 41.0, 215.0, 190.0, 4); + r2.click("hidpi_eq_on", 387.0, 42.0); + r2.idle("hidpi_idle", 3, 0.05); + + let mut out = r.out; + out.extend(r2.out.into_iter().map(|(l, h)| (format!("hidpi:{l}"), h))); + out +} + +#[test] +fn ui_matches_golden_fixture() { + let got = script(); + let text: String = got.iter().map(|(l, h)| format!("{l} {h:016x}\n")).collect(); + if let Ok(path) = std::env::var("UI_GOLDEN_OUT") { + std::fs::write(path, &text).unwrap(); + return; + } + let fixture = include_str!("golden.txt"); + let want: Vec<(&str, &str)> = fixture.lines().filter(|l| !l.is_empty() && !l.starts_with('#')).filter_map(|l| l.split_once(' ')).collect(); + assert_eq!(want.len(), got.len(), "frame count changed: fixture {} vs now {}", want.len(), got.len()); + let mut bad = Vec::new(); + for ((wl, wh), (gl, gh)) in want.iter().zip(&got) { + if wl != gl || *wh != format!("{gh:016x}") { + bad.push(format!("{gl} (fixture {wl} {wh}, now {gh:016x})")); + } + } + assert!(bad.is_empty(), "{} frames differ; first: {}", bad.len(), bad.first().unwrap()); +} + +#[test] +fn limiter_button_writes_its_parameter() { + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + r.click("lim", 445.0, 16.0); + assert!(r.writes.iter().any(|w| w.starts_with("set Limiter") && w.ends_with("0.000000")), "{:?}", r.writes); + // and the preset-stored state: the parameter is in the preset table and not excluded + assert!(crate::params::TABLE.iter().any(|e| e.1 == "lim_on" && e.4 == 1.0)); + assert!(!crate::presets::EXCLUDED.contains(&"lim_on")); +} + +/// The post-saturator meter turns accent when the saturator output passes 0 dBFS and holds it for one second. +#[test] +fn sat_meter_clip_holds_for_a_second_then_releases() { + let run = |peak: f32, probe: usize| { + let mut r = Rig::new(1.0); + r.manual_sat = true; + r.idle("boot", 3, 0.016); + r.shared.sat_pk.store(peak, std::sync::atomic::Ordering::Relaxed); + r.frame("hit", vec![], 0.016); + for i in 0..probe { + r.shared.sat_pk.store(0.0, std::sync::atomic::Ordering::Relaxed); + r.frame(&format!("after{i}"), vec![], 0.05); + } + r.out.last().unwrap().1 + }; + // 0.3 s later: clipped meter differs from a just-under-0 dBFS one (accent colour held) + assert_ne!(run(1.0, 6), run(0.99999, 6)); + // 1.5 s later: the hold is over, both draw the same + assert_eq!(run(1.0, 30), run(0.99999, 30)); +} + +#[test] +fn ui_script_is_deterministic() { + let a = script(); + let b = script(); + assert_eq!(a, b); +} + +/// ASYM is the bottom half of the BIAS / ASYM group: a drag lowers the value of the current shaper only, double-click resets it, +/// and it writes no host parameter (stored in the project / presets). +#[test] +fn asym_slider_writes_the_shapers_value() { + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + assert_eq!(r.params.asym_snapshot()[0], 100.0); + r.drag("asym", 110.0, 225.0, 245.0, 5); // drag down = lower (bottom half of the BIAS / ASYM group) + let a = r.params.asym_snapshot(); + assert!(a[0] < 100.0, "dragging ASYM changed nothing: {:?}", &a[..3]); + assert_eq!(a[1], 100.0, "other shapers keep their own value"); + assert!(!r.writes.iter().any(|w| w.contains("Asym")), "ASYM is not a host parameter: {:?}", r.writes); + r.click("asym_a", 110.0, 225.0); + r.click("asym_b", 110.0, 225.0); // double-click = reset + assert_eq!(r.params.asym_snapshot()[0], 100.0); + // the top half is still BIAS + r.drag("bias", 110.0, 207.0, 187.0, 5); + assert!(r.writes.iter().any(|w| w.starts_with("set Bias")), "BIAS half wrote nothing: {:?}", r.writes); +} diff --git a/rust/satcomp-plugin/src/gui/golden.txt b/rust/satcomp-plugin/src/gui/golden.txt new file mode 100644 index 0000000..4956a79 --- /dev/null +++ b/rust/satcomp-plugin/src/gui/golden.txt @@ -0,0 +1,471 @@ +boot0 aa657a4a1de57931 +boot1 c5000c72bee0a224 +boot2 7fbe8355feb1a77c +boot3 5eb9b4e35ab2f1f7 +drive_drag/move d34c8bc70047ac23 +drive_drag/down 94ce5c42bce9ded5 +drive_drag/drag1 d5744cca6396575d +drive_drag/drag2 ab07d61f2cccf159 +drive_drag/drag3 2d263fefb733ca0f +drive_drag/drag4 ed191d01a0309759 +drive_drag/drag5 939ce051f27fad63 +drive_drag/drag6 a3a908a6fa591ca1 +drive_drag/up c2a9d2aade4f0bcf +drive_drag/settle 2734a08fd3ad0ca5 +thresh_wheel/move 34e138d0b16b6528 +thresh_wheel/wheel 8faa21c6d48180cc +thresh_wheel/settle 37d31db6e3f2d368 +thresh_wheel_dn/move 74e7a0e86a2ec540 +thresh_wheel_dn/wheel 1b33ece00e6891ef +thresh_wheel_dn/settle 15afcb85000ba2d5 +ratio_drag/move 0d7f15c06d35d84a +ratio_drag/down 2399f68101527212 +ratio_drag/drag1 7ad24fa0617ce67b +ratio_drag/drag2 8646c19754e98354 +ratio_drag/drag3 ea316be3e3e04a35 +ratio_drag/drag4 f9883b8e0730ab2d +ratio_drag/drag5 d0b71f5a69286a0c +ratio_drag/up f7c729c6f1c9efb5 +ratio_drag/settle a62a8eb3c9b9ed84 +drive_dbl_a/move d22eaacc15d3859d +drive_dbl_a/down 68d50fbc9ba86210 +drive_dbl_a/up 4d4fd61ba7318f08 +drive_dbl_a/settle 298a4eebad621c9c +drive_dbl_b/move abd7b835d9e53cdb +drive_dbl_b/down 4d54795367644039 +drive_dbl_b/up 5a4e7d7c9638d03e +drive_dbl_b/settle c866615557afbd99 +hp_drag/move 59501076693dbed6 +hp_drag/down df5d6309fecf75f3 +hp_drag/drag1 b36dfbd843253260 +hp_drag/drag2 3f7ed97407946721 +hp_drag/drag3 8ce8c5373b2676ca +hp_drag/drag4 e4e52aea9535b128 +hp_drag/up 421820131a9c4d6c +hp_drag/settle 2461017b7a025a24 +lp_drag/move a24e38ee56858434 +lp_drag/down c3f473d605ab6de4 +lp_drag/drag1 c43d81d4846eaad3 +lp_drag/drag2 87ccc4ad72bcd4ff +lp_drag/drag3 a5361221c11cb11b +lp_drag/drag4 c23c63a02f0133df +lp_drag/up c3356de2356f332d +lp_drag/settle 72a22b24a6e2933a +makeup_drag/move 0010437ddacf0b6a +makeup_drag/down 5b2e99c726f9b59e +makeup_drag/drag1 921984886a54edda +makeup_drag/drag2 4302e058691d1158 +makeup_drag/drag3 3a591911a807a4d8 +makeup_drag/drag4 e31d2191e755bfc6 +makeup_drag/up 72bc28270062afb4 +makeup_drag/settle 872b943b26cfea9a +idle_a0 f2c645a650cb4d1d +idle_a1 74f1c860648f39cd +idle_a2 5ff51f62c777e2de +idle_a3 91cee8adc4fa9ac4 +idle_a4 a92c95e990bd8958 +idle_a5 2661e9286233306a +idle_a6 f751f3a3079dee6f +idle_a7 2c530160aa4a819c +idle_a8 b9db6b5a029722d3 +idle_a9 efcca7fad0596898 +shape_next/move 8ad7f55376770374 +shape_next/down 66a74b115895f1ab +shape_next/up ab101bbfd857a8c5 +shape_next/settle 875a712f0bc8a3d3 +shape_next2/move 57f5989ac18ca6f7 +shape_next2/down 15653bf347f47dae +shape_next2/up ed6b805d25031805 +shape_next2/settle 4f5e1044228453fd +shape_menu_open/move d6cf8e610af6b05c +shape_menu_open/down c4167f4c1882a6a4 +shape_menu_open/up 91a0f0150f07afb2 +shape_menu_open/settle 0a34ce7e04dcb003 +shape_menu_idle0 054c6521564cb277 +shape_menu_idle1 4b0849e881e5408f +shape_menu_pick/move 35c30486d1fb49b3 +shape_menu_pick/down 10a4b96acf6edfe8 +shape_menu_pick/up 4c7cc8f88659d067 +shape_menu_pick/settle 8d441573274986df +shape_prev/move 452c1b6557c46cd9 +shape_prev/down 20ce21befaaf69eb +shape_prev/up e285330db099c327 +shape_prev/settle f6be382be6c414d8 +os_x2/move 1da5723a1e965a04 +os_x2/down 362e4d86983f1b93 +os_x2/up 760877a473ec7e64 +os_x2/settle c01bf038845092b0 +os_x4/move 5cfb88a5f57eb808 +os_x4/down acafb8e6f9d8fb01 +os_x4/up 5b70deeaaf497c84 +os_x4/settle 4b5d92dda2b02e88 +os_x1/move b6993a36c71a1d10 +os_x1/down 616f4d780d3f78eb +os_x1/up a02772186a4432c8 +os_x1/settle 66d0290ea5265947 +sidechain_on/move 804699ddfafc7978 +sidechain_on/down 31f5f879549d30a4 +sidechain_on/up 4f2094a9673f9c79 +sidechain_on/settle 1a7b0ea98f13a706 +sidechain_idle0 727f073050dc573b +sidechain_idle1 8fe9e81ed64f8ec3 +sidechain_idle2 9623518836036a44 +sc_gain_drag/move ee7389b06b58949b +sc_gain_drag/down c02477bdf4b51cd6 +sc_gain_drag/drag1 740ed3688f81b264 +sc_gain_drag/drag2 fac4afdf04f9fb5c +sc_gain_drag/drag3 6edf708316552f8e +sc_gain_drag/up f22e925c994098bb +sc_gain_drag/settle 205f2bd0a7164f42 +sidechain_off/move 6ebf11aedf84e627 +sidechain_off/down eab8fef55c44cc5a +sidechain_off/up 45150ff70f1d7315 +sidechain_off/settle 706176cb90e889d2 +delta_on/move 5f2aabc0ddf12004 +delta_on/down bc94d2e8a0fbeb69 +delta_on/up 45198b6363878760 +delta_on/settle e2aab109450f3198 +delta_off/move db4ee35b656fa044 +delta_off/down fbecc63418c30e62 +delta_off/up f3ee5073ed2c0074 +delta_off/settle d833aba8e575e9e3 +bypass_on/move 2fbfa44367e5a9eb +bypass_on/down e852d050c1c22320 +bypass_on/up cbc4163baad8f0ad +bypass_on/settle 7a71a3b60a75d9b4 +bypass_idle0 41eea22d7d8a9ae5 +bypass_idle1 b2488c6401ca5c25 +bypass_idle2 0712dc08fb843119 +bypass_off/move ef70de0dfce4c8c5 +bypass_off/down 378ed51811756595 +bypass_off/up c8fc9c342d6f1a65 +bypass_off/settle 3d58b715d63032c2 +lim_off/move eca7b14cf749eefe +lim_off/down af8a4a40c5c347fe +lim_off/up ed24b5bb83de2d76 +lim_off/settle 9588169154fc2168 +lim_off_idle0 5b381910f532585c +lim_off_idle1 b6bead47608ebee1 +lim_off_idle2 784ecf3986267011 +lim_on/move f3a33a2a149934bd +lim_on/down 88d2777058156160 +lim_on/up ebc41cbbb8abb42c +lim_on/settle 64d946bec10e7520 +gain_match/move ce33b8589e5ca265 +gain_match/down cb636230e3b1e2bc +gain_match/up 1fae7b4c6bedeacd +gain_match/settle 81f09f8bc4e00603 +gain_match_idle0 a9662496c5266b95 +gain_match_idle1 d7a40a2cb44a2dc6 +gain_match_idle2 6705a08acc516576 +gain_match_idle3 c98e19607fb065a1 +gain_match_idle4 6a4146b4357ca242 +gain_match_idle5 98d0d2b9442d4fe7 +gain_match_off/move 15886bcc7f897f89 +gain_match_off/down 4037310d0cc8b105 +gain_match_off/up 641c98aa92fdc01a +gain_match_off/settle 00142e44255a7b99 +pencil_on/move 1309cfde02e7fbf1 +pencil_on/down c3cab7b615de59cc +pencil_on/up d739f2012a341b79 +pencil_on/settle 584e0f035303569c +pencil_idle0 b806dae041582cbe +pencil_idle1 cab55bac1cdcd593 +pencil_idle2 79c3a9cd65a43b84 +curve_pt_add/move 0d9b70357898bd55 +curve_pt_add/down 1e78fbba8d0b7545 +curve_pt_add/up 4c0c07cc78cf664a +curve_pt_add/settle 74933a8b9710b6dc +curve_pt_drag/move ab1dd2a6d55e5d1b +curve_pt_drag/down bb50226fa11ecc27 +curve_pt_drag/drag1 3cc343dd04d40401 +curve_pt_drag/drag2 6f89723b9f32ef60 +curve_pt_drag/drag3 d9676eae3efe72b3 +curve_pt_drag/drag4 a307a297ef10c3af +curve_pt_drag/up 09647545dc7eeaf3 +curve_pt_drag/settle 0786aaf59d290d61 +curve_pt_add2/move 4fe83a04a38356d2 +curve_pt_add2/down 31b07000cbedd375 +curve_pt_add2/up ebf6f9737c9a1756 +curve_pt_add2/settle 8d99a36571271d2f +pencil_off/move 8325b8130bf0b0e9 +pencil_off/down 65b758e1771360e1 +pencil_off/up 4696d0f0a80181e2 +pencil_off/settle 6bce6d4e258465b7 +scope_on/move d2df5dc5adca5fe9 +scope_on/down c399411531743267 +scope_on/up 5f68655da15214c7 +scope_on/settle dd2ce4dac5fad03e +scope_idle0 803c0e1110e60a4a +scope_idle1 be8acbf7bc369122 +scope_idle2 eba01399dc891dd4 +scope_idle3 d5c25deee3ee14cc +scope_drag/move cbd1e5b9bb472aed +scope_drag/down effd01a4fa932902 +scope_drag/drag1 0f825b3f5ba315a6 +scope_drag/drag2 a7f05be60f6bc9a1 +scope_drag/drag3 d9548e461a682a89 +scope_drag/drag4 ce31428e7eaf9769 +scope_drag/up 7fe4979ffb87f746 +scope_drag/settle 9cbb8eaf044e3ca8 +scope_off/move cb7b5c51c35ee687 +scope_off/down 6ce7abf85f5c49b4 +scope_off/up 031e5c0b2396b778 +scope_off/settle c8cf9f3d34c054a3 +ccurve_drag/move 4297b172c9e260a1 +ccurve_drag/down 5a4a4844cf2ccc50 +ccurve_drag/drag1 0d70686c47c627e5 +ccurve_drag/drag2 8c06929998c4247f +ccurve_drag/drag3 99c62ebcf616c951 +ccurve_drag/drag4 bcc977d53a8ffaa4 +ccurve_drag/up 497cbf36fdf25efc +ccurve_drag/settle c26bb56092165ef1 +eq_on/move 20a8283957649a5e +eq_on/down fad67581c066e6c0 +eq_on/up fd73ea80b522dacc +eq_on/settle c709057454f3e5ee +eq_idle0 bc18742bae2c48c5 +eq_idle1 e8586856591acd11 +eq_idle2 fb4bad87b931a28d +eq_idle3 367ae1ef97360a66 +eq_band_drag/move f78f3abdffd09333 +eq_band_drag/down 103229277558694f +eq_band_drag/drag1 615b1766fdbf13b5 +eq_band_drag/drag2 8644b13d9aa249de +eq_band_drag/drag3 5463fdd68a0320f8 +eq_band_drag/drag4 9567f94592aea6c2 +eq_band_drag/drag5 9db9a507dbba87fc +eq_band_drag/up affe26643f3b77af +eq_band_drag/settle 60028543ae00cc77 +eq_band2_drag/move 602f95c99a5fee0f +eq_band2_drag/down eeacc417be2e9869 +eq_band2_drag/drag1 f33d23b2d295679a +eq_band2_drag/drag2 4f21d15a16290c61 +eq_band2_drag/drag3 77d2e74f08679de9 +eq_band2_drag/drag4 792b6d7f08994bdc +eq_band2_drag/drag5 daf54c238a0ea576 +eq_band2_drag/up f84399c5a6e298be +eq_band2_drag/settle 7f24dc34acafde09 +eq_band_wheel/move bd3efc11bb30c4f8 +eq_band_wheel/wheel a6da61760adef3c2 +eq_band_wheel/settle a0674fd6dd6d0bbb +eq_band_dbl_a/move ff675a51f11b8f8a +eq_band_dbl_a/down f72989012c83f727 +eq_band_dbl_a/up efbc2208d649379f +eq_band_dbl_a/settle 3d1b6727a3ee26c0 +eq_band_dbl_b/move a4639a026e7c25c9 +eq_band_dbl_b/down 3edae9fead7aa9d0 +eq_band_dbl_b/up 73a19cc26e74916b +eq_band_dbl_b/settle 68510ab880c09024 +eq_type_icon/move 4d4ed4aa858101fb +eq_type_icon/down bf54fa8c52e7c494 +eq_type_icon/up 5c812e80370cd009 +eq_type_icon/settle e04092445691d705 +eq_type_icon2/move a2faff345afb5de5 +eq_type_icon2/down 37a8ff52d85c8bec +eq_type_icon2/up d79d3533525f88a8 +eq_type_icon2/settle c4b1ed248806d5ec +eq_freq_cell/move 9c75b8e365f24a07 +eq_freq_cell/down abce296a1e30e4dd +eq_freq_cell/drag1 bcf5521f56e0b23c +eq_freq_cell/drag2 146d4fcb536ce13d +eq_freq_cell/drag3 1ca7e625b4dfa566 +eq_freq_cell/drag4 8a80b2f763d7f1be +eq_freq_cell/up 92ed2cac05e75d6b +eq_freq_cell/settle 0066372319f8f816 +eq_gain_cell/move c4e50b858c3856ae +eq_gain_cell/down d111201d97a1bcee +eq_gain_cell/drag1 4805c6a40bc2a6b1 +eq_gain_cell/drag2 d04ae18407ec48aa +eq_gain_cell/drag3 102cb9f358c73517 +eq_gain_cell/drag4 48078541bc724bb1 +eq_gain_cell/up bd1f71d7441df72b +eq_gain_cell/settle 7dc2f7aa43c78a83 +eq_tilt_cell/move 9c539c63eddb3594 +eq_tilt_cell/down 1b112ac91259b224 +eq_tilt_cell/drag1 9f8a9b58e09ae2a4 +eq_tilt_cell/drag2 39738b40e8fa4a07 +eq_tilt_cell/drag3 2a75abfcf532aa25 +eq_tilt_cell/drag4 b2f6bc469ab47fca +eq_tilt_cell/up 4f345eb435e563dc +eq_tilt_cell/settle 4e81727ad5535387 +eq_stage_toggle/move 5b1d4329b0a66ec0 +eq_stage_toggle/down ea8062df24e69279 +eq_stage_toggle/up 717bc5d362862b59 +eq_stage_toggle/settle 2463339d004342ed +eq_stage_idle0 e2267e282268cbc2 +eq_stage_idle1 6852077567535593 +eq_stage_idle2 b87d8c40e1d8fefa +eq_stage_toggle2/move a0c38bceee9587af +eq_stage_toggle2/down 46179ae2865ca8f4 +eq_stage_toggle2/up 2ef7da627d39c817 +eq_stage_toggle2/settle 08f20521d42e92f0 +eq_module_byp/move f0131534ec347b34 +eq_module_byp/down 0b3eaf94cc40f03d +eq_module_byp/up bfa630d5f4d535da +eq_module_byp/settle a624d3401735ad33 +eq_byp_idle0 211e5594d0845477 +eq_byp_idle1 acb0312398c2d20a +eq_module_byp_off/move e3040743f43de391 +eq_module_byp_off/down 8ff5e1466e235418 +eq_module_byp_off/up 45e1faa70128ffdf +eq_module_byp_off/settle 23f254350792bff1 +eq_off/move 6c305a2cc76514f7 +eq_off/down 96b48b2626a6ea73 +eq_off/up 23e761d838c14f52 +eq_off/settle 957ce38a51da6c59 +preset_next/move 84a50b6a5e2ab8b0 +preset_next/down ef71fc1f4989762d +preset_next/up 58a45d559a51555e +preset_next/settle ad7551d47e936a73 +preset_next_idle0 f538164ba2de5384 +preset_next_idle1 67c1deda7dfcb8d3 +preset_next_idle2 1ee7194ecbb5efeb +preset_next2/move bf8b7ffce8e4c7eb +preset_next2/down c6eb2d330d886eb1 +preset_next2/up e3f4dacb6bba5afe +preset_next2/settle 2c87066915e93b27 +preset_prev/move 1217fc51b32324d4 +preset_prev/down fd9db333c4826d08 +preset_prev/up 3ce4b4f55d13cd62 +preset_prev/settle 570808d8c27dd8aa +preset_idle0 20a59776a1e5da1d +preset_idle1 ebdd3df990ffa57c +preset_idle2 b1d395d3682a94e1 +preset_idle3 e5eb6e0fa5de96d7 +preset_idle4 ca35275f351225d5 +preset_idle5 f8bdb30ee12463b1 +preset_idle6 84618175dc8734ff +preset_idle7 8fb05fa1fefdd791 +logo_single/move cda3e7891719d987 +logo_single/down 2a42700be6029b7e +logo_single/up fca08a4d0ea52a6e +logo_single/settle bb1ef63560bb8398 +logo_single_wait0 5bc196ed43d7cf49 +logo_single_wait1 e153ee0f6234b4f8 +logo_single_wait2 65333fdaaa0db58a +logo_single_wait3 d4642d8dc3692026 +logo_single_wait4 ebd3c4b72e9f8509 +logo_single_wait5 02cd8b5476ccecc8 +logo_single_wait6 49494b229cc3bc6b +logo_single_wait7 2f28fbf01932f386 +logo_menu/move 8cb8425aaa900851 +logo_menu/down 48b011b794e0b0e0 +logo_menu/up 747772114b035053 +logo_menu/settle aebd726ec8b8ff0f +logo_menu_idle0 7b9b771adf51b808 +logo_menu_idle1 d33979d76c6169a0 +logo_menu_pick/move 5823a782a6e023fc +logo_menu_pick/down 349feeae242b539e +logo_menu_pick/up 0df45e57f0fe771e +logo_menu_pick/settle e66ce09e12f187e8 +logo_dbl_a/move 936ce49997f8b10d +logo_dbl_a/down 3f7868703a37d27e +logo_dbl_a/up ff3bd3824a5aaa3b +logo_dbl_a/settle 81db76c9215efb40 +logo_dbl_b/move e8388d6dfd135de0 +logo_dbl_b/down 09aba992bddc62ea +logo_dbl_b/up 3f2e4f3fae519841 +logo_dbl_b/settle 5c38fd4bfc22559b +light_idle0 79fa0e3171b89825 +light_idle1 8d0e5d8821dd4315 +light_idle2 6a8fcf7768095f60 +logo_dbl2_a/move 62d7aed4fdf95a0f +logo_dbl2_a/down e97c35d7829bad0a +logo_dbl2_a/up 4ad290d411fa87c8 +logo_dbl2_a/settle 18031bd440de3c98 +logo_dbl2_b/move aa41183a29c67e2b +logo_dbl2_b/down 95265dcf486d8633 +logo_dbl2_b/up 4e1a2500a3950f12 +logo_dbl2_b/settle 432774958848ba9d +about_open/move 9d891cbea63b370a +about_open/down ef576aed6df415fc +about_open/up c6552ed441cc2c17 +about_open/settle a567e18a1e8e2b7e +about_idle0 5a23309ceb193de6 +about_idle1 0b548020d672c647 +about_idle2 b94563d273c97d21 +about_scroll/move 9cf629e3fea79704 +about_scroll/wheel 11796e2677b5150d +about_scroll/settle 721892f5c1140265 +about_scroll2/move 194101fc4404458b +about_scroll2/wheel 4e189b60ca89c68e +about_scroll2/settle 752ecfc75d06fa22 +about_tab_appearance/move d7cdea9a60d69521 +about_tab_appearance/down ef3b616f36844571 +about_tab_appearance/up 28bfea7a2bc99316 +about_tab_appearance/settle 8ae3714dfa2367c5 +appearance_idle0 41cf2891a0791e01 +appearance_idle1 2409fb0b47cb9c42 +appearance_scroll/move 91f7d4df8e3c01b3 +appearance_scroll/wheel 88371b1de074cd32 +appearance_scroll/settle c5460fc3613caa9b +appearance_scheme_pick/move d9eb24fa66705b61 +appearance_scheme_pick/down a59a8d3e5b0dc962 +appearance_scheme_pick/up e9e9429a6ea3cf59 +appearance_scheme_pick/settle a34afd56acf18feb +appearance_font_pick/move 857ee7656a13bd43 +appearance_font_pick/down 3f3312351a76ba5f +appearance_font_pick/up 44af8250a0a41836 +appearance_font_pick/settle 47b8b19b6037b8b9 +appearance_font_pick2/move 84ce3684d2418b23 +appearance_font_pick2/down c315994c0328bcb0 +appearance_font_pick2/up 4f734fc2e50824a4 +appearance_font_pick2/settle d2bbfc4a91844991 +about_tab_changelog/move 03c644fce553013c +about_tab_changelog/down c847002342b35e6a +about_tab_changelog/up 4c6ac187883acf71 +about_tab_changelog/settle 6b4a9150737578e9 +changelog_idle0 083b26711686a1e8 +changelog_idle1 d425b52321ab9877 +changelog_scroll/move c719195d319f2933 +changelog_scroll/wheel b0bb40acff575c74 +changelog_scroll/settle 7554892c0a2f22da +changelog_thumb/move a0276b8ffe814438 +changelog_thumb/down a40c3d63020b5c16 +changelog_thumb/drag1 4ff41d7b80b214ba +changelog_thumb/drag2 973d8580ef029fb4 +changelog_thumb/drag3 27654ccc9307c503 +changelog_thumb/drag4 85df1510831d3a23 +changelog_thumb/up b84ce0dd1a8eed2a +changelog_thumb/settle e8d89d34aa27a004 +about_tab_about/move 0e389fe2ca03a0d4 +about_tab_about/down a48557010b055e9a +about_tab_about/up edc1d54fb0d6136c +about_tab_about/settle a1433b828f6a72d8 +about_close/move 49fcde77be8a102d +about_close/down c4f19dd7f7e9aa5c +about_close/up 55f360edbc2eb152 +about_close/settle 88433993653b474d +closed_idle0 8104cd68e5c09134 +closed_idle1 1a96f990331b825f +closed_idle2 1b4e6b2718104d9f +scale_menu_open/move 8004438c6b6f8a8d +scale_menu_open/down db38716f7aaa2ae9 +scale_menu_open/up 532e1a2fd823f35f +scale_menu_open/settle dcc11b8738ec3707 +scale_menu_idle0 791a7dbabab08b8a +scale_menu_idle1 29567702f70f4972 +scale_menu_close/move c4eefbd594f215a2 +scale_menu_close/down 449106715b45c435 +scale_menu_close/up f21b2bd9dca7d5b7 +scale_menu_close/settle 9d833dda3b63a2ba +hidpi:hidpi_boot0 5d5411fe00c74e86 +hidpi:hidpi_boot1 09008c00a6b1ac67 +hidpi:hidpi_boot2 bf627c0231188d0e +hidpi:hidpi_boot3 e1c0d681eccca32a +hidpi:hidpi_drive/move d802e7fe84a16d47 +hidpi:hidpi_drive/down 6591f8b0d59f03c3 +hidpi:hidpi_drive/drag1 054ed1f2a2fc0ecd +hidpi:hidpi_drive/drag2 649fea688a79fd8c +hidpi:hidpi_drive/drag3 2ec7cfd68e82fbf7 +hidpi:hidpi_drive/drag4 32a9a64e741e513a +hidpi:hidpi_drive/up b3bca8f35ed66786 +hidpi:hidpi_drive/settle 260f50e753af7d68 +hidpi:hidpi_eq_on/move 5cc6478c1b74621c +hidpi:hidpi_eq_on/down b84417d13b59f8c3 +hidpi:hidpi_eq_on/up 242b011574cc3f6e +hidpi:hidpi_eq_on/settle 86450106adda4e2f +hidpi:hidpi_idle0 3e65ce84fefae0fe +hidpi:hidpi_idle1 5441f124acb7955d +hidpi:hidpi_idle2 0ddc2df1a9d9bf78 diff --git a/rust/satcomp-plugin/src/gui/mod.rs b/rust/satcomp-plugin/src/gui/mod.rs index b620fb1..1b20797 100644 --- a/rust/satcomp-plugin/src/gui/mod.rs +++ b/rust/satcomp-plugin/src/gui/mod.rs @@ -1,84 +1,81 @@ -mod canvas; mod ui; +#[cfg(test)] +mod golden; use crate::params::SatCompParams; use crate::Shared; -use canvas::{font_family, Canvas, H, W}; +use satcomp_ui::canvas::{Canvas, FONT_NAMES, H, W}; +use satcomp_ui::init_ctx; use nih_plug::prelude::Editor; -use nih_plug_egui::egui::{self, FontData, FontDefinitions, LayerId}; +use nih_plug_egui::egui::{self, LayerId}; use nih_plug_egui::create_egui_editor; use std::sync::Arc; use std::time::Duration; use ui::{Env, Gui, State}; +/// One editor frame: map the egui input into logical canvas units, draw the whole UI. +pub(crate) fn run_frame( + ctx: &egui::Context, + setter: &nih_plug::prelude::ParamSetter, + st: &mut State, + params: &SatCompParams, + shared: &Shared, +) { + let screen = ctx.screen_rect(); + let s = ((screen.width() / W).min(screen.height() / H) * 4.0).floor() / 4.0; + let s = s.max(0.5); + let ox = ((screen.width() - W * s) * 0.5).floor(); + let oy = ((screen.height() - H * s) * 0.5).floor(); + let ppp = ctx.pixels_per_point(); + let (pos, down, rdown, scroll, shift, now) = ctx.input(|i| { + ( + i.pointer.latest_pos(), + i.pointer.primary_down(), + i.pointer.secondary_down(), + i.raw_scroll_delta.y, + i.modifiers.shift, + i.time, + ) + }); + let (mx, my) = match pos { + Some(p) => ((p.x - ox) / s, (p.y - oy) / s), + None => (-1000.0, -1000.0), + }; + st.set_input(mx, my, down, rdown, scroll, shift, now); + st.ptr_pt = pos.map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0)); + st.win_pt = (screen.width(), screen.height()); + + let painter = ctx.layer_painter(LayerId::background()); + let cv = Canvas::new(&painter, ppp, ox, oy, s, st.colors(), st.face); + painter.rect_filled(screen, 0.0, cv.bg_color()); + // Theme editor: the whole window is a static INIT page (default params, constant meter values); the real + // params and shared state are not touched. + let (dp, ds) = (st.dummy_params.clone(), st.dummy_shared.clone()); + let editing = st.app.editing(); + if editing { + st.fill_dummy(); + } + let (pr, sr): (&SatCompParams, &Shared) = if editing { (&*dp, &*ds) } else { (params, shared) }; + let env = Env { params: pr, setter, shared: sr, dsp: pr.to_dsp() }; + let mut g = Gui { s: st, cv, env }; + g.frame(); + ctx.request_repaint_after(Duration::from_millis(16)); + let _ = egui::Id::NULL; +} + pub fn create(params: Arc, shared: Arc) -> Option> { let (pal, light) = ui::initial_palette(¶ms); - let face = params.font.load(std::sync::atomic::Ordering::Relaxed).clamp(0, canvas::FONT_NAMES.len() as i32 - 1) as usize; + let face = params.font.load(std::sync::atomic::Ordering::Relaxed).clamp(0, FONT_NAMES.len() as i32 - 1) as usize; let state = State::new(pal, light, face, ¶ms); let editor_state = params.editor_state.clone(); + let look_params = params.clone(); create_egui_editor( editor_state, state, - |ctx, _| { - let mut fonts = FontDefinitions::default(); - let faces: [&'static [u8]; 6] = [ - include_bytes!("../../assets/fonts/FiraCode-Regular.ttf"), - include_bytes!("../../assets/fonts/JetBrainsMono-Regular.ttf"), - include_bytes!("../../assets/fonts/GeistMono-Regular.ttf"), - include_bytes!("../../assets/fonts/RobotoMono-Regular.ttf"), - include_bytes!("../../assets/fonts/OxygenMono-Regular.ttf"), - include_bytes!("../../assets/fonts/Doto-Black.ttf"), - ]; - for (i, bytes) in faces.iter().enumerate() { - fonts.font_data.insert(format!("f{i}"), Arc::new(FontData::from_static(bytes))); - fonts.families.insert(font_family(i), vec![format!("f{i}")]); - } - ctx.set_fonts(fonts); - ctx.tessellation_options_mut(|o| o.feathering = false); - ctx.style_mut(|s| s.animation_time = 0.0); - }, - move |ctx, setter, st| { - let screen = ctx.screen_rect(); - let s = ((screen.width() / W).min(screen.height() / H) * 4.0).floor() / 4.0; - let s = s.max(0.5); - let ox = ((screen.width() - W * s) * 0.5).floor(); - let oy = ((screen.height() - H * s) * 0.5).floor(); - let ppp = ctx.pixels_per_point(); - let (pos, down, rdown, scroll, shift, now) = ctx.input(|i| { - ( - i.pointer.latest_pos(), - i.pointer.primary_down(), - i.pointer.secondary_down(), - i.raw_scroll_delta.y, - i.modifiers.shift, - i.time, - ) - }); - let (mx, my) = match pos { - Some(p) => ((p.x - ox) / s, (p.y - oy) / s), - None => (-1000.0, -1000.0), - }; - st.set_input(mx, my, down, rdown, scroll, shift, now); - st.ptr_pt = pos.map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0)); - st.win_pt = (screen.width(), screen.height()); - - let painter = ctx.layer_painter(LayerId::background()); - let cv = Canvas::new(&painter, ppp, ox, oy, s, st.colors(), st.face); - painter.rect_filled(screen, 0.0, cv.bg_color()); - // Theme editor: the whole window is a static INIT page (default params, constant meter values); the real - // params and shared state are not touched. - let (dp, ds) = (st.dummy_params.clone(), st.dummy_shared.clone()); - let editing = st.edit.is_some(); - if editing { - st.fill_dummy(); - } - let (pr, sr): (&crate::params::SatCompParams, &crate::Shared) = - if editing { (&*dp, &*ds) } else { (&*params, &*shared) }; - let env = Env { params: pr, setter, shared: sr, dsp: pr.to_dsp() }; - let mut g = Gui { s: st, cv, env }; - g.frame(); - ctx.request_repaint_after(Duration::from_millis(16)); - let _ = egui::Id::NULL; + move |ctx, st| { + init_ctx(ctx); + st.sync_look(&look_params); }, + move |ctx, setter, st| run_frame(ctx, setter, st, ¶ms, &shared), ) } diff --git a/rust/satcomp-plugin/src/gui/ui.rs b/rust/satcomp-plugin/src/gui/ui.rs index 89ea1a4..2731922 100644 --- a/rust/satcomp-plugin/src/gui/ui.rs +++ b/rust/satcomp-plugin/src/gui/ui.rs @@ -1,8 +1,10 @@ //! Port of the JSFX `@gfx` section: widget kit (cell, btn, selector, ...), the sat / comp / EQ viewports, //! meters and the main layout. Immediate mode with the same `act` / `press` drag logic as the JSFX. -use super::canvas::{Canvas, FONT_NAMES, PALETTES}; -use theme::{ThemeEdit, UserTheme}; +use satcomp_ui::canvas::Canvas; +use satcomp_ui::fft::fft; +use satcomp_ui::kit::{Kit, Meta, Widgets}; +use satcomp_ui::appearance::{self, AppState, AppearanceUi, CellGrid, Rect}; use crate::params::{SatCompParams, TABLE}; use crate::presets::{self, Preset}; use crate::Shared; @@ -15,25 +17,6 @@ use std::ops::{Deref, DerefMut}; use std::sync::atomic::Ordering; use std::sync::Arc; -#[derive(Clone, Copy, Default)] -pub struct Meta { - pub min: f32, - pub max: f32, - pub def: f32, - /// 0 linear, 1 log, 2 sqrt - pub mode: u8, - /// bit 0: snap to min near the start of travel, bit 1: snap to max near the end - pub snap: u8, - pub step: f32, -} - -/// One line of the scrolling About / Changelog text. Head = version title (+ rule), takes the next Pad row too. -enum Row { - Text(f32, String), - Head(String), - Pad, -} - enum MenuKind { Shape, Palette, @@ -49,6 +32,8 @@ struct MItem { id: i32, } +/// ASYM slider drag (viewport-style act id: released with the mouse) +const ACT_ASYM: i32 = 145; const MENU_ROWS: usize = 18; const MENU_ROW_H: f32 = 14.0; @@ -73,56 +58,38 @@ pub enum Dlg { } mod scope; -mod theme; pub struct State { + /// widget interaction state (satcomp-ui); `State` derefs to it + pub kit: Kit, /// packed scope settings (see scope.rs) scope_cfg: i32, + /// steady scope scrolling: eased read position (bucket index) and the time of the last frame + scope_pos: f64, + scope_t: f64, /// scope viewport drag start: (mouse x, mouse y, window step, ceiling step) scope_drag: (f32, f32, usize, usize), - pub themes: Vec, - pub edit: Option, + /// ASYM drag anchor: (mouse y, value 0..1) at the press + asym_drag: (f32, f32), + /// colour themes, theme editor and About-page state (satcomp-ui) + pub app: AppState, pub dummy_params: Arc, pub dummy_shared: Arc, - real_in: (bool, bool, bool, i32, f32, f32), - del_arm: f64, - meta: [Meta; 68], - touched: [bool; 68], pub pal: usize, pub light: bool, /// UI font index (FONT_NAMES) pub face: usize, - /// first visible scheme row in the Appearance list - ap_scroll: usize, - /// first visible row of the About / Changelog text box - about_scroll: usize, /// time of a logo click waiting out the double-click window (then it cycles the colour scheme) logo_pend: f64, // interaction - act: i32, - act_t: f32, - last_my: f32, - last_clk_n: i32, - last_clk_t: f64, vt1: usize, vt2: usize, gdx: f32, gdy: f32, tacc: f32, tlast: f32, - last_down: bool, - last_rdown: bool, - wacc: f32, menu: Option, // per-frame input (logical units) - mx: f32, - my: f32, - down: bool, - press: bool, - rpress: bool, - wheel: i32, - shift: bool, - now: f64, // meters gr_disp: f32, gr_hold: f32, @@ -136,14 +103,19 @@ pub struct State { hl_r_t: f64, opk_max: f32, clip_lat: bool, + /// post-saturator level meter: decaying level and the last time it clipped (accent, held 1 s) + sat_lv: f32, + sat_clip_t: f64, + /// limiter gain reduction (dB): decaying display value + lim_disp: f32, // readouts (refresh ~8x/s) rd_last: f64, rd_tick: bool, rd_gr: f32, + rd_lim: f32, rd_pk: f32, rd_rms: f32, rd_diff: f32, - rd_bg: f32, rd_lk: f32, rd_mt: f32, rd_sat: f32, @@ -170,10 +142,11 @@ pub struct State { lut: ShaperLut, /// custom-curve draw mode (pencil) and the point being dragged curve_edit: bool, + /// draw view tool: true = symmetry (odd curve), false = free draw + sym_mode: bool, /// shape was observed as Custom since the draw view opened (host writes land a frame or more later) edit_seen: bool, cpt: usize, - dk: f32, // window resize grip resizing: bool, resize_off: (f32, f32), @@ -187,8 +160,6 @@ pub struct State { pending: u8, /// result slot of a file dialog running on a worker thread (never block the UI/host thread in a modal) dlg: Option>>, - /// About page: 0 closed, 1 about, 2 changelog, 3 appearance - about: u8, /// preset the edit marker compares against (cached by name), and the post-load settle time base: Option<(String, Preset)>, hold_until: f64, @@ -197,37 +168,23 @@ pub struct State { impl State { /// Per-frame input snapshot (positions in logical canvas units). Computes press edges like the JSFX. pub fn set_input(&mut self, mx: f32, my: f32, down: bool, rdown: bool, scroll: f32, shift: bool, now: f64) { - self.mx = mx; - self.my = my; - self.down = down; - self.press = down && !self.last_down; - self.last_down = down; - self.rpress = rdown && !self.last_rdown; - self.last_rdown = rdown; - self.shift = shift; // The egui clock restarts from 0 whenever the editor window is reopened, but this State lives on. Re-base every // stored timestamp, otherwise `now - last` stays negative and the ~8 Hz readouts (PK, RMS, GR) stay frozen. - if now < self.now { + if self.kit.set_input(mx, my, down, rdown, scroll, shift, now) { self.rd_last = now; + self.scope_t = now; self.hl_l_t = now; self.hl_r_t = now; self.gr_hold_t = now; - self.last_clk_t = now; + self.sat_clip_t = -10.0; self.hold_until = now; self.spec_t = now; } - self.now = now; - // notch the scroll: a mouse wheel reports big steps, a trackpad many small ones - self.wacc += scroll; - self.wheel = 0; - if self.wacc.abs() >= 10.0 { - self.wheel = if self.wacc > 0.0 { 1 } else { -1 }; - self.wacc = 0.0; - } } pub fn new(pal: usize, light: bool, face: usize, params: &SatCompParams) -> Self { - let mut meta = [Meta::default(); 68]; + let mut kit = Kit::new(69); + let meta = &mut kit.meta; for &(n, _, mn, mx, df) in TABLE { meta[n] = Meta { min: mn, max: mx, def: df, mode: 0, snap: 0, step: 1.0 }; } @@ -277,45 +234,26 @@ impl State { } let fwin = (0..4096).map(|i| 0.5 - 0.5 * (2.0 * std::f32::consts::PI * i as f32 / 4096.0).cos()).collect(); let mut st = Self { - meta, - touched: [false; 68], + kit, pal, light, face, scope_cfg: params.scope.load(Ordering::Relaxed), + scope_pos: 0.0, + scope_t: 0.0, scope_drag: (0.0, 0.0, 0, 0), - themes: theme::load_themes(), - edit: None, - dummy_params: Arc::new(SatCompParams::default()), + asym_drag: (0.0, 0.0), + app: AppState::new(), + dummy_params: Arc::new(SatCompParams::from_defaults(None)), dummy_shared: Arc::new(Shared::new()), - real_in: (false, false, false, 0, -1000.0, -1000.0), - del_arm: -10.0, - ap_scroll: 0, - about_scroll: 0, logo_pend: -1.0, - act: 0, - act_t: 0.0, - last_my: 0.0, - last_clk_n: 0, - last_clk_t: 0.0, vt1: 0, vt2: 0, gdx: 0.0, gdy: 0.0, tacc: 0.0, tlast: 0.0, - last_down: false, - last_rdown: false, - wacc: 0.0, menu: None, - mx: -1000.0, - my: -1000.0, - down: false, - press: false, - rpress: false, - wheel: 0, - shift: false, - now: 0.0, gr_disp: 0.0, gr_hold: 0.0, gr_hold_t: 0.0, @@ -328,13 +266,16 @@ impl State { hl_r_t: 0.0, opk_max: 0.0, clip_lat: false, + sat_lv: 0.0, + sat_clip_t: -10.0, + lim_disp: 0.0, rd_last: 0.0, rd_tick: false, rd_gr: 0.0, + rd_lim: 0.0, rd_pk: 0.0, rd_rms: 0.0, rd_diff: 0.0, - rd_bg: 1.0, rd_lk: 0.0, rd_mt: 0.0, rd_sat: 0.0, @@ -358,9 +299,9 @@ impl State { fwin, lut: ShaperLut::new(0), curve_edit: false, + sym_mode: true, edit_seen: false, cpt: 0, - dk: 1.0, resizing: false, resize_off: (0.0, 0.0), ptr_pt: (0.0, 0.0), @@ -369,7 +310,6 @@ impl State { user: presets::scan_user(), pending: 0, dlg: None, - about: 0, base: None, hold_until: 0.0, }; @@ -378,6 +318,62 @@ impl State { } } +impl State { + /// Colours the canvas draws with: the editor preview while editing, else the active scheme. + pub fn colors(&self) -> [f32; 9] { + self.app.colors(self.pal, self.light) + } + + /// nih-plug builds the editor (and so this state) when the plug-in is created, BEFORE the host restores the project's + /// saved parameters. Re-read the saved look every time the window opens, otherwise a project reopens on the defaults. + pub fn sync_look(&mut self, params: &SatCompParams) { + let (pal, light) = initial_palette(params); + self.pal = pal; + self.light = light; + self.face = (params.font.load(Ordering::Relaxed).max(0) as usize).min(satcomp_ui::canvas::FONT_NAMES.len() - 1); + self.scope_cfg = params.scope.load(Ordering::Relaxed); + self.restore_custom(params); + } + + /// A project that used a user theme: resolve it from the themes file or the project copy. + pub fn restore_custom(&mut self, params: &SatCompParams) { + let pal = self.app.restore_custom(self.pal, ¶ms.custom_theme.lock()); + if pal != self.pal || pal >= satcomp_ui::canvas::PALETTES.len() { + self.pal = pal; + params.palette_v2.store(pal as i32, Ordering::Relaxed); + } + } + + /// Constant meter / readout values for the dummy page (set every frame, the draw code then settles on them). + pub fn fill_dummy(&self) { + let d = &self.dummy_shared; + d.gr_pk.store(3.5, Ordering::Relaxed); + d.opk[0].store(1.0, Ordering::Relaxed); + d.opk[1].store(0.5, Ordering::Relaxed); + d.clip.store(true, Ordering::Relaxed); + d.vz_lv.store(0.3, Ordering::Relaxed); + d.mn_lv.store(0.5, Ordering::Relaxed); + d.fms.store(0.05, Ordering::Relaxed); + d.diff_disp.store(2.0, Ordering::Relaxed); + d.sat_db.store(2.0, Ordering::Relaxed); + d.sat_vz.store(0.3, Ordering::Relaxed); + d.sat_pk.store(0.4, Ordering::Relaxed); + d.lim_gr_pk.store(1.5, Ordering::Relaxed); + } +} + +impl Deref for State { + type Target = Kit; + fn deref(&self) -> &Kit { + &self.kit + } +} +impl DerefMut for State { + fn deref_mut(&mut self) -> &mut Kit { + &mut self.kit + } +} + pub struct Env<'a> { pub params: &'a SatCompParams, pub setter: &'a ParamSetter<'a>, @@ -391,6 +387,100 @@ pub struct Gui<'a> { pub env: Env<'a>, } +impl<'a> Widgets<'a> for Gui<'a> { + fn kit(&mut self) -> &mut Kit { + &mut self.s.kit + } + fn kit_ref(&self) -> &Kit { + &self.s.kit + } + fn cv(&mut self) -> &mut Canvas<'a> { + &mut self.cv + } + fn param_ptr(&self, n: usize) -> Option { + self.env.params.ptr(n) + } + fn host(&self) -> &dyn GuiContext { + self.env.setter.raw_context + } + fn masked(&self) -> bool { + self.s.app.edit.is_some() + } + fn fmt(&self, n: usize, v: f32) -> String { + self.fmt_slot(n, v) + } +} + +impl<'a> AppearanceUi<'a> for Gui<'a> { + fn app(&mut self) -> &mut AppState { + &mut self.s.app + } + fn app_ref(&self) -> &AppState { + &self.s.app + } + fn pal(&self) -> usize { + self.s.pal + } + fn light(&self) -> bool { + self.s.light + } + fn face(&self) -> usize { + self.s.face + } + fn commit_scheme(&mut self, pal: usize, encoded: String) { + self.s.pal = pal; + self.env.params.palette_v2.store(pal as i32, Ordering::Relaxed); + // a user theme is also stored in the project, so it survives a machine without the themes file + *self.env.params.custom_theme.lock() = encoded; + self.apply_pal(); + } + fn commit_light(&mut self, light: bool) { + self.s.light = light; + self.env.params.light.store(light, Ordering::Relaxed); + self.apply_pal(); + } + fn plugin_key(&self) -> &'static str { + "satcomp" + } + fn presets_dir(&self) -> Option { + crate::presets::user_dir() + } + fn scale_now(&self) -> f32 { + self.cur_scale() + } + fn set_scale(&mut self, scale: f32) { + self.request_scale(scale); + } + fn factory_scale(&self) -> f32 { + 1.25 + } + fn commit_face(&mut self, face: usize) { + self.s.face = face; + self.env.params.font.store(face as i32, Ordering::Relaxed); + self.cv.face = face; + } + fn about_paras(&self) -> &'static [&'static [&'static str]] { + ABOUT_TEXT + } + fn changelog(&self) -> &'static [(&'static str, &'static [&'static str])] { + CHANGELOG + } + fn manual_pdf(&self) -> Option<(&'static str, &'static [u8])> { + // the file must exist for the crate's current version (docs/manual/build.py), or the plug-in does not compile + Some(( + concat!("SatComp-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf"), + include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/manual/SatComp-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf")), + )) + } + fn draw_flow(&mut self, r: Rect, byp: bool) { + self.draw_flow_at(r.x, r.y, r.w, r.h, byp); + } + fn about_scroll_drag_start(&mut self) { + self.vt1 = 0; + self.vt2 = 0; + } +} + impl<'a> Deref for Gui<'a> { type Target = State; fn deref(&self) -> &State { @@ -406,13 +496,14 @@ impl<'a> DerefMut for Gui<'a> { /// About page copy (docs/abouttextcopy.md). Each inner slice is one paragraph, each string one source line. const ABOUT_TEXT: &[&[&str]] = &[ &["A waveshaping saturator with compressor and 2-stage 3-band EQ", "Made with bricking intentions (:"], - &["Use saturator module to give compressor more spice to squash.", "Left-click top-right pencil icon to enter custom draw mode."], - &["Refine tone with pre/post-compressor 3-band EQ, then dial in the desired gain in the output module."], - &["Double-click slider to reset parameter to its default value", "Left/Right-click top-left icon for more color ways", "Double-click top-left icon to switch between dark and light mode"], + &["Use the saturator module to give the compressor more spice to squash.", "[Click] the top-right pencil icon to enter custom draw mode.", "[Click] the lower-right SAT value to auto-match the gain."], + &["Refine tone with the pre/post-compressor 3-band EQ, then dial in the desired gain in the output module."], + &["[Double-click] slider resets the parameter to its default value", "[Click] GR meter cycles its range", "[Click] clip meter resets the readout", "[Left/Right-click] top-left icon cycles the colour theme", "[Double-click] top-left icon switches between dark and light mode"], ]; /// Changelog, newest first. Keep each entry to two short sentences or fewer. const CHANGELOG: &[(&str, &[&str])] = &[ + ("v0.5.2", &["BYPASS is now a plain bypass: the dry input comes back at its own level, no longer scaled to the processed loudness (which could peak up to +10 dB with a hot saturator), and the BYP readout is gone.", "New output limiter: a true-peak brickwall at -0.2 dBTP, on by default (LIM button). Its gain reduction shows in the LIM readout, and it adds about 2 ms of latency that is always reported to the host.", "New thin level meter after the saturator that turns accent when it clips. The compressor GR number now sits at the top of the GR meter.", "The signal flow shows the limiter. INIT now starts with drive 0 and threshold 0.", "Better saturator: the even-order part of the waveshaper no longer drags DC and sub-bass pulses into the signal, so lopsided shapers and custom curves keep their grit with far calmer peaks. New ASYM slider under the plot sets how much of the even part each shaper keeps (stored per shaper, saved with presets).", "INIT sounds slightly cleaner in the lows with Tube, Diode, Rectify, Asym Fold and Custom.", "The saturator's OUT GAIN cell is now called SAT GAIN (same parameter)."]), ("v0.5.1", &["Fixed a loud thump when the plug-in is enabled or the window regains focus.", "New Appearance tab under About: colour mode, a scheme list with swatches, six fonts and a custom theme editor with a colour picker.", "New waveform scope (transient meter): click the icon in the compressor plot corner for a half or full wave view with the gain reduction stacked in the accent colour. Drag the view to change the window and ceiling (+2 dB to -14 dB).", "Sulfur and Matcha were replaced by Genesis and Suika.", "The oversampling OFF button now reads x1."]), ("v0.5", &["Added a sidechain input with key gain, HP, LP, a solo monitor and KEY MIX.", "Every colour scheme now has a light mode: double-click the icon or use the scheme menu.", "LP filters now reach down to 200 Hz."]), ("v0.4.1", &["Fixed the PK readout and peak reset after reopening the window."]), @@ -443,156 +534,31 @@ pub fn initial_palette(p: &crate::params::SatCompParams) -> (usize, bool) { } fn version_short() -> String { + if cfg!(test) { + return "TEST".into(); // keeps the UI golden independent of release version bumps + } let v = env!("CARGO_PKG_VERSION"); v.strip_suffix(".0").unwrap_or(v).to_string() } -fn blink(t: f64) -> bool { - ((t * 4.0).floor() as i64) & 1 == 1 -} +use appearance::blink; impl<'a> Gui<'a> { - // ------------------------------------------------------------------ params (slider-number addressing) - fn sget(&self, n: usize) -> f32 { - match self.env.params.ptr(n) { - Some(p) => { - let m = &self.meta[n]; - m.min + (m.max - m.min) * unsafe { p.unmodulated_normalized_value() } - } - None => 0.0, - } - } - - fn sset(&mut self, n: usize, v: f32) { - if self.edit.is_some() { - return; // theme editor page: dummy widgets never write parameters - } - if let Some(p) = self.env.params.ptr(n) { - let m = self.meta[n]; - let norm = ((v - m.min) / (m.max - m.min)).clamp(0.0, 1.0); - unsafe { - if !self.touched[n] { - self.env.setter.raw_context.raw_begin_set_parameter(p); - self.touched[n] = true; - } - self.env.setter.raw_context.raw_set_parameter_normalized(p, norm); - } - } - } - - fn end_touch(&mut self, n: usize) { - if self.edit.is_some() { - return; - } - if n < 68 && self.touched[n] { - if let Some(p) = self.env.params.ptr(n) { - unsafe { self.env.setter.raw_context.raw_end_set_parameter(p) }; - } - self.touched[n] = false; - } - } - - /// set + release in one go (a click, not a drag) - fn click_set(&mut self, n: usize, v: f32) { - self.sset(n, v); - self.end_touch(n); - } - - fn setv(&mut self, n: usize, mut v: f32) { - let m = self.meta[n]; - if m.step > 0.0 { - v = (v / m.step + 0.5).floor() * m.step; - } - v = v.clamp(m.min, m.max); - if v != self.sget(n) { - self.sset(n, v); - } - } - - fn n2t(&self, n: usize, v: f32) -> f32 { - let m = self.meta[n]; - let t = match m.mode { - 1 => (v.max(m.min) / m.min).ln() / (m.max / m.min).ln(), - 2 => ((v - m.min).max(0.0) / (m.max - m.min)).sqrt(), - _ => (v - m.min) / (m.max - m.min), - }; - t.clamp(0.0, 1.0) - } - - fn t2n(&self, n: usize, mut t: f32) -> f32 { - let m = self.meta[n]; - if m.snap & 1 != 0 && t < 0.03 { - t = 0.0; - } - if m.snap & 2 != 0 && t > 0.97 { - t = 1.0; - } - let mut v = match m.mode { - 1 => m.min * (t * (m.max / m.min).ln()).exp(), - 2 => m.min + (m.max - m.min) * t * t, - _ => m.min + (m.max - m.min) * t, - }; - if m.step > 0.0 { - v = (v / m.step + 0.5).floor() * m.step; - } - v.clamp(m.min, m.max) - } - - fn commit(&mut self, n: usize, t: f32) { - let v = self.t2n(n, t); - if v != self.sget(n) { - self.sset(n, v); - } - } - - fn hit(&self, x: f32, y: f32, w: f32, h: f32) -> bool { - self.mx >= x && self.mx < x + w && self.my >= y && self.my < y + h - } - - fn dbl(&mut self, id: i32) -> bool { - let r = self.last_clk_n == id && self.now - self.last_clk_t < 0.35; - self.last_clk_n = if r { 0 } else { id }; - self.last_clk_t = self.now; - r - } - - fn begin_drag(&mut self, n: usize) { - if self.last_clk_n == n as i32 && self.now - self.last_clk_t < 0.35 { - let d = self.meta[n].def; - self.click_set(n, d); - self.act = 0; - self.last_clk_n = 0; - } else { - self.act = n as i32; - self.act_t = self.n2t(n, self.sget(n)); - self.last_my = self.my; - self.last_clk_n = n as i32; - self.last_clk_t = self.now; - } - } - - fn wheel_adj(&mut self, n: usize) { - let t = self.n2t(n, self.sget(n)) + if self.wheel > 0 { 1.0 } else { -1.0 } * if self.shift { 0.005 } else { 0.03 }; - self.commit(n, t.clamp(0.0, 1.0)); - self.end_touch(n); - } - - fn setc(&mut self, red: bool) { - self.cv.dk = self.dk; - self.cv.setc(red); - } - - fn set_dk(&mut self, d: f32) { - self.dk = d; - self.cv.dk = d; + /// Push the active scheme's colours into the canvas. + fn apply_pal(&mut self) { + let a = self.app.scheme_cols(self.pal, self.light); + self.cv.bk = [a[0], a[1], a[2]]; + self.cv.fg = [a[3], a[4], a[5]]; + self.cv.ac = [a[6], a[7], a[8]]; } + // ------------------------------------------------------------------ params (slider-number addressing) fn refresh_dsp(&mut self) { self.env.dsp = self.env.params.to_dsp(); } // ------------------------------------------------------------------ formatting - fn fmt(&self, n: usize, v: f32) -> String { + fn fmt_slot(&self, n: usize, v: f32) -> String { if (29..=58).contains(&n) { let o = (n - 29) % 15; return if o < 12 { @@ -684,104 +650,6 @@ impl<'a> Gui<'a> { } // ------------------------------------------------------------------ widgets - fn cell(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str) { - let hv = self.hit(x, y, w, h); - if hv && self.press && self.act == 0 { - self.begin_drag(n); - } - if hv && self.wheel != 0 { - self.wheel_adj(n); - } - let v = self.sget(n); - let t = self.n2t(n, v); - let isact = self.act == n as i32; - self.setc(isact); - self.cv.boxr(x, y, w, h); - self.cv.set_font(1); - self.cv.text(x + 3.0, y + 3.0, lbl); - self.cv.set_font(2); - let s = self.fmt(n, v); - self.cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, &s); - self.cv.fill(x + 2.0, y + h - 4.0, ((t * (w - 4.0)).floor()).max(1.0), 2.0); - } - - /// inverted cell (lit block) for the gain-stage cells - fn cell_o(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str) { - let hv = self.hit(x, y, w, h); - if hv && self.press && self.act == 0 { - self.begin_drag(n); - } - if hv && self.wheel != 0 { - self.wheel_adj(n); - } - let v = self.sget(n); - let t = self.n2t(n, v); - let isact = self.act == n as i32; - self.setc(isact); - self.cv.fill(x, y, w, h); - self.cv.setbg(); - self.cv.set_font(1); - self.cv.text(x + 3.0, y + 3.0, lbl); - self.cv.set_font(2); - let s = self.fmt(n, v); - self.cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, &s); - self.cv.fill(x + 2.0, y + h - 4.0, ((t * (w - 4.0)).floor()).max(1.0), 2.0); - self.setc(false); - } - - /// two stacked params in one cell (label left, value right) - fn cell2(&mut self, na: usize, nb: usize, x: f32, y: f32, w: f32, h: f32, la: &str, lb: &str) { - let hh = (h * 0.5).floor(); - let ha = self.hit(x, y, w, hh); - let hb = self.hit(x, y + hh, w, h - hh); - if ha && self.press && self.act == 0 { - self.begin_drag(na); - } - if hb && self.press && self.act == 0 { - self.begin_drag(nb); - } - if ha && self.wheel != 0 { - self.wheel_adj(na); - } - if hb && self.wheel != 0 { - self.wheel_adj(nb); - } - self.setc(self.act == na as i32 || self.act == nb as i32); - self.cv.boxr(x, y, w, h); - self.setc(false); - self.cv.fill(x, y + hh, w, 1.0); - self.cv.set_font(1); - self.setc(self.act == na as i32); - let s = self.fmt(na, self.sget(na)); - self.cv.text(x + 3.0, y + 3.0, la); - self.cv.textr(x, y + 3.0, w - 3.0, &s); - self.cv.fill(x + 2.0, y + hh - 3.0, ((self.n2t(na, self.sget(na)) * (w - 4.0)).floor()).max(1.0), 1.0); - self.setc(self.act == nb as i32); - let s = self.fmt(nb, self.sget(nb)); - self.cv.text(x + 3.0, y + hh + 3.0, lb); - self.cv.textr(x, y + hh + 3.0, w - 3.0, &s); - self.cv.fill(x + 2.0, y + h - 4.0, ((self.n2t(nb, self.sget(nb)) * (w - 4.0)).floor()).max(1.0), 2.0); - self.setc(false); - } - - /// lit: 0 off, 1 white, 2 red - fn btn(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8) -> bool { - let hv = self.hit(x, y, w, h); - let clicked = hv && self.press && self.act == 0; - if lit > 0 { - self.setc(lit > 1); - self.cv.fill(x, y, w, h); - self.cv.setbg(); - } else { - self.setc(false); - self.cv.boxr(x, y, w, h); - } - self.cv.set_font(1); - self.cv.textc(x, y + ((h - 8.0) * 0.5).floor(), w, s); - self.setc(false); - clicked - } - fn open_menu(&mut self, kind: MenuKind, x: f32, y: f32, items: Vec, checked: usize) { let items = items.into_iter().enumerate().map(|(i, label)| MItem { label, kind: 0, id: i as i32 }).collect(); self.menu = Some(Menu { kind, x, y, items, checked: checked as i32, scroll: 0 }); @@ -869,19 +737,20 @@ impl<'a> Gui<'a> { } if self.logo_pend >= 0.0 && self.now - self.logo_pend >= 0.3 { self.logo_pend = -1.0; - let n = self.n_schemes(); + let n = self.app.n_schemes(); self.set_pal((self.pal + 1) % n); } if hv && self.rpress { self.logo_pend = -1.0; let mut items = vec![MItem { label: format!("MODE: {}", if self.light { "LIGHT" } else { "DARK" }), kind: 0, id: 1000 }]; items.push(MItem { label: String::new(), kind: 2, id: -1 }); - items.extend((0..self.n_schemes()).map(|i| MItem { label: self.scheme_name(i), kind: 0, id: i as i32 })); + items.extend((0..self.app.n_schemes()).map(|i| MItem { label: self.app.scheme_name(i), kind: 0, id: i as i32 })); self.menu = Some(Menu { kind: MenuKind::Palette, x, y: y + 22.0, items, checked: self.pal as i32, scroll: 0 }); } // plug-in icon in a square box: fill = BG, stroke = UI (so light mode inverts it with the scheme) self.setc(false); - if self.light { + // hovering inverts the icon (a plate in the UI colour, or back to the outline in light mode): it is clickable + if self.light != hv { // light mode inverts the icon: UI-coloured plate, BG-coloured glyph self.cv.fill(x - 3.0, y - 3.0, 27.0, 27.0); self.cv.setbg(); @@ -899,57 +768,6 @@ impl<'a> Gui<'a> { l(&self.cv, 14.5, 6.5, 20.5, 0.5); } - fn set_pal(&mut self, p: usize) { - self.pal = p.min(self.n_schemes() - 1); - self.env.params.palette_v2.store(self.pal as i32, Ordering::Relaxed); - // a user theme is also stored in the project, so it survives a machine without the themes file - *self.env.params.custom_theme.lock() = match self.pal.checked_sub(PALETTES.len()) { - Some(i) => theme::encode(&self.themes[i]), - None => String::new(), - }; - self.apply_pal(); - } - - fn set_light(&mut self, light: bool) { - self.light = light; - self.env.params.light.store(light, Ordering::Relaxed); - self.apply_pal(); - } - - fn apply_pal(&mut self) { - let a = self.scheme_cols(self.pal, self.light); - self.cv.bk = [a[0], a[1], a[2]]; - self.cv.fg = [a[3], a[4], a[5]]; - self.cv.ac = [a[6], a[7], a[8]]; - } - - /// module-active square: filled = active, outline = untouched; byp = outlined with an X - fn sqind(&mut self, x: f32, y: f32, s: f32, on: bool, lit: bool, byp: bool) { - if lit { - self.cv.setbg(); - } else { - self.setc(false); - } - if byp { - self.cv.boxr(x, y, s, s); - self.cv.line(x, y, x + s - 1.0, y + s - 1.0); - self.cv.line(x + s - 1.0, y, x, y + s - 1.0); - } else if on { - self.cv.fill(x, y, s, s); - } else { - self.cv.boxr(x, y, s, s); - } - self.setc(false); - } - - fn sq_tog(&mut self, n: usize, x: f32, y: f32, s: f32) { - if self.hit(x - 3.0, y - 3.0, s + 6.0, s + 6.0) && self.press && self.act == 0 { - let v = if self.sget(n) > 0.5 { 0.0 } else { 1.0 }; - self.click_set(n, v); - self.press = false; - } - } - fn diff_box(&mut self, x: f32, y: f32, w: f32, h: f32) { self.setc(false); self.cv.boxr(x, y, w, h); @@ -973,6 +791,8 @@ impl<'a> Gui<'a> { fn draw_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { let g = self.env.shared.gr_pk.swap(0.0, Ordering::Relaxed); self.gr_disp = g.max(self.gr_disp * 0.9); + let lg = self.env.shared.lim_gr_pk.swap(0.0, Ordering::Relaxed); + self.lim_disp = lg.max(self.lim_disp * 0.9); if g >= self.gr_hold { self.gr_hold = g; self.gr_hold_t = self.now; @@ -996,6 +816,13 @@ impl<'a> Gui<'a> { let hp = y + 1.0 + ((h - 3.0) * (self.gr_hold / rg).min(1.0)).floor(); self.cv.fill(x + 1.0, hp, w - 2.0, 1.0); self.cv.set_font(1); + // compressor GR as a number in a window at the top of the bar (positive, like the bar) + self.cv.setbg(); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, 11.0); + self.setc(false); + self.cv.fill(x + 1.0, y + 12.0, w - 2.0, 1.0); + let gs = format!("{:.1}", self.rd_gr); + self.cv.textc(x, y + 3.0, w, &gs); let mj = if rg == 3.0 { 1.0 } else if rg == 6.0 { 2.0 } else if rg == 12.0 { 3.0 } else { 6.0 }; let stp = if rg <= 6.0 { 0.5 } else { 1.0 }; let cnt = (rg / stp) as i32; @@ -1013,6 +840,25 @@ impl<'a> Gui<'a> { } } + /// Thin summed post-saturator level (solid fill, -48..0 dB). The whole meter turns accent while the saturator output + /// is over 0 dBFS, held for 1 s after the last clip. + fn sat_vu(&mut self, x: f32, y: f32, w: f32, h: f32) { + let pk = self.env.shared.sat_pk.swap(0.0, Ordering::Relaxed); + self.sat_lv = pk.max(self.sat_lv * 0.85); + if pk >= 1.0 { + self.sat_clip_t = self.now; + } + let clip = self.now - self.sat_clip_t < 1.0; + let lvf = |v: f32| ((8.6858896 * v.max(0.0000001).ln() + 48.0) / 48.0).clamp(0.0, 1.0); + self.setc(clip); + self.cv.boxr(x, y, w, h); + let lh = ((h - 2.0) * lvf(self.sat_lv)).floor(); + if lh > 0.0 { + self.cv.fill(x + 1.0, y + h - 1.0 - lh, w - 2.0, lh); + } + self.setc(false); + } + fn out_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { let rw = 8.0; let bw = w - rw - 2.0; @@ -1067,6 +913,70 @@ impl<'a> Gui<'a> { } // ------------------------------------------------------------------ sat plot + /// BIAS over ASYM as one stacked group (like HP / LP). ASYM is the current shaper's share of its even part (the part that + /// carries DC and sub-audio pulses): one value per shaper, stored in the project / presets (not a host parameter). + /// Drag, wheel, double-click = 100 %. + fn bias_asym(&mut self, x: f32, y: f32, w: f32, h: f32) { + let hh = (h * 0.5).floor(); + let shape = ((self.sget(1) + 0.5).floor() as i32).clamp(0, CUSTOM) as usize; + let cell = self.env.params.asym.clone(); + let get = || satcomp_dsp::shapers::asym_from(&cell.lock())[shape] as f32; + let set = |v: f32| { + let mut g = cell.lock(); + if g.len() < SHAPER_NAMES.len() { + g.resize(SHAPER_NAMES.len(), 100.0); + } + g[shape] = v.clamp(0.0, 100.0); + }; + // top half: BIAS (an ordinary slider) + let ha = self.hit(x, y, w, hh); + if ha && self.press && self.act == 0 { + self.begin_drag(3); + } + if ha && self.wheel != 0 { + self.wheel_adj(3); + } + // bottom half: ASYM + let hb = self.hit(x, y + hh, w, h - hh); + if hb && self.press && self.act == 0 { + if self.dbl(170) { + set(100.0); + } else { + self.act = ACT_ASYM; + self.asym_drag = (self.my, get() * 0.01); + } + self.press = false; + } + if hb && self.wheel != 0 { + let d = if self.wheel > 0 { 1.0 } else { -1.0 } * if self.shift { 0.5 } else { 3.0 }; + set((get() + d).round()); + } + if self.act == ACT_ASYM && self.down { + let k = if self.shift { 0.0008 } else { 0.006 }; + let t = (self.asym_drag.1 + (self.asym_drag.0 - self.my) * k).clamp(0.0, 1.0); + set((t * 100.0).round()); + } + let act = self.act; + self.setc(act == 3 || act == ACT_ASYM); + self.cv.boxr(x, y, w, h); + self.setc(false); + self.cv.fill(x, y + hh, w, 1.0); + self.cv.set_font(1); + self.setc(act == 3); + let vb = self.sget(3); + let sb = self.fmt(3, vb); + let tb = self.n2t(3, vb); + self.cv.text(x + 3.0, y + 3.0, "BIAS"); + self.cv.textr(x, y + 3.0, w - 3.0, &sb); + self.cv.fill(x + 2.0, y + hh - 3.0, ((tb * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(act == ACT_ASYM); + let v = get(); + self.cv.text(x + 3.0, y + hh + 3.0, "ASYM"); + self.cv.textr(x, y + hh + 3.0, w - 3.0, &format!("{:.0}%", v)); + self.cv.fill(x + 2.0, y + h - 4.0, (((v * 0.01) * (w - 4.0)).floor()).max(1.0), 2.0); + self.setc(false); + } + fn draw_plot(&mut self, x: f32, y: f32, w: f32, h: f32) { let sh = self.env.shared; let dsp = self.env.dsp; @@ -1074,6 +984,12 @@ impl<'a> Gui<'a> { let pre = (dsp.drive * 0.01 * 36.0 * 0.11512925).exp() as f32; let bias = (dsp.bias * 0.01) as f32; self.lut.sync(dsp.shape, &dsp.curve); + // static curve as heard: the shaper minus the part of its even half that ASYM removes + let ak = dsp.asym[(dsp.shape.max(0) as usize).min(dsp.asym.len() - 1)] * 0.01; + let eff = move |l: &ShaperLut, v: f64| { + let r = 0.5 * (1.0 - ak); + l.eval(v) * (1.0 - r) - r * l.eval(-v) + }; // pencil (top right): toggles the custom-curve draw view; entering selects the Custom shaper so edits are audible let pen = self.hit(x + w - 14.0, y + 2.0, 12.0, 12.0); if pen && self.press && self.act == 0 { @@ -1081,6 +997,8 @@ impl<'a> Gui<'a> { self.edit_seen = false; if self.curve_edit { self.click_set(1, CUSTOM as f32); + // symmetry is the default tool, unless the stored curve is lopsided: opening must not alter it + self.sym_mode = self.env.params.curve_snapshot().is_odd(); } self.press = false; } @@ -1112,7 +1030,11 @@ impl<'a> Gui<'a> { for i in 0..(h / 2.0).floor() as i32 { self.cv.fill(x + (w / 2.0).floor(), y + i as f32 * 2.0, 1.0, 1.0); } - self.pencil_glyph(x + w - 14.0, y + 2.0, self.curve_edit, pen); + if self.curve_edit { + self.close_glyph(x + w - 14.0, y + 2.0, pen); + } else { + self.pencil_glyph(x + w - 14.0, y + 2.0, false, pen); + } if self.curve_edit { self.draw_curve_edit(x, y, w, h); return; @@ -1122,7 +1044,7 @@ impl<'a> Gui<'a> { let (mut lx, mut ly) = (0.0, 0.0); for i in 0..=n { let vx = -1.0 + 2.0 * i as f32 / n as f32; - let mut vy = if sat_on { self.lut.eval((vx * pre + bias) as f64) as f32 } else { vx }; + let mut vy = if sat_on { eff(&self.lut, (vx * pre + bias) as f64) as f32 } else { vx }; vy = vy.clamp(-1.0, 1.0); let px = x + (vx + 1.0) * 0.5 * (w - 1.0); let py = y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0); @@ -1135,9 +1057,9 @@ impl<'a> Gui<'a> { } if sat_on && pk > 0.002 { self.setc(true); - let vy = (self.lut.eval((pk * pre + bias) as f64) as f32).clamp(-1.0, 1.0); + let vy = (eff(&self.lut, (pk * pre + bias) as f64) as f32).clamp(-1.0, 1.0); self.cv.fill(x + (pk + 1.0) * 0.5 * (w - 1.0) - 1.0, y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0) - 1.0, 3.0, 3.0); - let vy = (self.lut.eval((-pk * pre + bias) as f64) as f32).clamp(-1.0, 1.0); + let vy = (eff(&self.lut, (-pk * pre + bias) as f64) as f32).clamp(-1.0, 1.0); self.cv.fill(x + (1.0 - pk) * 0.5 * (w - 1.0) - 1.0, y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0) - 1.0, 3.0, 3.0); self.setc(false); } @@ -1180,50 +1102,75 @@ impl<'a> Gui<'a> { self.setc(false); } - /// Draw view of the custom curve (unity input, independent of drive/bias). + /// Draw view of the custom curve (unity input, independent of drive/bias). Tools (top right, left of the close cross): + /// symmetry (default) draws the right half and mirrors it through the origin, `f(-x) = -f(x)`, the pencil draws free. /// Left click empty space = add a point (and drag it), drag = move, double click = remove. /// The two end points are fixed in x and cannot be removed. fn draw_curve_edit(&mut self, x: f32, y: f32, w: f32, h: f32) { let mut c = self.env.params.curve_snapshot(); let before = c; - // domain [-1,1]^2 is inset so end points and the pencil never collide (symmetric margins keep the centre cross true) + // tool icons left of the close cross: free draw (pencil), symmetry + let (pen_x, sym_x) = (x + w - 28.0, x + w - 42.0); + let (hp, hs) = (self.hit(pen_x, y + 2.0, 12.0, 12.0), self.hit(sym_x, y + 2.0, 12.0, 12.0)); + if self.press && self.act == 0 { + if hp && self.sym_mode { + self.sym_mode = false; + self.press = false; + } else if hs && !self.sym_mode { + // free -> symmetric keeps the odd part of the curve (what a symmetric curve can hold) + c = Curve::from_odd_half(&c.odd_half()); + self.sym_mode = true; + self.press = false; + } + } + let sym = self.sym_mode; + // domain [-1,1]^2 is inset so end points and the icons never collide (symmetric margins keep the centre cross true) let (ex, ey, ew, eh) = (x + 9.0, y + 14.0, w - 18.0, h - 28.0); let (px, py) = (|vx: f32| ex + (vx + 1.0) * 0.5 * (ew - 1.0), |vy: f32| ey + (1.0 - (vy + 1.0) * 0.5) * (eh - 1.0)); let to_v = |mx: f32, my: f32| (((mx - ex) / (ew - 1.0)) * 2.0 - 1.0, 1.0 - ((my - ey) / (eh - 1.0)) * 2.0); - let pick = |s: &Self, c: &Curve| -> Option { + // working list: the whole curve, or in symmetry mode its right half (x > 0, ending at x = 1); the left is derived + let mut hv: Vec<(f32, f32)> = if sym { c.pts().iter().cloned().filter(|p| p.0 > 0.0).collect() } else { c.pts().to_vec() }; + if sym && hv.is_empty() { + hv.push((1.0, 1.0)); + } + let cap = if sym { MAX_PTS / 2 } else { MAX_PTS }; + let interior = |i: usize, n: usize| if sym { i + 1 < n } else { i > 0 && i + 1 < n }; + let xlo = |hv: &Vec<(f32, f32)>, i: usize| if i == 0 { if sym { 0.0 } else { -1.0 } } else { hv[i - 1].0 }; + // a point is picked on its own spot, or in symmetry mode on its mirror image + let pick = |s: &Self, hv: &Vec<(f32, f32)>| -> Option { let mut best: Option<(usize, f32)> = None; - for (i, &(vx, vy)) in c.pts().iter().enumerate() { - let d = ((s.mx - px(vx)).powi(2) + (s.my - py(vy)).powi(2)).sqrt(); + for (i, &(vx, vy)) in hv.iter().enumerate() { + let mut d = ((s.kit.mx - px(vx)).powi(2) + (s.kit.my - py(vy)).powi(2)).sqrt(); + if sym { + d = d.min(((s.kit.mx - px(-vx)).powi(2) + (s.kit.my - py(-vy)).powi(2)).sqrt()); + } if d <= 6.0 && best.map_or(true, |b| d < b.1) { best = Some((i, d)); } } best.map(|b| b.0) }; - let in_box = self.hit(x, y, w, h) && !self.hit(x + w - 14.0, y + 2.0, 12.0, 12.0); + let in_box = self.hit(x, y, w, h) && !self.hit(sym_x, y + 2.0, 56.0, 12.0); if in_box && self.press && self.act == 0 { - if let Some(i) = pick(self, &c) { - let interior = i > 0 && i + 1 < c.n; - if self.dbl(200 + i as i32) && interior { - for k in i..c.n - 1 { - c.p[k] = c.p[k + 1]; - } - c.n -= 1; + let n = hv.len(); + if let Some(i) = pick(self, &hv) { + if self.dbl(200 + i as i32) && interior(i, n) { + hv.remove(i); self.last_clk_n = 0; } else { self.act = 160; self.cpt = i; } - } else if c.n < MAX_PTS { - let (vx, vy) = to_v(self.mx, self.my); - let at = (1..c.n).find(|&k| c.p[k].0 > vx).unwrap_or(c.n - 1); - let room = vx - c.p[at - 1].0 >= MIN_GAP && c.p[at].0 - vx >= MIN_GAP; + } else if n < cap { + let (mut vx, mut vy) = to_v(self.mx, self.my); + if sym && vx < 0.0 { + vx = -vx; + vy = -vy; + } + let at = if sym { hv.iter().position(|p| p.0 > vx) } else { (1..n).find(|&k| hv[k].0 > vx) }.unwrap_or(n - 1); + let room = vx - xlo(&hv, at) >= MIN_GAP && hv[at].0 - vx >= MIN_GAP; if room { - for k in (at..c.n).rev() { - c.p[k + 1] = c.p[k]; - } - c.p[at] = (vx, vy.clamp(-1.0, 1.0)); - c.n += 1; + hv.insert(at, (vx, vy.clamp(-1.0, 1.0))); self.act = 160; self.cpt = at; self.last_clk_n = 0; // a creating click never counts towards a double click @@ -1233,14 +1180,23 @@ impl<'a> Gui<'a> { self.vt2 = 0; self.press = false; } - if self.act == 160 && self.down && self.cpt < c.n { - let (vx, vy) = to_v(self.mx, self.my); + if self.act == 160 && self.down && self.cpt < hv.len() { + let (mut vx, mut vy) = to_v(self.mx, self.my); let i = self.cpt; - if i > 0 && i + 1 < c.n { - c.p[i].0 = vx.clamp(c.p[i - 1].0 + MIN_GAP, c.p[i + 1].0 - MIN_GAP); + if sym { + // dragging the ghost half moves the real point the other way round + if vx < 0.0 { + vx = -vx; + vy = -vy; + } + } + let n = hv.len(); + if interior(i, n) { + hv[i].0 = vx.clamp(xlo(&hv, i) + MIN_GAP, hv[i + 1].0 - MIN_GAP); } - c.p[i].1 = vy.clamp(-1.0, 1.0); + hv[i].1 = vy.clamp(-1.0, 1.0); } + c = if sym { Curve::from_odd_half(&hv) } else { Curve::from_points(&hv) }; if c != before { *self.env.params.custom_curve.lock() = c.pts().to_vec(); } @@ -1266,17 +1222,30 @@ impl<'a> Gui<'a> { lx = qx; ly = qy; } - let hot = if self.act == 160 { Some(self.cpt) } else { pick(self, &c) }; - for (i, &(vx, vy)) in c.pts().iter().enumerate() { + let hot = if self.act == 160 { Some(self.cpt) } else { pick(self, &hv) }; + let nh = hv.len(); + for (i, &(vx, vy)) in hv.iter().enumerate() { let (qx, qy) = (px(vx).round(), py(vy).round()); self.setc(hot == Some(i)); - if i == 0 || i + 1 == c.n { + let end = if sym { i + 1 == nh } else { i == 0 || i + 1 == nh }; + if end { self.cv.boxr(qx - 2.0, qy - 2.0, 5.0, 5.0); // y-only end points } else { self.cv.fill(qx - 2.0, qy - 2.0, 5.0, 5.0); } + if sym { + // the mirrored partner: a dim outline you can grab just the same + let (gx, gy) = (px(-vx).round(), py(-vy).round()); + let pd = self.dk; + self.set_dk(pd * 0.6); + self.cv.boxr(gx - 2.0, gy - 2.0, 5.0, 5.0); + self.set_dk(pd); + } } self.setc(false); + // tools: pencil (free draw), symmetry + self.pencil_glyph(pen_x, y + 2.0, !sym, hp); + self.sym_glyph(sym_x, y + 2.0, sym, hs); self.cv.set_font(1); self.cv.text(x + 3.0, y + 3.0, "DRAW"); self.cv.textr(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, MAX_PTS)); @@ -1317,7 +1286,7 @@ impl<'a> Gui<'a> { } fn draw_ccurve(&mut self, x: f32, y: f32, w: f32, h: f32) { - let gc = GainComputer::from_params(&self.env.dsp); + let gc = GainComputer::from_params(&self.env.dsp.comp()); let hv = self.hit(x, y, w, h); let thr = self.sget(8); if self.act == 120 && self.down { @@ -1334,7 +1303,7 @@ impl<'a> Gui<'a> { let thr = self.sget(8); let gc = if self.act == 120 || self.act == 121 { self.refresh_dsp(); - GainComputer::from_params(&self.env.dsp) + GainComputer::from_params(&self.env.dsp.comp()) } else { gc }; @@ -1941,6 +1910,7 @@ impl<'a> Gui<'a> { // absent curve = linear (deterministic: loading a preset never keeps the previous preset's curve) let c = Curve::from_points(&p.curve); *self.env.params.custom_curve.lock() = c.pts().to_vec(); + *self.env.params.asym.lock() = satcomp_dsp::shapers::asym_from(&p.asym).iter().map(|&v| v as f32).collect(); self.set_preset_name(&p.name); self.base = None; self.hold_until = self.now + 0.6; @@ -1972,7 +1942,7 @@ impl<'a> Gui<'a> { return true; } } - Curve::from_points(&b.curve) != self.env.params.curve_snapshot() + Curve::from_points(&b.curve) != self.env.params.curve_snapshot() || satcomp_dsp::shapers::asym_from(&b.asym) != self.env.params.asym_snapshot() } fn capture(&self, name: &str) -> Preset { @@ -1986,6 +1956,10 @@ impl<'a> Gui<'a> { if c != Curve::linear() { p.curve = c.pts().to_vec(); } + let a = self.env.params.asym_snapshot(); + if a.iter().any(|&v| v != 100.0) { + p.asym = a.iter().map(|&v| v as f32).collect(); + } p } @@ -2186,263 +2160,9 @@ impl<'a> Gui<'a> { } // ------------------------------------------------------------------ about page - /// Greedy word wrap at the current font. - fn wrap(&self, s: &str, w: f32) -> Vec { - let mut out = Vec::new(); - let mut cur = String::new(); - for word in s.split(' ') { - let t = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") }; - if !cur.is_empty() && self.cv.text_w(&t) > w { - out.push(std::mem::take(&mut cur)); - cur = word.to_string(); - } else { - cur = t; - } - } - if !cur.is_empty() { - out.push(cur); - } - out - } - - /// Replaces the left two thirds of the window (tab row, viz row, cells) while the About page is open. - fn draw_about(&mut self, byp: bool) { - for (x, w, l, id) in [(10.0, 114.0, "ABOUT", 1u8), (125.0, 114.0, "APPEARANCE", 3u8), (240.0, 114.0, "CHANGELOG", 2u8)] { - if self.btn(x, 34.0, w, 16.0, l, (self.about == id) as u8) { - self.about = id; - self.about_scroll = 0; - if id == 3 { - self.ap_scroll = self.pal.saturating_sub(2); - } - } - } - if self.btn(356.0, 34.0, 62.0, 16.0, "X CLOSE", 0) { - self.about = 0; - self.about_scroll = 0; - } - self.setc(false); - self.cv.set_font(1); - if self.about == 3 { - self.draw_appearance(); - return; - } - if self.about == 2 { - self.cv.boxr(10.0, 56.0, 408.0, 266.0); - let mut rows = Vec::new(); - for (ver, lines) in CHANGELOG { - rows.push(Row::Head(ver.to_string())); - rows.push(Row::Pad); - for l in *lines { - for (i, t) in self.wrap(l, 378.0).into_iter().enumerate() { - rows.push(Row::Text(if i == 0 { 0.0 } else { 10.0 }, if i == 0 { format!("- {t}") } else { t })); - } - } - rows.push(Row::Pad); - } - self.scroll_rows(10.0, 56.0, 408.0, 266.0, &rows); - return; - } - self.draw_flow(10.0, 56.0, 408.0, 114.0, byp); - self.setc(false); - self.cv.boxr(10.0, 176.0, 408.0, 146.0); - let mut rows = Vec::new(); - for para in ABOUT_TEXT { - for l in *para { - for t in self.wrap(l, 378.0) { - rows.push(Row::Text(0.0, t)); - } - } - rows.push(Row::Pad); - } - self.scroll_rows(10.0, 176.0, 408.0, 129.0, &rows); - self.setc(false); - self.cv.text(16.0, 322.0 - 17.0, &format!("Font: {} (SIL OFL 1.1)", FONT_NAMES[self.face])); - self.cv.textr(10.0, 322.0 - 17.0, 408.0 - 6.0, "thomchantra"); - } - - fn set_face(&mut self, i: usize) { - self.face = i.min(FONT_NAMES.len() - 1); - self.env.params.font.store(self.face as i32, Ordering::Relaxed); - self.cv.face = self.face; - } - - /// Appearance tab: colour mode switch, scrollable scheme list with swatches, font choice. Everything applies at once. - fn draw_appearance(&mut self) { - const ROWS: usize = 5; - const RH: f32 = 20.0; - self.cv.boxr(10.0, 56.0, 408.0, 266.0); - self.setc(false); - self.cv.set_font(1); - self.cv.text(18.0, 64.0, "COLOR MODE"); - for (x, l, lt) in [(110.0, "DARK", false), (176.0, "LIGHT", true)] { - if self.btn(x, 60.0, 64.0, 16.0, l, (self.light == lt) as u8) { - self.set_light(lt); - } - } - - // ---- scheme list - self.setc(false); - self.cv.text(18.0, 86.0, "COLOR SCHEME"); - let user_sel = self.pal >= PALETTES.len(); - if self.btn(248.0, 82.0, 82.0, 14.0, "NEW THEME", 0) { - self.begin_edit(None); - return; - } - let prev_dk = self.dk; - if !user_sel { - self.set_dk(0.5); // EDIT / DELETE only apply to a user theme - } - let armed = self.now - self.del_arm < 3.0; - let edit_hit = self.btn(332.0, 82.0, 38.0, 14.0, "EDIT", 0); - let del_hit = self.btn(372.0, 82.0, 38.0, 14.0, if armed && user_sel { "SURE?" } else { "DEL" }, (armed && user_sel) as u8 * 2); - self.set_dk(prev_dk); - if user_sel { - if edit_hit { - self.begin_edit(Some(self.pal - PALETTES.len())); - return; - } - if del_hit { - if armed { - self.delete_user(self.pal - PALETTES.len()); - self.del_arm = -10.0; - } else { - self.del_arm = self.now; - } - } - } - let (lx, ly, lw) = (18.0, 98.0, 392.0); - let lh = ROWS as f32 * RH + 2.0; - let n = self.n_schemes(); - let max = n.saturating_sub(ROWS); - if self.hit(lx, ly, lw, lh) && self.wheel != 0 { - self.ap_scroll = (self.ap_scroll as i32 - self.wheel).clamp(0, max as i32) as usize; - } - let (tx, ty, th) = (lx + lw - 9.0, ly + 3.0, lh - 6.0); - let thumb = (th * ROWS as f32 / n as f32).floor().max(14.0).min(th); - if self.hit(tx - 3.0, ty, 11.0, th) && self.press && self.act == 0 { - self.act = 141; - self.press = false; - } - if self.act == 141 && self.down { - let f = ((self.my - ty - thumb * 0.5) / (th - thumb).max(1.0)).clamp(0.0, 1.0); - self.ap_scroll = (f * max as f32 + 0.5).floor() as usize; - } - self.ap_scroll = self.ap_scroll.min(max); - self.setc(false); - self.cv.boxr(lx, ly, lw, lh); - let rw = lw - 2.0 - 11.0; - for i in 0..ROWS.min(n) { - let idx = self.ap_scroll + i; - let y = ly + 1.0 + i as f32 * RH; - let sel = idx == self.pal; - if self.hit(lx + 1.0, y, rw, RH) && self.press && self.act == 0 { - self.set_pal(idx); - self.press = false; - } - if sel { - self.setc(false); - self.cv.fill(lx + 1.0, y, rw, RH); - self.cv.setbg(); - } else { - self.setc(false); - } - let nm = self.scheme_name(idx); - self.cv.text(lx + 9.0, y + 6.0, &nm); - let a = self.scheme_cols(idx, self.light); - for (k, name) in ["BG", "UI", "ACCENT"].iter().enumerate() { - let _ = name; - let (cx, cy) = (lx + rw - 3.0 - (3 - k) as f32 * 22.0 + 4.0, y + 3.0); - if sel { - self.cv.setbg(); - } else { - self.setc(false); - } - self.cv.fill(cx, cy, 20.0, RH - 6.0); - self.cv.setrgb([a[k * 3], a[k * 3 + 1], a[k * 3 + 2]]); - self.cv.fill(cx + 1.0, cy + 1.0, 18.0, RH - 8.0); - } - } - self.setc(false); - self.cv.fill(tx + 3.0, ty, 1.0, th); // track - let top = ty + (th - thumb) * self.ap_scroll as f32 / max as f32; - self.setc(self.act == 141); - self.cv.fill(tx + 1.0, top.floor(), 5.0, thumb); - self.setc(false); - - // ---- font - self.cv.text(18.0, 208.0, "FONT"); - for (i, name) in FONT_NAMES.iter().enumerate() { - let (x, y, w, h) = (18.0 + (i % 2) as f32 * 200.0, 220.0 + (i / 2) as f32 * 24.0, 192.0, 20.0); - let on = self.face == i; - if self.hit(x, y, w, h) && self.press && self.act == 0 { - self.set_face(i); - self.press = false; - } - self.setc(false); - if on { - self.cv.fill(x, y, w, h); - self.cv.setbg(); - } else { - self.cv.boxr(x, y, w, h); - } - let keep = self.cv.face; - self.cv.face = i; // each name is drawn in its own typeface - self.cv.textc(x, y + 6.0, w, name); - self.cv.face = keep; - } - self.setc(false); - self.cv.text(18.0, 300.0, "Applies at once, saved with the project. Fonts: SIL OFL 1.1"); - } - - /// Text rows (11 units each) in a box whose frame the caller has drawn. Mouse wheel scrolls 3 rows per notch; when the - /// text overflows a thumb on the right edge shows the position and can be dragged. Rows are culled whole (no clipping). - fn scroll_rows(&mut self, x: f32, y: f32, w: f32, h: f32, rows: &[Row]) { - let vis = (((h - 10.0) / 11.0).floor() as usize).max(1); - let max = rows.len().saturating_sub(vis); - if self.hit(x, y, w, h) && self.wheel != 0 { - self.about_scroll = (self.about_scroll as i32 - self.wheel * 3).clamp(0, max as i32) as usize; - } - let (tx, ty, th) = (x + w - 8.0, y + 4.0, h - 8.0); - let thumb = (th * vis as f32 / rows.len().max(1) as f32).floor().max(14.0).min(th); - if max > 0 { - if self.hit(tx - 3.0, ty, 10.0, th) && self.press && self.act == 0 { - self.act = 140; - self.vt1 = 0; - self.vt2 = 0; - self.press = false; - } - if self.act == 140 && self.down { - let f = ((self.my - ty - thumb * 0.5) / (th - thumb).max(1.0)).clamp(0.0, 1.0); - self.about_scroll = (f * max as f32 + 0.5).floor() as usize; - } - } - self.about_scroll = self.about_scroll.min(max); - self.setc(false); - for (i, r) in rows.iter().skip(self.about_scroll).take(vis).enumerate() { - let yy = y + 7.0 + i as f32 * 11.0; - match r { - Row::Text(ind, t) => self.cv.text(x + 8.0 + ind, yy, t), - Row::Head(t) => { - self.cv.text(x + 8.0, yy, t); - if i + 1 < vis { - self.cv.fill(x + 8.0, yy + 13.0, w - 16.0 - if max > 0 { 8.0 } else { 0.0 }, 1.0); - } - } - Row::Pad => {} - } - } - if max > 0 { - self.cv.fill(tx + 3.0, ty, 1.0, th); // track - let top = ty + (th - thumb) * self.about_scroll as f32 / max as f32; - self.setc(self.act == 140); - self.cv.fill(tx + 1.0, top.floor(), 5.0, thumb); - self.setc(false); - } - } - /// Signal-flow diagram: SAT > PRE EQ > COMP > MIX (dry path) > POST EQ > OUT. Dots move along the path; their size /// follows the live output level (pre-compressor segments add the gain reduction back, so they read hotter). - fn draw_flow(&mut self, x: f32, y: f32, w: f32, h: f32, byp: bool) { + fn draw_flow_at(&mut self, x: f32, y: f32, w: f32, h: f32, byp: bool) { let prev = self.dk; let sh = self.env.shared; self.setc(false); @@ -2459,15 +2179,17 @@ impl<'a> Gui<'a> { let pre_on = a0 && !eq_mod && self.sget(60) < 0.5; let post_on = a1 && !eq_mod && self.sget(61) < 0.5; let sat_on = sh.sat_vz.load(Ordering::Relaxed) > 0.02; - let names = ["IN", "SAT", "PRE EQ", "COMP", "MIX", "POST EQ", "OUT"]; - let bw = [26.0, 34.0, 52.0, 40.0, 32.0, 58.0, 32.0]; - let lit = [false, sat_on, pre_on, gr > 0.1, false, post_on, false]; - let eq_off = [false, false, eq_mod || self.sget(60) > 0.5, false, false, eq_mod || self.sget(61) > 0.5, false]; - let gap = (w - 24.0 - bw.iter().sum::()) / 6.0; + let names = ["IN", "SAT", "PRE EQ", "COMP", "MIX", "POST EQ", "LIM", "OUT"]; + let bw = [24.0, 32.0, 48.0, 38.0, 30.0, 50.0, 26.0, 28.0]; + let lim_on = self.sget(68) > 0.5; + let lit = [false, sat_on, pre_on, gr > 0.1, false, post_on, lim_on && self.lim_disp > 0.1, false]; + // an unused stage is drawn dim: the EQ stages when bypassed, the limiter when switched off + let eq_off = [false, false, eq_mod || self.sget(60) > 0.5, false, false, eq_mod || self.sget(61) > 0.5, !lim_on, false]; + let gap = (w - 24.0 - bw.iter().sum::()) / 7.0; let (cy, bh) = (y + 50.0, 22.0); - let mut bx = [0.0f32; 7]; + let mut bx = [0.0f32; 8]; let mut cx = x + 12.0; - for i in 0..7 { + for i in 0..8 { bx[i] = cx; cx += bw[i] + gap; } @@ -2480,7 +2202,7 @@ impl<'a> Gui<'a> { } }; self.setc(false); - for i in 0..6 { + for i in 0..7 { let (g0, g1) = (bx[i] + bw[i], bx[i + 1]); self.cv.fill(g0, cy, g1 - g0 - 3.0, 1.0); self.cv.tri((g1 - 4.0, cy - 3.0), (g1 - 4.0, cy + 4.0), (g1, cy + 0.5)); @@ -2513,11 +2235,29 @@ impl<'a> Gui<'a> { } self.cv.textc(xa, yd + 4.0, xb - xa, "DRY"); // blocks - for i in 0..7 { + for i in 0..8 { self.set_dk(if eq_off[i] { prev * 0.5 } else { prev }); let (bxl, byt) = (bx[i], cy - bh * 0.5 + 0.5); + // PRE EQ, POST EQ and LIM are switches: click one to bypass it or bring it back + let hov = (i == 2 || i == 5 || i == 6) && self.hit(bxl, byt, bw[i], bh); + if hov && self.kit.press && self.kit.act == 0 { + self.kit.press = false; + match i { + 2 | 5 => { + let slot = if i == 2 { 60 } else { 61 }; + if eq_off[i] { + // switching it on also clears the whole-EQ bypass + self.click_set(slot, 0.0); + self.click_set(62, 0.0); + } else { + self.click_set(slot, 1.0); + } + } + _ => self.click_set(68, if lim_on { 0.0 } else { 1.0 }), + } + } if lit[i] { - self.setc(false); + self.setc(hov); self.cv.fill(bxl, byt, bw[i], bh); self.cv.setbg(); } else { @@ -2525,7 +2265,7 @@ impl<'a> Gui<'a> { self.cv.fill(bxl + 1.0, byt + 1.0, bw[i] - 2.0, bh - 2.0); // clear the line under the box self.cv.setbg(); self.cv.fill(bxl + 1.0, byt + 1.0, bw[i] - 2.0, bh - 2.0); - self.setc(false); + self.setc(hov); self.cv.boxr(bxl, byt, bw[i], bh); } self.cv.textc(bxl, byt + 7.0, bw[i], names[i]); @@ -2553,7 +2293,7 @@ impl<'a> Gui<'a> { } else { self.cv.textc(bx[3] - 10.0, cy - bh * 0.5 - 14.0, bw[3] + 20.0, &s); } - self.cv.text(x + 6.0, y + h - 15.0, if sig { "DOT SIZE = LEVEL" } else { "PLAY AUDIO TO SEE THE FLOW" }); + self.cv.text(x + 6.0, y + h - 15.0, if sig { "DOT SIZE = LEVEL. CLICK PRE EQ, POST EQ OR LIM TO SWITCH IT" } else { "CLICK PRE EQ, POST EQ OR LIM TO SWITCH IT" }); let _ = byp; } @@ -2561,26 +2301,23 @@ impl<'a> Gui<'a> { pub fn frame(&mut self) { let sh = self.env.shared; // Theme editor: every widget draws as a dummy with the input masked; only the editor cells and the picker get it. - let editing = self.edit.is_some(); - self.real_in = (self.press, self.down, self.rpress, self.wheel, self.mx, self.my); + let editing = self.app.editing(); + self.begin_frame_editing(); if editing { - self.mask_in(); - self.act = 0; self.logo_pend = -1.0; self.eq_page = false; self.curve_edit = false; self.menu = None; - self.about = 0; } // readouts refresh ~8x/s self.rd_tick = self.now - self.rd_last >= 0.12; if self.rd_tick { self.rd_last = self.now; self.rd_gr = self.gr_disp; + self.rd_lim = self.lim_disp; self.rd_pk = self.opk_max; self.rd_rms = sh.fms.load(Ordering::Relaxed); self.rd_diff = sh.diff_disp.load(Ordering::Relaxed); - self.rd_bg = sh.bg.load(Ordering::Relaxed); self.rd_lk = self.env.params.match_trim.load(Ordering::Relaxed); self.rd_mt = sh.out_mt.load(Ordering::Relaxed); self.rd_sat = sh.sat_db.load(Ordering::Relaxed); @@ -2628,19 +2365,30 @@ impl<'a> Gui<'a> { let title = format!("SATCOMP {}", version_short()); let tw = self.cv.text_w(&title); if self.hit(42.0, 5.0, tw + 4.0, 21.0) && self.press && self.act == 0 { - self.about = if self.about == 0 { 1 } else { 0 }; - self.about_scroll = 0; + self.app.about = if self.app.about == 0 { 1 } else { 0 }; + self.app.about_scroll = 0; self.press = false; } + // hovering highlights the title (a UI-coloured rectangle behind it, the text in the background colour): it opens About + if self.hit(42.0, 5.0, tw + 4.0, 21.0) { + self.cv.fill(42.0, 8.0, tw + 4.0, 15.0); + self.cv.setbg(); + } self.cv.text(44.0, 12.0, &title); + self.setc(false); self.preset_bar(); - self.out_meter(430.0, 8.0, 120.0, 16.0); + // LIM switch + output peak meter + if self.btn(430.0, 8.0, 30.0, 16.0, "LIM", (self.sget(68) > 0.5) as u8) { + let on = self.sget(68) > 0.5; + self.click_set(68, if on { 0.0 } else { 1.0 }); + } + self.out_meter(464.0, 8.0, 86.0, 16.0); // ---------- tab row - let ab = self.about > 0; + let ab = self.app.about > 0; self.set_dk(if byp { 0.5 } else { 1.0 }); if ab { - self.draw_about(byp); + self.draw_about(Rect::new(10.0, 56.0, 408.0, 266.0), byp); } if !ab { self.selector(1, 10.0, 34.0, 130.0, 16.0); @@ -2708,11 +2456,12 @@ impl<'a> Gui<'a> { // ---------- SAT cells if !ab { self.cell(2, 10.0, 196.0, 62.0, 38.0, "DRIVE"); - self.cell(3, 78.0, 196.0, 62.0, 38.0, "BIAS"); + self.bias_asym(78.0, 196.0, 62.0, 38.0); self.cell2(4, 5, 10.0, 240.0, 62.0, 38.0, "HP", "LP"); self.cell(6, 78.0, 240.0, 62.0, 38.0, "TONE"); self.cell(25, 10.0, 284.0, 62.0, 38.0, "SAT MIX"); - self.cell_o(27, 78.0, 284.0, 62.0, 38.0, "OUT GAIN"); + self.cell_o(27, 78.0, 284.0, 62.0, 38.0, "SAT GAIN"); + self.sat_vu(144.0, 196.0, 5.0, 126.0); // ---------- COMP cells (or the EQ page's cells) if self.eq_page { @@ -2720,7 +2469,7 @@ impl<'a> Gui<'a> { self.set_dk(if byp || eq_mod_byp || stage_byp { 0.5 } else { 1.0 }); self.draw_eq_cells(); } else if editing { - self.theme_cells(); + self.theme_cells(CellGrid { x0: 152.0, y0: 196.0, cw: 62.0, ch: 38.0, px: 68.0, py: 44.0 }); } else { self.cell(8, 152.0, 196.0, 62.0, 38.0, "THRESH"); self.cell(9, 220.0, 196.0, 62.0, 38.0, "RATIO"); @@ -2745,9 +2494,13 @@ impl<'a> Gui<'a> { self.set_dk(1.0); self.cv.set_font(1); self.setc(false); - self.cv.text(464.0, 58.0, "GR"); - let s = format!("{:04.1}", self.rd_gr); + // limiter reduction: the only sign the limiter has engaged (the compressor's GR number lives on its meter) + let lim_on = self.sget(68) > 0.5; + self.setc(lim_on && self.rd_lim > 0.05); + self.cv.text(464.0, 58.0, "LIM"); + let s = if lim_on { format!("{:04.1}dB", self.rd_lim) } else { "-----dB".to_string() }; self.cv.textr(464.0, 58.0, 86.0, &s); + self.setc(false); let gmatch = self.sget(23) > 0.5; let meas = sh.out_meas.load(Ordering::Relaxed); let s1 = if gmatch { @@ -2771,11 +2524,6 @@ impl<'a> Gui<'a> { let s1 = if self.rd_rms > 0.000000001 { format!("{:+05.1}dB", 4.3429448 * self.rd_rms.ln()) } else { "-----dB".into() }; self.cv.text(464.0, 100.0, "RMS"); self.cv.textr(464.0, 100.0, 86.0, &s1); - if byp { - self.cv.text(464.0, 112.0, "BYP"); - let s = format!("{:+05.1}dB", 8.6858896 * self.rd_bg.max(1e-9).ln()); - self.cv.textr(464.0, 112.0, 86.0, &s); - } // GAIN MATCH: off -> click measures 3 s then locks a trim (red); click while measuring cancels; click while locked turns it off let gm_lit = if gmatch { if meas && blink(self.now) { 1 } else { 2 } } else { 0 }; if self.btn(464.0, 128.0, 86.0, 14.0, "GAIN MATCH", gm_lit) { @@ -2797,56 +2545,15 @@ impl<'a> Gui<'a> { self.run_pending(); if editing { self.unmask_in(); - let osk = self.edit.as_ref().map(|e| e.osk.is_some()).unwrap_or(false); + let osk = self.app.osk_open(); if osk { self.mask_in(); // picker stays visible underneath but inert } - self.theme_picker(); + self.theme_picker(Rect::new(152.0, 56.0, 266.0, 128.0)); if osk { self.unmask_in(); - self.theme_osk(); + self.theme_osk(Rect::new(152.0, 56.0, 266.0, 128.0)); } } } } - -/// In-place radix-2 complex FFT (n = 4096), bit-reversal included. -fn fft(re: &mut [f32], im: &mut [f32]) { - let n = re.len(); - let mut j = 0usize; - for i in 1..n { - let mut bit = n >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j ^= bit; - if i < j { - re.swap(i, j); - im.swap(i, j); - } - } - let mut len = 2; - while len <= n { - let ang = -2.0 * std::f32::consts::PI / len as f32; - let (wr, wi) = (ang.cos(), ang.sin()); - let mut i = 0; - while i < n { - let (mut cr, mut ci) = (1.0f32, 0.0f32); - for k in 0..len / 2 { - let (a, b) = (i + k, i + k + len / 2); - let tr = re[b] * cr - im[b] * ci; - let ti = re[b] * ci + im[b] * cr; - re[b] = re[a] - tr; - im[b] = im[a] - ti; - re[a] += tr; - im[a] += ti; - let ncr = cr * wr - ci * wi; - ci = cr * wi + ci * wr; - cr = ncr; - } - i += len; - } - len <<= 1; - } -} diff --git a/rust/satcomp-plugin/src/gui/ui/scope.rs b/rust/satcomp-plugin/src/gui/ui/scope.rs index d228978..d6017d3 100644 --- a/rust/satcomp-plugin/src/gui/ui/scope.rs +++ b/rust/satcomp-plugin/src/gui/ui/scope.rs @@ -16,6 +16,25 @@ fn ceil_db(i: usize) -> i32 { 2 - i as i32 } +/// (output peak, peak before the reduction) of absolute column `j` on a grid of `k` buckets per column, read from a ring whose +/// newest bucket index is `head - 1`. Pure in (ring contents, j, k): once a column is complete it never changes. +fn scope_col(ring: &satcomp_dsp::ScopeRing, head: usize, j: i64, k: f64) -> (f32, f32) { + let len = satcomp_dsp::ScopeRing::LEN as i64; + let b0 = j as f64 * k; + let i0 = b0.floor() as i64; + let i1 = ((b0 + k).floor() as i64).max(i0 + 1); + let (mut o, mut p) = (0.0f32, 0.0f32); + for i in i0..i1 { + if i < 0 || head as i64 - i >= len { + continue; + } + let (a, b) = ring.get(i as usize); + o = o.max(a); + p = p.max(b); + } + (o, p.max(o)) +} + fn fmt_db(db: i32) -> String { if db > 0 { format!("+{db}dB") } else { format!("{db}dB") } } @@ -25,7 +44,7 @@ fn fmt_db(db: i32) -> String { impl State { pub fn scope_on(&self) -> bool { - self.scope_cfg & 1 != 0 && self.edit.is_none() + self.scope_cfg & 1 != 0 && self.app.edit.is_none() } } @@ -93,23 +112,23 @@ impl<'a> Gui<'a> { let ring = self.env.shared.scope.clone(); let head = ring.head(); let ncol = (w - 2.0) as usize; - let k = WIN_S[win] / satcomp_dsp::ScopeRing::BUCKET_S as f32 / ncol as f32; - let len = satcomp_dsp::ScopeRing::LEN as i64; + let k = WIN_S[win] as f64 / satcomp_dsp::ScopeRing::BUCKET_S / ncol as f64; // buckets per column (fractional) + // Steady scrolling: the audio thread delivers buckets in host-block chunks, and a column grouped relative to the newest + // bucket changes every frame. So (1) the read position eases toward the head instead of jumping with each chunk, and + // (2) columns sit on a fixed grid in absolute bucket time and only complete ones are drawn: a column's content never + // changes once it exists, the picture just advances. + let target = head as f64 - 4.0; + let dt = (self.now - self.scope_t).clamp(0.0, 0.25); + self.scope_t = self.now; + if self.scope_pos <= 0.0 || (target - self.scope_pos).abs() > 4000.0 { + self.scope_pos = target; + } else { + self.scope_pos += (target - self.scope_pos) * (1.0 - (-dt * 10.0).exp()); + } + let last = (self.scope_pos / k).floor() as i64 - 1; // newest complete column let mut cols = vec![(0.0f32, 0.0f32); ncol]; for (c, col) in cols.iter_mut().enumerate() { - let b0 = head as f32 - (ncol - c) as f32 * k; - let i0 = b0.floor() as i64; - let i1 = ((b0 + k).floor() as i64).max(i0 + 1); - let (mut o, mut p) = (0.0f32, 0.0f32); - for i in i0..i1 { - if i < 0 || head as i64 - i >= len { - continue; - } - let (a, b) = ring.get(i as usize); - o = o.max(a); - p = p.max(b); - } - *col = (o, p.max(o)); + *col = scope_col(&ring, head, last - (ncol - 1 - c) as i64, k); } let span = if full { ((h - 2.0) * 0.5).floor() } else { h - 2.0 }; let hpx = |v: f32| ((v * zoom).min(1.0) * span).floor(); @@ -233,3 +252,30 @@ impl<'a> Gui<'a> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_complete_column_does_not_change_as_new_buckets_arrive() { + let ring = satcomp_dsp::ScopeRing::new(); + let val = |i: usize| 0.2 + 0.3 * ((i as f32 * 0.37).sin().abs()); + for i in 0..2000 { + ring.push(val(i), val(i) * 1.5); + } + // k = 3.7 buckets per column (a fractional window), the same columns read at two different heads + let k = 3.7; + let head0 = ring.head(); + let before: Vec<_> = (400..420).map(|j| scope_col(&ring, head0, j, k)).collect(); + for i in 2000..2013 { + ring.push(val(i), val(i) * 1.5); + } + let after: Vec<_> = (400..420).map(|j| scope_col(&ring, ring.head(), j, k)).collect(); + assert_eq!(before, after); + // a column reads the maximum of the buckets it spans: column 500 covers buckets 1850..1853 + let (o, _) = scope_col(&ring, ring.head(), 500, k); + let want = (1850..1853).map(val).fold(0.0f32, f32::max); + assert!((o - want).abs() < 1e-6, "{o} vs {want}"); + } +} diff --git a/rust/satcomp-plugin/src/gui/ui/theme.rs b/rust/satcomp-plugin/src/gui/ui/theme.rs deleted file mode 100644 index cab7595..0000000 --- a/rust/satcomp-plugin/src/gui/ui/theme.rs +++ /dev/null @@ -1,648 +0,0 @@ -//! User colour themes: storage (`themes.json` next to the Presets folder), the theme editor page (the INIT page drawn as a -//! static dummy, with the comp-settings area turned into the editor) and the colour picker overlay. - -use super::*; -use serde::{Deserialize, Serialize}; -use std::path::PathBuf; - -/// [BG rgb, UI rgb, ACCENT rgb] per mode, same layout as `PALETTES`. -#[derive(Clone, Serialize, Deserialize, PartialEq)] -pub struct UserTheme { - pub name: String, - pub dark: [f32; 9], - pub light: [f32; 9], -} - -const SLOT_NAMES: [&str; 6] = ["DARK BG", "DARK UI", "DARK ACCENT", "LIGHT BG", "LIGHT UI", "LIGHT ACCENT"]; -const SLOT_SHORT: [&str; 6] = ["DARK BG", "DARK UI", "DARK ACC", "LIGHT BG", "LIGHT UI", "LIGHT ACC"]; - -fn themes_path() -> Option { - presets::user_dir().and_then(|d| d.parent().map(|p| p.join("themes.json"))) -} - -pub fn load_themes() -> Vec { - themes_path() - .and_then(|p| std::fs::read_to_string(p).ok()) - .and_then(|s| serde_json::from_str::>(&s).ok()) - .unwrap_or_default() -} - -fn save_themes(v: &[UserTheme]) { - if let Some(p) = themes_path() { - if let Some(d) = p.parent() { - let _ = std::fs::create_dir_all(d); - } - if let Ok(s) = serde_json::to_string_pretty(v) { - let _ = std::fs::write(p, s); - } - } -} - -fn hex6(c: [f32; 3]) -> String { - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - format!("{:02X}{:02X}{:02X}", b(c[0]), b(c[1]), b(c[2])) -} - -fn parse6(s: &str) -> Option<[f32; 3]> { - if s.len() != 6 { - return None; - } - let v = u32::from_str_radix(s, 16).ok()?; - Some([((v >> 16) & 255) as f32 / 255.0, ((v >> 8) & 255) as f32 / 255.0, (v & 255) as f32 / 255.0]) -} - -/// `name|` + 18 hex digits (dark BG UI ACCENT, light BG UI ACCENT) -pub fn encode(t: &UserTheme) -> String { - let mut s = format!("{}|", t.name); - for a in [&t.dark, &t.light] { - for k in 0..3 { - s.push_str(&hex6([a[k * 3], a[k * 3 + 1], a[k * 3 + 2]])); - } - } - s -} - -fn decode(s: &str) -> Option { - let (name, hex) = s.rsplit_once('|')?; - if hex.len() != 36 || name.is_empty() { - return None; - } - let mut c = [[0.0f32; 3]; 6]; - for (i, slot) in c.iter_mut().enumerate() { - *slot = parse6(&hex[i * 6..i * 6 + 6])?; - } - Some(UserTheme { name: name.to_string(), dark: flat(&c[0..3]), light: flat(&c[3..6]) }) -} - -fn flat(c: &[[f32; 3]]) -> [f32; 9] { - let mut a = [0.0; 9]; - for k in 0..3 { - a[k * 3..k * 3 + 3].copy_from_slice(&c[k]); - } - a -} - -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { - let h = (h.rem_euclid(1.0)) * 6.0; - let (i, f) = (h.floor() as i32, h - h.floor()); - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - match i { - 0 => [v, t, p], - 1 => [q, v, p], - 2 => [p, v, t], - 3 => [p, q, v], - 4 => [t, p, v], - _ => [v, p, q], - } -} - -fn rgb_to_hsv(c: [f32; 3]) -> (f32, f32, f32) { - let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); - let d = mx - mn; - let h = if d < 1e-6 { - 0.0 - } else if mx == c[0] { - ((c[1] - c[2]) / d).rem_euclid(6.0) / 6.0 - } else if mx == c[1] { - ((c[2] - c[0]) / d + 2.0) / 6.0 - } else { - ((c[0] - c[1]) / d + 4.0) / 6.0 - }; - (h, if mx <= 0.0 { 0.0 } else { d / mx }, mx) -} - -/// black or white, whichever reads on `c` -fn contrast(c: [f32; 3]) -> [f32; 3] { - if 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] > 0.5 { - [0.0; 3] - } else { - [1.0; 3] - } -} - -pub struct Picker { - slot: usize, - old: [f32; 3], - h: f32, - s: f32, - v: f32, - /// 0 none, 1 dragging the SV square, 2 dragging the hue strip - drag: u8, -} - -/// On-screen keyboard state: 0 = theme name, 1 = hex colour. -pub struct Osk { - kind: u8, - text: String, -} - -pub struct ThemeEdit { - name: String, - /// dark BG, UI, ACCENT, then light BG, UI, ACCENT - col: [[f32; 3]; 6], - preview_light: bool, - /// user theme being edited (None = new) - index: Option, - picker: Option, - pub(super) osk: Option, -} - -impl State { - pub fn n_schemes(&self) -> usize { - PALETTES.len() + self.themes.len() - } - - pub fn scheme_name(&self, i: usize) -> String { - match i.checked_sub(PALETTES.len()) { - Some(u) => self.themes.get(u).map(|t| t.name.clone()).unwrap_or_default(), - None => PALETTES[i].0.to_string(), - } - } - - pub fn scheme_cols(&self, i: usize, light: bool) -> [f32; 9] { - match i.checked_sub(PALETTES.len()) { - Some(u) => self.themes.get(u).map(|t| if light { t.light } else { t.dark }).unwrap_or(PALETTES[0].1), - None => { - let e = &PALETTES[i.min(PALETTES.len() - 1)]; - if light { e.2 } else { e.1 } - } - } - } - - /// Colours the canvas draws with: the editor preview while editing, else the active scheme. - pub fn colors(&self) -> [f32; 9] { - match &self.edit { - Some(e) => { - let o = if e.preview_light { 3 } else { 0 }; - flat(&e.col[o..o + 3]) - } - None => self.scheme_cols(self.pal, self.light), - } - } - - /// A project that used a user theme: find it in the themes file by name, or restore it from the project copy. - pub fn restore_custom(&mut self, params: &SatCompParams) { - if self.pal < PALETTES.len() { - return; - } - let saved = decode(¶ms.custom_theme.lock()); - self.pal = match saved { - Some(t) => match self.themes.iter().position(|u| u.name == t.name) { - Some(i) => PALETTES.len() + i, - None => { - self.themes.push(t); - PALETTES.len() + self.themes.len() - 1 - } - }, - None => 0, - }; - params.palette_v2.store(self.pal as i32, Ordering::Relaxed); - } - - /// Constant meter / readout values for the dummy page (set every frame, the draw code then settles on them). - pub fn fill_dummy(&self) { - let d = &self.dummy_shared; - d.gr_pk.store(3.5, Ordering::Relaxed); - d.opk[0].store(1.0, Ordering::Relaxed); - d.opk[1].store(0.5, Ordering::Relaxed); - d.clip.store(true, Ordering::Relaxed); - d.vz_lv.store(0.3, Ordering::Relaxed); - d.mn_lv.store(0.5, Ordering::Relaxed); - d.fms.store(0.05, Ordering::Relaxed); - d.diff_disp.store(2.0, Ordering::Relaxed); - d.sat_db.store(2.0, Ordering::Relaxed); - d.sat_vz.store(0.3, Ordering::Relaxed); - } -} - -impl<'a> Gui<'a> { - pub(super) fn mask_in(&mut self) { - self.press = false; - self.down = false; - self.rpress = false; - self.wheel = 0; - self.mx = -1000.0; - self.my = -1000.0; - } - - pub(super) fn unmask_in(&mut self) { - let r = self.real_in; - self.press = r.0; - self.down = r.1; - self.rpress = r.2; - self.wheel = r.3; - self.mx = r.4; - self.my = r.5; - } - - pub(super) fn begin_edit(&mut self, index: Option) { - let (name, d, l) = match index.and_then(|i| self.themes.get(i)) { - Some(t) => (t.name.clone(), t.dark, t.light), - None => (String::new(), self.scheme_cols(self.pal, false), self.scheme_cols(self.pal, true)), - }; - let tri = |a: [f32; 9], k: usize| [a[k * 3], a[k * 3 + 1], a[k * 3 + 2]]; - self.edit = Some(ThemeEdit { - name, - col: [tri(d, 0), tri(d, 1), tri(d, 2), tri(l, 0), tri(l, 1), tri(l, 2)], - preview_light: self.light, - index, - picker: None, - osk: None, - }); - self.about = 0; - } - - pub(super) fn delete_user(&mut self, i: usize) { - if i >= self.themes.len() { - return; - } - self.themes.remove(i); - save_themes(&self.themes); - let cur = self.pal; - let gone = PALETTES.len() + i; - self.set_pal(if cur == gone { 0 } else if cur > gone { cur - 1 } else { cur }); - } - - fn save_edit(&mut self) { - let Some(e) = self.edit.take() else { return }; - let mut name = e.name.trim().to_string(); - if name.is_empty() { - name = format!("Custom {}", self.themes.len() + 1); - } - let taken = |s: &State, n: &str, skip: Option| { - PALETTES.iter().any(|p| p.0.eq_ignore_ascii_case(n)) - || s.themes.iter().enumerate().any(|(i, u)| Some(i) != skip && u.name.eq_ignore_ascii_case(n)) - }; - let base = name.clone(); - let mut k = 2; - while taken(self, &name, e.index) { - name = format!("{base} {k}"); - k += 1; - } - let t = UserTheme { name, dark: flat(&e.col[0..3]), light: flat(&e.col[3..6]) }; - let idx = match e.index.filter(|&i| i < self.themes.len()) { - Some(i) => { - self.themes[i] = t; - i - } - None => { - self.themes.push(t); - self.themes.len() - 1 - } - }; - save_themes(&self.themes); - self.set_pal(PALETTES.len() + idx); - self.about = 3; - self.ap_scroll = (PALETTES.len() + idx).saturating_sub(4); - } - - fn cancel_edit(&mut self) { - self.edit = None; - self.about = 3; - } - - /// One 62x38 editor cell: label top left, centred value. Returns true when clicked. - fn tc_box(&mut self, x: f32, y: f32, w: f32, h: f32, lbl: &str, val: &str, lit: bool, hot: bool) -> bool { - let clicked = self.hit(x, y, w, h) && self.press; - self.setc(hot); - if lit { - self.cv.fill(x, y, w, h); - self.cv.setbg(); - } else { - self.cv.boxr(x, y, w, h); - } - self.cv.set_font(1); - self.cv.text(x + 3.0, y + 3.0, lbl); - self.cv.set_font(2); - self.cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, val); - self.setc(false); - clicked - } - - /// Large check mark (save) or X (cancel) button. - fn tc_icon(&mut self, x: f32, y: f32, w: f32, h: f32, check: bool, lit: bool) -> bool { - let clicked = self.hit(x, y, w, h) && self.press; - self.setc(false); - if lit { - self.cv.fill(x, y, w, h); - self.cv.setbg(); - } else { - self.cv.boxr(x, y, w, h); - } - let (cx, cy) = ((x + w * 0.5).floor(), (y + h * 0.5).floor()); - for d in 0..4 { - let o = d as f32 - 1.5; - if check { - self.cv.line(cx - 11.0 + o, cy + 1.0, cx - 4.0 + o, cy + 8.0); - self.cv.line(cx - 4.0 + o, cy + 8.0, cx + 11.0 + o, cy - 9.0); - } else { - self.cv.line(cx - 9.0 + o, cy - 9.0, cx + 9.0 + o, cy + 9.0); - self.cv.line(cx - 9.0 + o, cy + 9.0, cx + 9.0 + o, cy - 9.0); - } - } - self.setc(false); - clicked - } - - fn tc_swatch(&mut self, x: f32, y: f32, slot: usize, interactive: bool) { - let (w, h) = (62.0, 38.0); - let Some(e) = &self.edit else { return }; - let col = e.col[slot]; - let hot = e.picker.as_ref().map(|p| p.slot == slot).unwrap_or(false); - let clicked = interactive && self.hit(x, y, w, h) && self.press; - self.setc(hot); - self.cv.boxr(x, y, w, h); - self.cv.set_font(1); - self.cv.text(x + 3.0, y + 3.0, SLOT_SHORT[slot]); - self.setc(false); - self.cv.boxr(x + 3.0, y + 15.0, w - 6.0, h - 18.0); - self.cv.setrgb(col); - self.cv.fill(x + 4.0, y + 16.0, w - 8.0, h - 20.0); - self.cv.setrgb(contrast(col)); - self.cv.textc(x + 3.0, y + 20.0, w - 6.0, &format!("#{}", hex6(col))); - self.setc(false); - if clicked { - self.press = false; - let (h_, s_, v_) = rgb_to_hsv(col); - if let Some(e) = &mut self.edit { - e.preview_light = slot >= 3; - e.picker = Some(Picker { slot, old: col, h: h_, s: s_, v: v_, drag: 0 }); - } - } - } - - /// The comp-settings area of the dummy page: theme name, dark and light swatches, preview switch, save / cancel. - pub(super) fn theme_cells(&mut self) { - let interactive = self.edit.as_ref().map(|e| e.picker.is_none() && e.osk.is_none()).unwrap_or(false); - let keep = self.real_in; - if interactive { - self.unmask_in(); - } - let xs = [152.0, 220.0, 288.0, 356.0]; - let ys = [196.0, 240.0, 284.0]; - for k in 0..3 { - self.tc_swatch(xs[k], ys[0], k, interactive); - self.tc_swatch(xs[k], ys[1], 3 + k, interactive); - } - let Some(e) = &self.edit else { return }; - let pl = e.preview_light; - let name = e.name.clone(); - - if self.tc_box(xs[3], ys[0], 62.0, 38.0, "PREVIEW", if pl { "LIGHT" } else { "DARK" }, false, false) && interactive { - self.press = false; - if let Some(e) = &mut self.edit { - e.preview_light = !e.preview_light; - } - } - if self.tc_box(xs[3], ys[1], 62.0, 38.0, "AUTO", "LIGHT", false, false) && interactive { - self.press = false; - if let Some(e) = &mut self.edit { - // light = dark with BG and UI swapped, same accent - e.col[3] = e.col[1]; - e.col[4] = e.col[0]; - e.col[5] = e.col[2]; - } - } - - // name field (two cells wide) - let shown = if name.is_empty() { "Custom".to_string() } else { name.clone() }; - if self.tc_box(xs[0], ys[2], 130.0, 38.0, "THEME NAME", &shown, false, false) && interactive { - self.press = false; - if let Some(e) = &mut self.edit { - e.osk = Some(Osk { kind: 0, text: name.clone() }); - } - } - if self.tc_icon(xs[2], ys[2], 62.0, 38.0, true, true) && interactive { - self.press = false; - self.save_edit(); - } else if self.edit.is_some() && self.tc_icon(xs[3], ys[2], 62.0, 38.0, false, false) && interactive { - self.press = false; - self.cancel_edit(); - } - if interactive { - self.real_in = keep; - self.mask_in(); - } - } - - /// On-screen keyboard over the compressor plot (REAPER swallows typing in plug-in windows as hotkeys). Capital letters and - /// digits only; in hex mode just 0-9 and A-F are enabled. - pub(super) fn theme_osk(&mut self) { - let Some(e) = &self.edit else { return }; - let Some(o) = &e.osk else { return }; - let (kind, mut text) = (o.kind, o.text.clone()); - let (x, y, w, h) = (152.0, 56.0, 266.0, 128.0); - let max = if kind == 0 { 16 } else { 6 }; - self.setc(false); - self.cv.setbg(); - self.cv.fill(x, y, w, h); - self.setc(false); - self.cv.boxr(x, y, w, h); - self.cv.set_font(1); - self.cv.text(x + 8.0, y + 5.0, if kind == 0 { "THEME NAME" } else { "HEX COLOUR" }); - self.cv.boxr(x + 8.0, y + 16.0, w - 16.0, 14.0); - let caret = if blink(self.now) { "_" } else { " " }; - let shown = if kind == 1 { format!("#{text}{caret}") } else { format!("{text}{caret}") }; - self.cv.text(x + 12.0, y + 19.0, &shown); - let (pitch, kh) = (26.0, 15.0); - let x0 = x + ((w - (10.0 * pitch - 2.0)) * 0.5).floor(); - let prev_dk = self.dk; - let mut close = false; - let mut accept = false; - let rows = ["1234567890", "QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"]; - let offs = [0.0, 0.0, 0.5, 1.0]; - for (r, row) in rows.iter().enumerate() { - let ky = y + 34.0 + r as f32 * 17.0; - for (i, c) in row.chars().enumerate() { - let kx = x0 + (offs[r] + i as f32) * pitch; - let ok = kind == 0 || c.is_ascii_hexdigit(); - self.set_dk(if ok { prev_dk } else { 0.35 }); - let s = c.to_string(); - if self.btn(kx, ky, pitch - 2.0, kh, &s, 0) && ok && text.chars().count() < max { - text.push(c); - } - } - } - self.set_dk(prev_dk); - let ky = y + 34.0 + 4.0 * 17.0; - if self.btn(x0 + 8.0 * pitch, y + 34.0 + 3.0 * 17.0, 2.0 * pitch - 2.0, kh, "DEL", 0) { - text.pop(); - } - self.set_dk(if kind == 0 { prev_dk } else { 0.35 }); - if self.btn(x0, ky, 4.0 * pitch - 2.0, kh, "SPACE", 0) && kind == 0 && text.chars().count() < max { - text.push(' '); - } - self.set_dk(prev_dk); - if self.btn(x0 + 4.0 * pitch, ky, 3.0 * pitch - 2.0, kh, "OK", 1) { - accept = true; - } - if self.btn(x0 + 7.0 * pitch, ky, 3.0 * pitch - 2.0, kh, "CANCEL", 0) { - close = true; - } - if accept { - if kind == 0 { - if let Some(e) = &mut self.edit { - e.name = text.trim().to_string(); - e.osk = None; - } - return; - } - if let (Some(c), Some(e)) = (parse6(&text), self.edit.as_mut()) { - if let Some(p) = e.picker.as_mut() { - let (h_, s_, v_) = rgb_to_hsv(c); - p.h = if s_ > 0.0 { h_ } else { p.h }; - p.s = s_; - p.v = v_; - } - e.osk = None; - } - return; - } - if let Some(e) = &mut self.edit { - if close { - e.osk = None; - } else if let Some(o) = &mut e.osk { - o.text = text; - } - } - } - - /// Colour picker overlay (over the compressor plot): saturation / value square, hue strip, hex field, OK / CANCEL. - /// Edits the slot live, so the whole dummy page re-colours while you drag. - pub(super) fn theme_picker(&mut self) { - let Some(e) = &self.edit else { return }; - let Some(p) = &e.picker else { return }; - let slot = p.slot; - let (x, y, w, h) = (152.0, 56.0, 266.0, 128.0); - self.setc(false); - self.cv.setbg(); - self.cv.fill(x, y, w, h); - self.setc(false); - self.cv.boxr(x, y, w, h); - self.cv.set_font(1); - self.cv.text(x + 8.0, y + 6.0, &format!("{} (live preview)", SLOT_NAMES[slot])); - - let (sx, sy, sw, sh_) = (x + 8.0, y + 20.0, 120.0, 100.0); - let (hx, hw) = (sx + sw + 8.0, 14.0); - let (mx, my, down, press) = (self.mx, self.my, self.down, self.press); - let mut close_ok = false; - let mut close_cancel = false; - let hit = |ax: f32, ay: f32, aw: f32, ah: f32| mx >= ax && mx < ax + aw && my >= ay && my < ay + ah; - let mut ask_hex = false; - let idle = true; - - let Some(e) = &mut self.edit else { return }; - let Some(p) = &mut e.picker else { return }; - if press && idle { - if hit(sx, sy, sw, sh_) { - p.drag = 1; - } else if hit(hx, sy, hw, sh_) { - p.drag = 2; - } else if hit(hx + hw + 8.0, sy + 42.0, 106.0, 16.0) { - ask_hex = true; - } - } - if !down { - p.drag = 0; - } - if p.drag == 1 { - p.s = ((mx - sx) / (sw - 1.0)).clamp(0.0, 1.0); - p.v = (1.0 - (my - sy) / (sh_ - 1.0)).clamp(0.0, 1.0); - } else if p.drag == 2 { - p.h = ((my - sy) / (sh_ - 1.0)).clamp(0.0, 1.0); - } - let cur = hsv_to_rgb(p.h, p.s, p.v); - let ph = p.h; - let (ps, pv) = (p.s, p.v); - let old = p.old; - let hexshow = hex6(cur); - e.col[slot] = cur; - - // SV square (4 px cells) and hue strip - let cell = 4.0; - for iy in 0..(sh_ / cell) as i32 { - for ix in 0..(sw / cell) as i32 { - let s_ = (ix as f32 + 0.5) * cell / sw; - let v_ = 1.0 - (iy as f32 + 0.5) * cell / sh_; - self.cv.setrgb(hsv_to_rgb(ph, s_, v_)); - self.cv.fill(sx + ix as f32 * cell, sy + iy as f32 * cell, cell, cell); - } - } - for iy in 0..(sh_ / cell) as i32 { - self.cv.setrgb(hsv_to_rgb((iy as f32 + 0.5) * cell / sh_, 1.0, 1.0)); - self.cv.fill(hx, sy + iy as f32 * cell, hw, cell); - } - self.setc(false); - self.cv.boxr(sx - 1.0, sy - 1.0, sw + 2.0, sh_ + 2.0); - self.cv.boxr(hx - 1.0, sy - 1.0, hw + 2.0, sh_ + 2.0); - // markers: a ring on the square, a bar on the strip (contrast against what is under them) - let (cx, cy) = (sx + ps * (sw - 1.0), sy + (1.0 - pv) * (sh_ - 1.0)); - self.cv.setrgb(contrast(cur)); - self.cv.boxr((cx - 3.0).floor(), (cy - 3.0).floor(), 7.0, 7.0); - self.cv.setrgb(contrast(hsv_to_rgb(ph, 1.0, 1.0))); - self.cv.fill(hx, (sy + ph * (sh_ - 1.0)).floor() - 1.0, hw, 3.0); - - // old / new, hex, RGB, buttons - let rx = hx + hw + 8.0; - self.setc(false); - self.cv.text(rx, sy, "OLD"); - self.cv.text(rx + 56.0, sy, "NEW"); - self.cv.setrgb(old); - self.cv.fill(rx, sy + 10.0, 50.0, 22.0); - self.cv.setrgb(cur); - self.cv.fill(rx + 56.0, sy + 10.0, 50.0, 22.0); - self.setc(false); - self.cv.boxr(rx - 1.0, sy + 9.0, 52.0, 24.0); - self.cv.boxr(rx + 55.0, sy + 9.0, 52.0, 24.0); - self.setc(false); - self.cv.boxr(rx, sy + 42.0, 106.0, 16.0); - self.cv.text(rx + 4.0, sy + 46.0, &format!("#{hexshow} EDIT")); - self.setc(false); - let b = |v: f32| (v * 255.0 + 0.5) as u8; - self.cv.text(rx, sy + 66.0, &format!("R{:03} G{:03} B{:03}", b(cur[0]), b(cur[1]), b(cur[2]))); - let ok = self.btn(rx, sy + 84.0, 50.0, 16.0, "OK", 1); - let cn = self.btn(rx + 56.0, sy + 84.0, 50.0, 16.0, "CANCEL", 0); - if ask_hex { - if let Some(e) = &mut self.edit { - e.osk = Some(Osk { kind: 1, text: hexshow.clone() }); - } - } - if ok && press { - close_ok = true; - } - if cn && press { - close_cancel = true; - } - if close_cancel { - if let Some(e) = &mut self.edit { - e.col[slot] = old; - e.picker = None; - } - } else if close_ok { - if let Some(e) = &mut self.edit { - e.picker = None; - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn theme_encoding_roundtrips_and_hsv_inverts() { - let t = UserTheme { name: "My Theme".into(), dark: [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0], light: [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.2, 0.4, 1.0] }; - let r = decode(&encode(&t)).unwrap(); - assert_eq!(r.name, "My Theme"); - for k in 0..9 { - assert!((r.dark[k] - t.dark[k]).abs() < 0.003 && (r.light[k] - t.light[k]).abs() < 0.003); - } - assert!(decode("x|zz").is_none()); - let c = [0.2, 0.6, 0.9]; - let (h, s, v) = rgb_to_hsv(c); - let b = hsv_to_rgb(h, s, v); - assert!((0..3).all(|i| (b[i] - c[i]).abs() < 1e-5)); - } -} - diff --git a/rust/satcomp-plugin/src/lib.rs b/rust/satcomp-plugin/src/lib.rs index 61fdb7b..1aa6702 100644 --- a/rust/satcomp-plugin/src/lib.rs +++ b/rust/satcomp-plugin/src/lib.rs @@ -20,12 +20,15 @@ pub struct Shared { pub opk: [AtomicF32; 2], pub clip: AtomicBool, pub gr_pk: AtomicF32, + /// peak limiter gain reduction (dB, positive), accumulated like `gr_pk` + pub lim_gr_pk: AtomicF32, + /// post-saturator peak (linear), accumulated and consumed like `opk` + pub sat_pk: AtomicF32, pub fms: AtomicF32, pub vz_lv: AtomicF32, pub sat_vz: AtomicF32, pub diff_disp: AtomicF32, pub sat_db: AtomicF32, - pub bg: AtomicF32, pub out_meas: AtomicBool, pub out_mt: AtomicF32, pub sat_meas: AtomicBool, @@ -55,12 +58,13 @@ impl Shared { opk: [AtomicF32::new(0.0), AtomicF32::new(0.0)], clip: AtomicBool::new(false), gr_pk: AtomicF32::new(0.0), + lim_gr_pk: AtomicF32::new(0.0), + sat_pk: AtomicF32::new(0.0), fms: AtomicF32::new(1e-9), vz_lv: AtomicF32::new(0.0), sat_vz: AtomicF32::new(0.0), diff_disp: AtomicF32::new(0.0), sat_db: AtomicF32::new(0.0), - bg: AtomicF32::new(1.0), out_meas: AtomicBool::new(false), out_mt: AtomicF32::new(0.0), sat_meas: AtomicBool::new(false), @@ -89,6 +93,7 @@ pub struct SatComp { last_latency: u32, /// last custom curve read on the audio thread (reused while the UI holds the curve lock) last_curve: satcomp_dsp::shapers::Curve, + last_asym: [f64; satcomp_dsp::shapers::SHAPER_COUNT], } impl Default for SatComp { @@ -97,7 +102,7 @@ impl Default for SatComp { let mut engine = Engine::new(48000.0); engine.tap = shared.tap.clone(); engine.scope = shared.scope.clone(); - Self { params: Arc::new(SatCompParams::default()), shared, engine, last_latency: u32::MAX, last_curve: satcomp_dsp::shapers::Curve::linear() } + Self { params: Arc::new(SatCompParams::default()), shared, engine, last_latency: u32::MAX, last_curve: satcomp_dsp::shapers::Curve::linear(), last_asym: [100.0; satcomp_dsp::shapers::SHAPER_COUNT] } } } @@ -160,7 +165,7 @@ impl Plugin for SatComp { engine.tap = self.shared.tap.clone(); engine.scope = self.shared.scope.clone(); engine.match_trim = self.params.match_trim.load(Ordering::Relaxed) as f64; - engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve)); + engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve, &mut self.last_asym)); self.engine = engine; } @@ -171,7 +176,7 @@ impl Plugin for SatComp { context: &mut impl ProcessContext, ) -> ProcessStatus { let sh = &self.shared; - self.engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve)); + self.engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve, &mut self.last_asym)); let lat = self.engine.latency(); if lat != self.last_latency { self.last_latency = lat; @@ -209,13 +214,16 @@ impl Plugin for SatComp { } sh.gr_pk.fetch_max(e.gr_pk as f32, Ordering::Relaxed); e.gr_pk = 0.0; + sh.lim_gr_pk.fetch_max(e.lim_gr_pk as f32, Ordering::Relaxed); + e.lim_gr_pk = 0.0; + sh.sat_pk.fetch_max(e.sat_pk as f32, Ordering::Relaxed); + e.sat_pk = 0.0; sh.fms.store(e.fms as f32, Ordering::Relaxed); sh.vz_lv.store(e.vz_lv as f32, Ordering::Relaxed); sh.mn_lv.store(e.mn_lv as f32, Ordering::Relaxed); sh.sat_vz.store(e.sat_vz as f32, Ordering::Relaxed); sh.diff_disp.store(e.diff_disp as f32, Ordering::Relaxed); sh.sat_db.store(e.sat_db as f32, Ordering::Relaxed); - sh.bg.store(e.bg_gain() as f32, Ordering::Relaxed); sh.out_meas.store(e.out_matching(), Ordering::Relaxed); sh.out_mt.store(e.out_match_progress() as f32, Ordering::Relaxed); sh.sat_meas.store(e.sat_matching(), Ordering::Relaxed); diff --git a/rust/satcomp-plugin/src/params.rs b/rust/satcomp-plugin/src/params.rs index c22ff62..a8bbe19 100644 --- a/rust/satcomp-plugin/src/params.rs +++ b/rust/satcomp-plugin/src/params.rs @@ -2,7 +2,7 @@ use nih_plug::prelude::*; use nih_plug_egui::EguiState; -use satcomp_dsp::shapers::Curve; +use satcomp_dsp::shapers::{asym_from, Curve, SHAPER_COUNT}; use satcomp_dsp::{EqBandParams, EqStageParams}; use std::sync::atomic::{AtomicBool, AtomicI32}; use std::sync::Arc; @@ -10,13 +10,13 @@ use std::sync::Arc; /// (slider number, id, min, max, default, step) for every parameter; slider numbers follow SatComp.jsfx. pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[ (1, "shape", 0.0, 14.0, 0.0), - (2, "drive", 0.0, 100.0, 25.0), + (2, "drive", 0.0, 100.0, 0.0), (3, "bias", -100.0, 100.0, 0.0), (4, "sat_hp", 20.0, 2000.0, 20.0), (5, "sat_lp", 200.0, 20000.0, 20000.0), (6, "tone", 1000.0, 20000.0, 20000.0), (7, "os", 0.0, 2.0, 0.0), - (8, "thresh", -40.0, 0.0, -18.0), + (8, "thresh", -40.0, 0.0, 0.0), (9, "ratio", 1.0, 20.0, 4.0), (10, "attack", 0.05, 100.0, 10.0), (11, "release", 5.0, 2000.0, 150.0), @@ -73,6 +73,7 @@ pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[ (65, "sc_hp", 20.0, 2000.0, 20.0), (66, "sc_lp", 200.0, 20000.0, 20000.0), (67, "sc_mix", 0.0, 100.0, 100.0), + (68, "lim_on", 0.0, 1.0, 1.0), ]; #[derive(Params)] @@ -103,6 +104,9 @@ pub struct SatCompParams { /// User-drawn waveshaper curve (points on [-1,1]^2, shaper 14 "Custom"); saved with the project and presets. #[persist = "custom-curve"] pub custom_curve: Arc>>, + /// ASYM per waveshaper (0..100 %, index = shaper); saved with the project and presets (absent = all 100 %). + #[persist = "asym"] + pub asym: Arc>>, /// Out-stage gain-match trim (dB) written by the 3 s measurement; saved with the project. #[persist = "match-trim"] pub match_trim: Arc, @@ -234,29 +238,42 @@ pub struct SatCompParams { pub sc_lp: FloatParam, #[id = "sc_mix"] pub sc_mix: FloatParam, + #[id = "lim_on"] + pub lim_on: BoolParam, } impl Default for SatCompParams { + /// A new instance starts from the shared defaults file (the host then restores a saved project's own look over this). fn default() -> Self { + Self::from_defaults(satcomp_ui::appearance::load_defaults_for("satcomp")) + } +} + +impl SatCompParams { + pub fn from_defaults(d: Option) -> Self { Self { - editor_state: EguiState::from_size(700, 420), + editor_state: { + let (w, h) = d.as_ref().map(|d| d.size((560.0, 336.0))).unwrap_or((700, 420)); + EguiState::from_size(w, h) + }, palette: Arc::new(AtomicI32::new(0)), - palette_v2: Arc::new(AtomicI32::new(-1)), - light: Arc::new(AtomicBool::new(false)), - font: Arc::new(AtomicI32::new(0)), + palette_v2: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.pal_index()).unwrap_or(-1))), + light: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.light).unwrap_or(false))), + font: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.face_index()).unwrap_or(0))), scope: Arc::new(AtomicI32::new((5 << 4) | (2 << 8))), - custom_theme: Arc::new(parking_lot::Mutex::new(String::new())), + custom_theme: Arc::new(parking_lot::Mutex::new(d.as_ref().map(|d| d.theme.clone()).unwrap_or_default())), preset_name: Arc::new(parking_lot::Mutex::new(String::new())), custom_curve: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])), + asym: Arc::new(parking_lot::Mutex::new(Vec::new())), match_trim: Arc::new(AtomicF32::new(0.0)), shape: IntParam::new("Shape", 0, IntRange::Linear { min: 0, max: 14 }), - drive: FloatParam::new("Drive", 25.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + drive: FloatParam::new("Drive", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), bias: FloatParam::new("Bias", 0.0, FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), sat_hp: FloatParam::new("Sat HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), sat_lp: FloatParam::new("Sat LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), tone: FloatParam::new("Tone", 20000.0, FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), os: IntParam::new("Oversampling", 0, IntRange::Linear { min: 0, max: 2 }), - thresh: FloatParam::new("Thresh", -18.0, FloatRange::Linear { min: -40.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + thresh: FloatParam::new("Thresh", 0.0, FloatRange::Linear { min: -40.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), ratio: FloatParam::new("Ratio", 4.0, FloatRange::Linear { min: 1.0, max: 20.0 }).with_step_size(0.1), attack: FloatParam::new("Attack", 10.0, FloatRange::Linear { min: 0.05, max: 100.0 }).with_unit(" ms").with_step_size(0.01), release: FloatParam::new("Release", 150.0, FloatRange::Linear { min: 5.0, max: 2000.0 }).with_unit(" ms").with_step_size(1.0), @@ -313,6 +330,7 @@ impl Default for SatCompParams { sc_hp: FloatParam::new("SC HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), sc_lp: FloatParam::new("SC LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), sc_mix: FloatParam::new("Key Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lim_on: BoolParam::new("Limiter", true), } } } @@ -323,26 +341,34 @@ impl SatCompParams { Curve::from_points(&self.custom_curve.lock()) } + /// ASYM per shaper, sanitised (short / missing = 100 %). + pub fn asym_snapshot(&self) -> [f64; SHAPER_COUNT] { + asym_from(&self.asym.lock()) + } + /// Snapshot for the DSP engine (UI side: may wait briefly for the curve lock). pub fn to_dsp(&self) -> satcomp_dsp::Params { - self.to_dsp_with(self.curve_snapshot()) + self.to_dsp_with(self.curve_snapshot(), self.asym_snapshot()) } /// Audio-thread snapshot: never blocks on the curve lock. While the UI holds it the previous curve is reused. - pub fn to_dsp_rt(&self, last: &mut satcomp_dsp::shapers::Curve) -> satcomp_dsp::Params { + pub fn to_dsp_rt(&self, last: &mut satcomp_dsp::shapers::Curve, last_asym: &mut [f64; SHAPER_COUNT]) -> satcomp_dsp::Params { if let Some(g) = self.custom_curve.try_lock() { *last = satcomp_dsp::shapers::Curve::from_points(&g); } - self.to_dsp_with(*last) + if let Some(g) = self.asym.try_lock() { + *last_asym = asym_from(&g); + } + self.to_dsp_with(*last, *last_asym) } - fn to_dsp_with(&self, curve: satcomp_dsp::shapers::Curve) -> satcomp_dsp::Params { + fn to_dsp_with(&self, curve: satcomp_dsp::shapers::Curve, asym: [f64; SHAPER_COUNT]) -> satcomp_dsp::Params { let stage = |bands: [(&IntParam, &FloatParam, &FloatParam, &FloatParam); 3], tilt: &FloatParam, pivot: &FloatParam, og: &FloatParam| EqStageParams { bands: [0, 1, 2].map(|i| EqBandParams { ty: bands[i].0.value() as f64, freq: bands[i].1.value() as f64, gain: bands[i].2.value() as f64, q: bands[i].3.value() as f64 }), tilt: tilt.value() as f64, pivot: pivot.value() as f64, out_gain: og.value() as f64, }; satcomp_dsp::Params { - shape: self.shape.value(), curve, drive: self.drive.value() as f64, bias: self.bias.value() as f64, + shape: self.shape.value(), curve, asym, drive: self.drive.value() as f64, bias: self.bias.value() as f64, sat_hp: self.sat_hp.value() as f64, sat_lp: self.sat_lp.value() as f64, tone: self.tone.value() as f64, os: self.os.value(), thresh: self.thresh.value() as f64, ratio: self.ratio.value() as f64, attack: self.attack.value() as f64, release: self.release.value() as f64, speed: self.speed.value() as f64, knee: self.knee.value() as f64, @@ -354,6 +380,7 @@ impl SatCompParams { lookahead_ms: self.lookahead.value() as f64, eq_pre_bypass: self.eq_pre_bypass.value(), eq_post_bypass: self.eq_post_bypass.value(), eq_module_bypass: self.eq_module_bypass.value(), sc_on: self.sc_on.value(), sc_gain: self.sc_gain.value() as f64, sc_hp: self.sc_hp.value() as f64, sc_lp: self.sc_lp.value() as f64, sc_mix: self.sc_mix.value() as f64, + lim_on: self.lim_on.value(), } } @@ -424,6 +451,7 @@ impl SatCompParams { 65 => self.sc_hp.as_ptr(), 66 => self.sc_lp.as_ptr(), 67 => self.sc_mix.as_ptr(), + 68 => self.lim_on.as_ptr(), _ => return None, }) } diff --git a/rust/satcomp-plugin/src/presets.rs b/rust/satcomp-plugin/src/presets.rs index 95f8615..e24c009 100644 --- a/rust/satcomp-plugin/src/presets.rs +++ b/rust/satcomp-plugin/src/presets.rs @@ -23,11 +23,14 @@ pub struct Preset { /// Custom waveshaper curve points (absent in older presets = linear). Backward compatible: version stays 1. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub curve: Vec<(f32, f32)>, + /// ASYM (0..100 %) per waveshaper (absent / empty = all 100 %). Backward compatible: version stays 1. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asym: Vec, } impl Preset { pub fn new(name: &str, params: BTreeMap) -> Self { - Self { format: "satcomp-preset".into(), version: 1, name: name.into(), params, curve: Vec::new() } + Self { format: "satcomp-preset".into(), version: 1, name: name.into(), params, curve: Vec::new(), asym: Vec::new() } } /// All defaults. @@ -78,6 +81,10 @@ pub fn user_dir() -> Option { /// (display name, path) of the user presets, sorted case-insensitively. pub fn scan_user() -> Vec<(String, PathBuf)> { let mut v = Vec::new(); + // tests are hermetic: the machine's own user presets must not change what the editor lists (the UI golden steps through them) + if cfg!(test) { + return v; + } if let Some(d) = user_dir() { if let Ok(rd) = std::fs::read_dir(d) { for e in rd.flatten() { @@ -144,12 +151,27 @@ mod tests { fn init_roundtrips_and_excludes_performance_switches() { let p = Preset::init(); assert!(!p.params.contains_key("bypass") && !p.params.contains_key("gain_match")); - assert_eq!(p.params["drive"], 25.0); + assert_eq!(p.params["drive"], 0.0); + assert_eq!(p.params["thresh"], 0.0); + assert_eq!(p.params["lim_on"], 1.0); // the limiter switch is stored with presets let q = Preset::from_json(&p.to_json()).unwrap(); assert_eq!(q.params, p.params); assert!(Preset::from_json("{\"format\":\"nope\"}").is_none()); } + #[test] + fn asym_roundtrips_and_old_presets_load_without_it() { + let mut p = Preset::init(); + assert!(!p.to_json().contains("asym")); + p.asym = vec![100.0, 35.0]; + let q = Preset::from_json(&p.to_json()).unwrap(); + assert_eq!(q.asym, p.asym); + let a = satcomp_dsp::shapers::asym_from(&q.asym); + assert_eq!((a[0], a[1], a[14]), (100.0, 35.0, 100.0)); + let old = r#"{"format":"satcomp-preset","version":1,"name":"x","params":{}}"#; + assert!(Preset::from_json(old).unwrap().asym.is_empty()); + } + #[test] fn curve_roundtrips_and_old_presets_load_without_it() { let mut p = Preset::init(); diff --git a/rust/satcomp-ui/Cargo.toml b/rust/satcomp-ui/Cargo.toml new file mode 100644 index 0000000..9769f25 --- /dev/null +++ b/rust/satcomp-ui/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "satcomp-ui" +version = "0.5.2" +edition = "2021" +license = "GPL-3.0-or-later" +publish = false + +# Shared egui UI toolkit for the SatComp plug-in family: drawing canvas on the logical grid, colour schemes, the embedded +# UI fonts, FFT helper. No plug-in specific state lives here. +[dependencies] +nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git" } +nih_plug_egui = { path = "../vendor/nih_plug_egui" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/rust/satcomp-ui/assets/fonts/AnonymousPro-Regular.ttf b/rust/satcomp-ui/assets/fonts/AnonymousPro-Regular.ttf new file mode 100755 index 0000000..a98da85 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/AnonymousPro-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/CourierPrime-Regular.ttf b/rust/satcomp-ui/assets/fonts/CourierPrime-Regular.ttf new file mode 100755 index 0000000..4af1ff5 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/CourierPrime-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/DMMono-Regular.ttf b/rust/satcomp-ui/assets/fonts/DMMono-Regular.ttf new file mode 100755 index 0000000..7efe813 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/DMMono-Regular.ttf differ diff --git a/rust/satcomp-plugin/assets/fonts/Doto-Black.ttf b/rust/satcomp-ui/assets/fonts/Doto-Black.ttf similarity index 100% rename from rust/satcomp-plugin/assets/fonts/Doto-Black.ttf rename to rust/satcomp-ui/assets/fonts/Doto-Black.ttf diff --git a/rust/satcomp-plugin/assets/fonts/FiraCode-Regular.ttf b/rust/satcomp-ui/assets/fonts/FiraCode-Regular.ttf similarity index 100% rename from rust/satcomp-plugin/assets/fonts/FiraCode-Regular.ttf rename to rust/satcomp-ui/assets/fonts/FiraCode-Regular.ttf diff --git a/rust/satcomp-plugin/assets/fonts/GeistMono-Regular.ttf b/rust/satcomp-ui/assets/fonts/GeistMono-Regular.ttf similarity index 100% rename from rust/satcomp-plugin/assets/fonts/GeistMono-Regular.ttf rename to rust/satcomp-ui/assets/fonts/GeistMono-Regular.ttf diff --git a/rust/satcomp-ui/assets/fonts/Inconsolata-Regular.ttf b/rust/satcomp-ui/assets/fonts/Inconsolata-Regular.ttf new file mode 100755 index 0000000..ff1e6bb Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/Inconsolata-Regular.ttf differ diff --git a/rust/satcomp-plugin/assets/fonts/JetBrainsMono-Regular.ttf b/rust/satcomp-ui/assets/fonts/JetBrainsMono-Regular.ttf similarity index 100% rename from rust/satcomp-plugin/assets/fonts/JetBrainsMono-Regular.ttf rename to rust/satcomp-ui/assets/fonts/JetBrainsMono-Regular.ttf diff --git a/rust/satcomp-plugin/assets/fonts/OxygenMono-Regular.ttf b/rust/satcomp-ui/assets/fonts/OxygenMono-Regular.ttf similarity index 100% rename from rust/satcomp-plugin/assets/fonts/OxygenMono-Regular.ttf rename to rust/satcomp-ui/assets/fonts/OxygenMono-Regular.ttf diff --git a/rust/satcomp-plugin/assets/fonts/RobotoMono-Regular.ttf b/rust/satcomp-ui/assets/fonts/RobotoMono-Regular.ttf similarity index 100% rename from rust/satcomp-plugin/assets/fonts/RobotoMono-Regular.ttf rename to rust/satcomp-ui/assets/fonts/RobotoMono-Regular.ttf diff --git a/rust/satcomp-ui/assets/fonts/VictorMono-Regular.ttf b/rust/satcomp-ui/assets/fonts/VictorMono-Regular.ttf new file mode 100755 index 0000000..2ed2fa5 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/VictorMono-Regular.ttf differ diff --git a/rust/satcomp-ui/src/appearance.rs b/rust/satcomp-ui/src/appearance.rs new file mode 100644 index 0000000..d735e31 --- /dev/null +++ b/rust/satcomp-ui/src/appearance.rs @@ -0,0 +1,1550 @@ +//! Colour themes and the About / Appearance / Changelog pages, shared by the plug-ins. +//! +//! * `AppState`: scheme list (built-in `PALETTES` + user themes from `themes.json`), the theme-editor state and the +//! About-page scroll state. Plug-ins keep one in their GUI state. +//! * `AppearanceUi`: a trait over `Widgets` whose provided methods draw the pages and run the editor (swatches, colour +//! picker, on-screen keyboard). The plug-in supplies the few things that are its own: where the scheme / light flag / +//! font are stored, the page rectangles, the About copy and the signal-flow drawing. +//! +//! Themes live in one file (`SatComp/themes.json` beside the preset folders), so a theme made in one plug-in shows in all. + +use crate::canvas::{FONT_NAMES, PALETTES}; +use crate::kit::Widgets; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// [BG rgb, UI rgb, ACCENT rgb] per mode, same layout as `PALETTES`. +#[derive(Clone, Serialize, Deserialize, PartialEq)] +pub struct UserTheme { + pub name: String, + pub dark: [f32; 9], + pub light: [f32; 9], +} + +const SLOT_NAMES: [&str; 6] = ["DARK BG", "DARK UI", "DARK ACCENT", "LIGHT BG", "LIGHT UI", "LIGHT ACCENT"]; +const SLOT_SHORT: [&str; 6] = ["DARK BG", "DARK UI", "DARK ACC", "LIGHT BG", "LIGHT UI", "LIGHT ACC"]; + +/// The folder that holds `themes.json`, `defaults.json` and the preset folders. +fn data_dir() -> Option { + // test / portable override + if let Some(d) = std::env::var_os("SATCOMP_DATA_DIR") { + return Some(PathBuf::from(d)); + } + #[cfg(target_os = "macos")] + let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support")); + #[cfg(windows)] + let base = std::env::var_os("APPDATA").map(PathBuf::from); + #[cfg(not(any(target_os = "macos", windows)))] + let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")); + base.map(|b| b.join("SatComp")) +} + +fn themes_path() -> Option { + data_dir().map(|d| d.join("themes.json")) +} + +fn defaults_path() -> Option { + data_dir().map(|d| d.join("defaults.json")) +} + +/// One plug-in's own default (`defaults-.json`), which wins over the global `defaults.json` for that plug-in. +fn plugin_defaults_path(key: &str) -> Option { + data_dir().map(|d| d.join(format!("defaults-{key}.json"))) +} + +/// The look a NEW plug-in instance starts with, shared by all the plug-ins (`SatComp/defaults.json`). A saved project keeps +/// its own look; this only seeds fresh instances. Absent file = factory look. +#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)] +pub struct Defaults { + /// scheme index (`PALETTES.len()` = a user theme, given by `theme`) + pub pal: i32, + /// `encode`d user theme when `pal` is a user theme, else empty + pub theme: String, + pub light: bool, + pub face: i32, + /// spectrum / scope fill (plug-ins without the switch ignore it) + pub fill_solid: bool, + /// window scale relative to each plug-in's base size + pub scale: f32, +} + +impl Defaults { + /// Window size in logical pixels for a plug-in with this base size. + pub fn size(&self, base: (f32, f32)) -> (u32, u32) { + let s = self.scale.clamp(1.0, 2.5); + ((base.0 * s).round() as u32, (base.1 * s).round() as u32) + } + + /// Scheme index as stored in `palette-v2`, kept inside the table. + pub fn pal_index(&self) -> i32 { + self.pal.clamp(0, PALETTES.len() as i32) + } + + pub fn face_index(&self) -> i32 { + self.face.clamp(0, FONT_NAMES.len() as i32 - 1) + } +} + +fn read_defaults(p: Option) -> Option { + p.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()) +} + +fn write_defaults(p: Option, d: &Defaults) { + if let Some(p) = p { + if let Some(dir) = p.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(s) = serde_json::to_string_pretty(d) { + let _ = std::fs::write(p, s); + } + } +} + +/// The GLOBAL default (all plug-ins). +pub fn load_defaults() -> Option { + read_defaults(defaults_path()) +} + +pub fn save_defaults(d: &Defaults) { + write_defaults(defaults_path(), d); +} + +/// What a new instance of plug-in `key` ("satcomp", "satxcomp", "satlim") starts with: its own default if it has one, else +/// the global default, else `None` (the factory look). +pub fn load_defaults_for(key: &str) -> Option { + read_defaults(plugin_defaults_path(key)).or_else(load_defaults) +} + +pub fn save_defaults_for(key: &str, d: &Defaults) { + write_defaults(plugin_defaults_path(key), d); +} + +pub fn clear_defaults_for(key: &str) { + if let Some(p) = plugin_defaults_path(key) { + let _ = std::fs::remove_file(p); + } +} + +/// Write an embedded manual to the temp folder (`SatComp/`, rewritten when its size differs) and open it with the +/// default PDF viewer. If the file cannot be written the online manual folder is opened instead. +pub fn open_manual(name: &str, bytes: &[u8]) { + let dir = std::env::temp_dir().join("SatComp"); + let path = dir.join(name); + let ok = std::fs::create_dir_all(&dir).is_ok() + && (std::fs::metadata(&path).map(|m| m.len() == bytes.len() as u64).unwrap_or(false) || std::fs::write(&path, bytes).is_ok()); + open_target(&if ok { path.to_string_lossy().into_owned() } else { MANUAL_URL.to_string() }); +} + +/// Where the manuals live online (fallback of `open_manual`). +pub const MANUAL_URL: &str = "https://github.com/thomchantra/SatComp/tree/main/docs/manual"; + +/// Open a file or URL with the system's default application. +fn open_target(t: &str) { + #[cfg(target_os = "macos")] + let opener = "open"; + #[cfg(windows)] + let opener = "explorer"; + #[cfg(not(any(target_os = "macos", windows)))] + let opener = "xdg-open"; + let _ = std::process::Command::new(opener).arg(t).spawn(); +} + +/// Show a folder in the system file browser (created first, so a fresh install opens somewhere). +pub fn open_folder(dir: Option) { + let Some(dir) = dir else { return }; + let _ = std::fs::create_dir_all(&dir); + #[cfg(target_os = "macos")] + let opener = "open"; + #[cfg(windows)] + let opener = "explorer"; + #[cfg(not(any(target_os = "macos", windows)))] + let opener = "xdg-open"; + let _ = std::process::Command::new(opener).arg(&dir).spawn(); +} + +/// The folder with `themes.json` and `defaults.json` (shared by the three plug-ins). +pub fn settings_dir() -> Option { + data_dir() +} + +/// Remove the global default. +pub fn clear_defaults() { + if let Some(p) = defaults_path() { + let _ = std::fs::remove_file(p); + } +} + +/// A quick pseudo-random number from the clock (xorshift over the nanoseconds): good enough to roll a die. +fn rand_u32(salt: f64) -> u32 { + let ns = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos() as u64 ^ d.as_secs()).unwrap_or(1); + let mut x = ns ^ salt.to_bits() ^ 0x9E37_79B9_7F4A_7C15; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 16) as u32 +} + +/// Index of the built-in scheme called `name` (case-insensitive). +pub fn builtin_by_name(name: &str) -> Option { + PALETTES.iter().position(|p| p.0.eq_ignore_ascii_case(name.trim())) +} + +pub fn load_themes() -> Vec { + themes_path() + .and_then(|p| std::fs::read_to_string(p).ok()) + .and_then(|s| serde_json::from_str::>(&s).ok()) + .unwrap_or_default() +} + +fn save_themes(v: &[UserTheme]) { + if let Some(p) = themes_path() { + if let Some(d) = p.parent() { + let _ = std::fs::create_dir_all(d); + } + if let Ok(s) = serde_json::to_string_pretty(v) { + let _ = std::fs::write(p, s); + } + } +} + +fn hex6(c: [f32; 3]) -> String { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + format!("{:02X}{:02X}{:02X}", b(c[0]), b(c[1]), b(c[2])) +} + +fn parse6(s: &str) -> Option<[f32; 3]> { + if s.len() != 6 { + return None; + } + let v = u32::from_str_radix(s, 16).ok()?; + Some([((v >> 16) & 255) as f32 / 255.0, ((v >> 8) & 255) as f32 / 255.0, (v & 255) as f32 / 255.0]) +} + +/// `name|` + 36 hex digits (dark BG UI ACCENT, light BG UI ACCENT) +pub fn encode(t: &UserTheme) -> String { + let mut s = format!("{}|", t.name); + for a in [&t.dark, &t.light] { + for k in 0..3 { + s.push_str(&hex6([a[k * 3], a[k * 3 + 1], a[k * 3 + 2]])); + } + } + s +} + +pub fn decode(s: &str) -> Option { + let (name, hex) = s.rsplit_once('|')?; + if hex.len() != 36 || name.is_empty() { + return None; + } + let mut c = [[0.0f32; 3]; 6]; + for (i, slot) in c.iter_mut().enumerate() { + *slot = parse6(&hex[i * 6..i * 6 + 6])?; + } + Some(UserTheme { name: name.to_string(), dark: flat(&c[0..3]), light: flat(&c[3..6]) }) +} + +fn flat(c: &[[f32; 3]]) -> [f32; 9] { + let mut a = [0.0; 9]; + for k in 0..3 { + a[k * 3..k * 3 + 3].copy_from_slice(&c[k]); + } + a +} + +pub fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { + let h = (h.rem_euclid(1.0)) * 6.0; + let (i, f) = (h.floor() as i32, h - h.floor()); + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + match i { + 0 => [v, t, p], + 1 => [q, v, p], + 2 => [p, v, t], + 3 => [p, q, v], + 4 => [t, p, v], + _ => [v, p, q], + } +} + +pub fn rgb_to_hsv(c: [f32; 3]) -> (f32, f32, f32) { + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let d = mx - mn; + let h = if d < 1e-6 { + 0.0 + } else if mx == c[0] { + ((c[1] - c[2]) / d).rem_euclid(6.0) / 6.0 + } else if mx == c[1] { + ((c[2] - c[0]) / d + 2.0) / 6.0 + } else { + ((c[0] - c[1]) / d + 4.0) / 6.0 + }; + (h, if mx <= 0.0 { 0.0 } else { d / mx }, mx) +} + +/// black or white, whichever reads on `c` +fn contrast(c: [f32; 3]) -> [f32; 3] { + if 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] > 0.5 { + [0.0; 3] + } else { + [1.0; 3] + } +} + +/// Text cursor blink. +pub fn blink(t: f64) -> bool { + ((t * 4.0).floor() as i64) & 1 == 1 +} + +pub struct Picker { + slot: usize, + old: [f32; 3], + h: f32, + s: f32, + v: f32, + /// 0 none, 1 dragging the SV square, 2 dragging the hue strip + drag: u8, +} + +/// On-screen keyboard state: 0 = theme name, 1 = hex colour. +pub struct Osk { + kind: u8, + text: String, +} + +pub struct ThemeEdit { + name: String, + /// dark BG, UI, ACCENT, then light BG, UI, ACCENT + col: [[f32; 3]; 6], + preview_light: bool, + /// user theme being edited (None = new) + index: Option, + picker: Option, + pub osk: Option, +} + +/// One line of the scrolling About / Changelog text. Head = version title (+ rule), takes the next Pad row too. +pub enum Row { + Text(f32, String), + Head(String), + Pad, +} + +#[derive(Clone, Copy)] +pub struct Rect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +impl Rect { + pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Self { + Self { x, y, w, h } + } +} + +/// Where the theme-editor cells go: a 4 x 3 grid of `cw` x `ch` cells, `px` / `py` apart, from (`x0`, `y0`). +#[derive(Clone, Copy)] +pub struct CellGrid { + pub x0: f32, + pub y0: f32, + pub cw: f32, + pub ch: f32, + pub px: f32, + pub py: f32, +} + +/// Input captured before the theme editor masks it, restored for the editor's own widgets. +pub type RealInput = (bool, bool, bool, i32, f32, f32); + +pub struct AppState { + /// About page: 0 closed, 1 about, 2 changelog, 3 appearance + pub about: u8, + /// first visible row of the About / Changelog text box + pub about_scroll: usize, + /// first visible scheme row in the Appearance list + pub ap_scroll: usize, + del_arm: f64, + /// feedback line on the Preferences page: (time it was set, text) + pub note: (f64, &'static str), + /// the font dropdown on the Preferences page is open + pub font_open: bool, + /// the little menu under a chevron on the Preferences page: 0 closed, 1 SET AS GLOBAL DEFAULT, 2 RESET GLOBAL DEFAULT + pub def_menu: u8, + /// a global default exists (cached: read when the page opens and after a save / reset; labels the reset button) + pub has_global: bool, + pub themes: Vec, + pub edit: Option, + pub real_in: RealInput, +} + +impl AppState { + pub fn new() -> Self { + Self { about: 0, about_scroll: 0, ap_scroll: 0, del_arm: -10.0, note: (-10.0, ""), font_open: false, def_menu: 0, has_global: load_defaults().is_some(), themes: load_themes().into_iter().filter(|t| builtin_by_name(&t.name).is_none()).collect(), edit: None, real_in: (false, false, false, 0, -1000.0, -1000.0) } + } + + /// The egui clock restarted (editor reopened): re-base stored timestamps. + pub fn rebase(&mut self) { + self.del_arm = -10.0; + } + + pub fn n_schemes(&self) -> usize { + PALETTES.len() + self.themes.len() + } + + pub fn scheme_name(&self, i: usize) -> String { + match i.checked_sub(PALETTES.len()) { + Some(u) => self.themes.get(u).map(|t| t.name.clone()).unwrap_or_default(), + None => PALETTES[i].0.to_string(), + } + } + + pub fn scheme_cols(&self, i: usize, light: bool) -> [f32; 9] { + match i.checked_sub(PALETTES.len()) { + Some(u) => self.themes.get(u).map(|t| if light { t.light } else { t.dark }).unwrap_or(PALETTES[0].1), + None => { + let e = &PALETTES[i.min(PALETTES.len() - 1)]; + if light { e.2 } else { e.1 } + } + } + } + + /// Colours the canvas draws with: the editor preview while editing, else the active scheme. + pub fn colors(&self, pal: usize, light: bool) -> [f32; 9] { + match &self.edit { + Some(e) => { + let o = if e.preview_light { 3 } else { 0 }; + flat(&e.col[o..o + 3]) + } + None => self.scheme_cols(pal, light), + } + } + + /// A project that used a user theme: find it in the themes file by name, or restore it from the project copy. + /// `saved` is the project's `custom-theme` string. Returns the scheme index to use. + pub fn restore_custom(&mut self, pal: usize, saved: &str) -> usize { + // A saved user theme (the project carries a copy: `saved`) wins over the stored index: the built-in table has grown + // since projects were saved, so an old "user theme" index (>= 20) can now be a built-in one. A user theme that has + // since become a built-in (same name) resolves to the built-in. + match decode(saved) { + Some(t) => { + if let Some(i) = builtin_by_name(&t.name) { + return i; + } + match self.themes.iter().position(|u| u.name == t.name) { + Some(i) => PALETTES.len() + i, + None => { + self.themes.push(t); + PALETTES.len() + self.themes.len() - 1 + } + } + } + None => { + if pal < PALETTES.len() { + pal + } else { + 0 + } + } + } + } + + pub fn editing(&self) -> bool { + self.edit.is_some() + } + + pub fn osk_open(&self) -> bool { + self.edit.as_ref().map(|e| e.osk.is_some()).unwrap_or(false) + } +} + +impl Default for AppState { + fn default() -> Self { + Self::new() + } +} + +/// Everything the pages need from the plug-in. Implemented on the plug-in's per-frame GUI type next to `Widgets`. +pub trait AppearanceUi<'c>: Widgets<'c> { + fn app(&mut self) -> &mut AppState; + fn app_ref(&self) -> &AppState; + fn pal(&self) -> usize; + fn light(&self) -> bool; + fn face(&self) -> usize; + /// Store the scheme (state, `palette-v2` and, for a user theme, the project copy `encoded`), then re-colour the canvas. + fn commit_scheme(&mut self, pal: usize, encoded: String); + fn commit_light(&mut self, light: bool); + fn commit_face(&mut self, face: usize); + /// Current window scale (1.0 = the plug-in's base size) and a request to change it. + fn scale_now(&self) -> f32; + fn set_scale(&mut self, scale: f32); + /// This plug-in's key in the defaults files ("satcomp", "satxcomp", "satlim"). + fn plugin_key(&self) -> &'static str; + /// This plug-in's user preset folder. + fn presets_dir(&self) -> Option; + /// The scale a fresh instance opens at when no defaults file exists. + fn factory_scale(&self) -> f32; + /// Factory spectrum / scope fill (for plug-ins that have the switch). + fn factory_fill_solid(&self) -> bool { + false + } + /// Spectrum fill style (`Some(solid)`), for plug-ins that draw a spectrum; `None` hides the switch on the Appearance page. + fn fft_solid(&self) -> Option { + None + } + fn commit_fft_solid(&mut self, _solid: bool) {} + /// Label of that switch (plug-ins that draw a scope rather than a spectrum can say so). + fn fill_label(&self) -> &'static str { + "SPECTRUM FILL" + } + + /// About page copy: paragraphs of source lines. + fn about_paras(&self) -> &'static [&'static [&'static str]]; + /// Changelog, newest first. + fn changelog(&self) -> &'static [(&'static str, &'static [&'static str])]; + /// The plug-in's manual: (file name, PDF bytes embedded in the binary). Shown as an OPEN MANUAL button on the About tab. + fn manual_pdf(&self) -> Option<(&'static str, &'static [u8])> { + None + } + /// The signal-flow diagram at the top of the About tab (height `flow_h`). + fn draw_flow(&mut self, r: Rect, byp: bool); + fn flow_h(&self) -> f32 { + 114.0 + } + + // ------------------------------------------------------------------ small helpers + fn set_pal(&mut self, p: usize) { + let p = p.min(self.app_ref().n_schemes() - 1); + let enc = match p.checked_sub(PALETTES.len()) { + Some(i) => encode(&self.app_ref().themes[i]), + None => String::new(), + }; + self.commit_scheme(p, enc); + } + + fn set_light(&mut self, l: bool) { + self.commit_light(l); + } + + /// Save this instance's look (scheme, mode, font, fill, window scale) as the default for new instances: of THIS plug-in + /// (`global` = false), or of every plug-in that has none of its own (`global` = true). + fn save_as_default(&mut self, global: bool) { + let pal = self.pal(); + let user = pal >= PALETTES.len(); + let theme = if user { self.app_ref().themes.get(pal - PALETTES.len()).map(encode).unwrap_or_default() } else { String::new() }; + let d = Defaults { + pal: if user && theme.is_empty() { 0 } else { pal.min(PALETTES.len()) as i32 }, + theme, + light: self.light(), + face: self.face() as i32, + fill_solid: self.fft_solid().unwrap_or_else(|| self.factory_fill_solid()), + scale: self.scale_now(), + }; + if global { + save_defaults(&d); + } else { + save_defaults_for(self.plugin_key(), &d); + } + self.app().has_global = load_defaults().is_some(); + let now = self.kit_ref().now; + self.app().note = (now, if global { "Saved as the global default" } else { "Saved as the default for this plug-in" }); + } + + /// The one item of the chevron menus: 1 = save as the global default, 2 = clear the global default. + fn reset_or_save_global(&mut self, menu: u8) { + if menu == 1 { + self.save_as_default(true); + } else { + self.reset_defaults(true); + } + } + + /// Give this instance a look: `None` = the factory look. + fn apply_defaults(&mut self, d: Option<&Defaults>) { + match d { + Some(d) => { + let pal = self.app().restore_custom(d.pal.max(0) as usize, &d.theme); + self.set_pal(pal); + self.set_light(d.light); + self.commit_face(d.face_index() as usize); + if self.fft_solid().is_some() { + self.commit_fft_solid(d.fill_solid); + } + self.set_scale(d.scale.clamp(1.0, 2.5)); + } + None => { + self.set_pal(0); + self.set_light(false); + self.commit_face(0); + if self.fft_solid().is_some() { + let f = self.factory_fill_solid(); + self.commit_fft_solid(f); + } + let f = self.factory_scale(); + self.set_scale(f); + } + } + } + + /// Clear this plug-in's own default (`global` = false) or the global one, then put this instance on the look a new + /// instance would get now: the plug-in's default, else the global one, else the factory look. + fn reset_defaults(&mut self, global: bool) { + if global { + clear_defaults(); + } else { + clear_defaults_for(self.plugin_key()); + } + let d = load_defaults_for(self.plugin_key()); + self.app().has_global = load_defaults().is_some(); + self.apply_defaults(d.as_ref()); + let note = match (global, d.is_some(), load_defaults().is_some()) { + (true, _, _) => "Global default cleared", + (false, _, true) => "Back to the global default", + (false, _, false) => "Back to the factory look", + }; + let now = self.kit_ref().now; + self.app().note = (now, note); + } + + fn mask_in(&mut self) { + let k = self.kit(); + k.press = false; + k.down = false; + k.rpress = false; + k.wheel = 0; + k.mx = -1000.0; + k.my = -1000.0; + } + + fn unmask_in(&mut self) { + let r = self.app_ref().real_in; + let k = self.kit(); + k.press = r.0; + k.down = r.1; + k.rpress = r.2; + k.wheel = r.3; + k.mx = r.4; + k.my = r.5; + } + + /// Call at the start of every frame: while the editor is open the real input is saved and masked. + fn begin_frame_editing(&mut self) { + let k = self.kit_ref(); + let r = (k.press, k.down, k.rpress, k.wheel, k.mx, k.my); + self.app().real_in = r; + if self.app_ref().editing() { + self.mask_in(); + self.kit().act = 0; + self.app().about = 0; + } + } + + fn wrap(&mut self, s: &str, w: f32) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + for word in s.split(' ') { + let t = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") }; + if !cur.is_empty() && self.cv().text_w(&t) > w { + out.push(std::mem::take(&mut cur)); + cur = word.to_string(); + } else { + cur = t; + } + } + if !cur.is_empty() { + out.push(cur); + } + out + } + + // ------------------------------------------------------------------ pages + /// About / Appearance / Changelog inside `r` (tab row 22 units above it). + fn draw_about(&mut self, r: Rect, byp: bool) { + let ty = r.y - 22.0; + // a narrow page (SatLim) fits three abutting tabs and a single cross icon, with no spacing; wider pages keep the labelled button + let narrow = r.w < 360.0; + let tw = ((r.w - 16.0) / 3.0).floor(); + for (i, (l, id)) in [("ABOUT", 1u8), ("PREFERENCES", 3u8), ("CHANGELOG", 2u8)].into_iter().enumerate() { + let (dx, w) = if narrow { (i as f32 * tw, tw + 1.0) } else { (i as f32 * 115.0, 114.0) }; + if self.btn(r.x + dx, ty, w, 16.0, l, (self.app_ref().about == id) as u8) { + let pal = self.pal(); + let a = self.app(); + a.about = id; + a.about_scroll = 0; + if id == 3 { + a.ap_scroll = pal.saturating_sub(2); + a.has_global = load_defaults().is_some(); + } + } + } + let (cx0, cw0) = if narrow { (r.x + 3.0 * tw, r.w - 3.0 * tw) } else { (r.x + r.w - 62.0, 62.0) }; + if self.btn(cx0, ty, cw0, 16.0, if narrow { "" } else { "X CLOSE" }, 0) { + let a = self.app(); + a.about = 0; + a.about_scroll = 0; + } + if narrow { + self.setc(false); + let (mx, my) = (cx0 + (cw0 * 0.5).floor(), ty + 8.0); + self.cv().line(mx - 3.0, my - 3.0, mx + 3.0, my + 3.0); + self.cv().line(mx - 3.0, my + 3.0, mx + 3.0, my - 3.0); + } + self.setc(false); + self.cv().set_font(1); + let page = self.app_ref().about; + if page == 3 { + self.draw_appearance(r); + return; + } + if page == 2 { + self.cv().boxr(r.x, r.y, r.w, r.h); + let mut rows = Vec::new(); + for (ver, lines) in self.changelog() { + rows.push(Row::Head(ver.to_string())); + rows.push(Row::Pad); + for l in *lines { + for (i, t) in self.wrap(l, r.w - 30.0).into_iter().enumerate() { + rows.push(Row::Text(if i == 0 { 0.0 } else { 10.0 }, if i == 0 { format!("- {t}") } else { t })); + } + } + rows.push(Row::Pad); + } + self.scroll_rows(r, &rows); + return; + } + let fh = self.flow_h(); + self.draw_flow(Rect::new(r.x, r.y, r.w, fh), byp); + self.setc(false); + let (by, bh) = (r.y + fh + 6.0, r.h - fh - 6.0); + self.cv().boxr(r.x, by, r.w, bh); + // OPEN MANUAL: the PDF is embedded in the plug-in, written to the temp folder and opened with the default viewer + let off = if let Some((name, bytes)) = self.manual_pdf() { + if self.btn(r.x + 4.0, by + 4.0, r.w - 8.0, 16.0, "OPEN MANUAL (PDF)", 0) { + open_manual(name, bytes); + } + self.setc(false); + 22.0 + } else { + 0.0 + }; + let (by, bh) = (by + off, bh - off); + let mut rows = Vec::new(); + for para in self.about_paras() { + for l in *para { + for t in self.wrap(l, r.w - 30.0) { + rows.push(Row::Text(0.0, t)); + } + } + rows.push(Row::Pad); + } + self.scroll_rows(Rect::new(r.x, by, r.w, bh - 17.0), &rows); + self.setc(false); + let face = self.face(); + self.cv().text(r.x + 6.0, r.y + r.h - 17.0, &format!("Font: {} (SIL OFL 1.1)", FONT_NAMES[face])); + self.cv().textr(r.x, r.y + r.h - 17.0, r.w - 6.0, "thomchantra"); + } + + /// Appearance tab: colour mode switch, scrollable scheme list with swatches, font choice. Everything applies at once. + fn draw_appearance(&mut self, r: Rect) { + const RH: f32 = 20.0; + // a narrow page puts the fill switch on a row of its own under COLOR MODE (everything below moves down) + let narrow = r.w < 460.0 && self.fft_solid().is_some(); + let hx = if narrow { 22.0 } else { 0.0 }; + let rows = ((r.h - 232.0 - hx) / RH).floor().max(0.0) as usize + 5; + let extra = (rows - 5) as f32 * RH; + let (lx, ly, lw) = (r.x + 8.0, r.y + 42.0 + hx, r.w - 16.0); + // Font dropdown: its list opens upwards over the page. The press is taken here, before anything under the list sees + // it, and the list itself is drawn last (end of this function). + const FH: f32 = 15.0; + let fy = r.y + 152.0 + extra + hx; + let n_fonts = FONT_NAMES.len(); + let (dx, dw) = (lx + 44.0, lw - 44.0); + let list_h = n_fonts as f32 * FH + 2.0; + let list_y = (fy - 4.0 - list_h).max(r.y + 2.0); + let bw = ((lw - 8.0) * 0.5).floor(); + let by = fy + 20.0; + let menu = self.app_ref().def_menu; + // the chevron menu's single item sits right under its button (over the OPEN row) + let item = Rect::new(if menu == 2 { lx + bw + 8.0 } else { lx }, by + 14.0, bw, 15.0); + let was_open = self.app_ref().font_open; + let real = { + let k = self.kit_ref(); + (k.press, k.down, k.rpress, k.wheel, k.mx, k.my) + }; + if was_open { + if real.0 && self.kit_ref().act == 0 { + if real.4 >= dx && real.4 < dx + dw && real.5 >= list_y && real.5 < list_y + list_h { + let i = (((real.5 - list_y - 1.0) / FH).floor().max(0.0) as usize).min(n_fonts - 1); + self.commit_face(i); + } + self.app().font_open = false; + } + self.mask_in(); // the page underneath is inert while the list is open + } + if menu != 0 { + if real.0 && self.kit_ref().act == 0 { + if real.4 >= item.x && real.4 < item.x + item.w && real.5 >= item.y && real.5 < item.y + item.h { + self.reset_or_save_global(menu); + } + self.app().def_menu = 0; + } + self.mask_in(); // the page underneath is inert while the menu is open + } + self.cv().boxr(r.x, r.y, r.w, r.h); + self.setc(false); + self.cv().set_font(1); + self.cv().text(lx, r.y + 8.0, "COLOR MODE"); + let light = self.light(); + for (dx, l, lt) in [(100.0, "DARK", false), (166.0, "LIGHT", true)] { + if self.btn(r.x + dx, r.y + 4.0, 64.0, 16.0, l, (light == lt) as u8) { + self.set_light(lt); + } + } + if let Some(solid) = self.fft_solid() { + self.setc(false); + let (ly0, lx0, bx0) = if narrow { (r.y + 26.0, lx, r.x + 100.0) } else { (r.y + 4.0, r.x + 240.0, r.x + 330.0) }; + let label = self.fill_label(); + self.cv().text(lx0, ly0 + 4.0, label); + for (dx, l, sd) in [(0.0, "OUTLINE", false), (74.0, "SOLID", true)] { + if self.btn(bx0 + dx, ly0, if sd { 56.0 } else { 72.0 }, 16.0, l, (solid == sd) as u8) { + self.commit_fft_solid(sd); + } + } + } + + // ---- scheme list + self.setc(false); + self.cv().text(lx, r.y + 30.0 + hx, "COLOR SCHEME"); + let pal = self.pal(); + let user_sel = pal >= PALETTES.len(); + let bx = r.x + r.w - 170.0; + // dice: pick a random scheme (built-in or user theme), never the current one + let tw = self.cv().text_w("COLOR SCHEME"); + let dx0 = lx + tw + 8.0; + let dy0 = r.y + 26.0 + hx; + if dx0 + 18.0 < bx - 4.0 { + if self.btn(dx0, dy0, 18.0, 14.0, "", 0) { + let n = self.app_ref().n_schemes(); + if n > 1 { + let mut idx = (rand_u32(self.kit_ref().now) as usize) % (n - 1); + if idx >= pal { + idx += 1; // skip the current one + } + self.set_pal(idx); + self.app().ap_scroll = idx.saturating_sub(2); + } + } + self.setc(false); + self.cv().boxr(dx0 + 4.0, dy0 + 2.0, 10.0, 10.0); + for (px, py) in [(2.0, 2.0), (6.0, 2.0), (4.0, 4.0), (2.0, 6.0), (6.0, 6.0)] { + self.cv().fill(dx0 + 4.0 + px, dy0 + 2.0 + py, 2.0, 2.0); + } + } + if self.btn(bx, r.y + 26.0 + hx, 82.0, 14.0, "NEW THEME", 0) { + self.begin_edit(None); + return; + } + let prev_dk = self.kit_ref().dk; + if !user_sel { + self.set_dk(0.5); // EDIT / DELETE only apply to a user theme + } + let now = self.kit_ref().now; + let armed = now - self.app_ref().del_arm < 3.0; + let edit_hit = self.btn(bx + 84.0, r.y + 26.0 + hx, 38.0, 14.0, "EDIT", 0); + let del_hit = self.btn(bx + 124.0, r.y + 26.0 + hx, 38.0, 14.0, if armed && user_sel { "SURE?" } else { "DEL" }, (armed && user_sel) as u8 * 2); + self.set_dk(prev_dk); + if user_sel { + if edit_hit { + self.begin_edit(Some(pal - PALETTES.len())); + return; + } + if del_hit { + if armed { + self.delete_user(pal - PALETTES.len()); + self.app().del_arm = -10.0; + } else { + self.app().del_arm = now; + } + } + } + let lh = rows as f32 * RH + 2.0; + let n = self.app_ref().n_schemes(); + let max = n.saturating_sub(rows); + let wheel = self.kit_ref().wheel; + if self.hit(lx, ly, lw, lh) && wheel != 0 { + let a = self.app(); + a.ap_scroll = (a.ap_scroll as i32 - wheel).clamp(0, max as i32) as usize; + } + let (tx, ty, th) = (lx + lw - 9.0, ly + 3.0, lh - 6.0); + let thumb = (th * rows as f32 / n as f32).floor().max(14.0).min(th); + if self.hit(tx - 3.0, ty, 11.0, th) && self.kit_ref().press && self.kit_ref().act == 0 { + let k = self.kit(); + k.act = 141; + k.press = false; + } + if self.kit_ref().act == 141 && self.kit_ref().down { + let f = ((self.kit_ref().my - ty - thumb * 0.5) / (th - thumb).max(1.0)).clamp(0.0, 1.0); + self.app().ap_scroll = (f * max as f32 + 0.5).floor() as usize; + } + let a = self.app(); + a.ap_scroll = a.ap_scroll.min(max); + let scroll = a.ap_scroll; + self.setc(false); + self.cv().boxr(lx, ly, lw, lh); + let rw = lw - 2.0 - 11.0; + for i in 0..rows.min(n) { + let idx = scroll + i; + let y = ly + 1.0 + i as f32 * RH; + let sel = idx == self.pal(); // re-read: a click earlier in this list changes it for the rows below + if self.hit(lx + 1.0, y, rw, RH) && self.kit_ref().press && self.kit_ref().act == 0 { + self.set_pal(idx); + self.kit().press = false; + } + if sel { + self.setc(false); + self.cv().fill(lx + 1.0, y, rw, RH); + self.cv().setbg(); + } else { + self.setc(false); + } + let nm = self.app_ref().scheme_name(idx); + self.cv().text(lx + 9.0, y + 6.0, &nm); + let a = self.app_ref().scheme_cols(idx, light); + for k in 0..3 { + let (cx, cy) = (lx + rw - 3.0 - (3 - k) as f32 * 22.0 + 4.0, y + 3.0); + if sel { + self.cv().setbg(); + } else { + self.setc(false); + } + self.cv().fill(cx, cy, 20.0, RH - 6.0); + self.cv().setrgb([a[k * 3], a[k * 3 + 1], a[k * 3 + 2]]); + self.cv().fill(cx + 1.0, cy + 1.0, 18.0, RH - 8.0); + } + } + self.setc(false); + self.cv().fill(tx + 3.0, ty, 1.0, th); // track + let top = ty + (th - thumb) * scroll as f32 / max.max(1) as f32; + let act141 = self.kit_ref().act == 141; + self.setc(act141); + self.cv().fill(tx + 1.0, top.floor(), 5.0, thumb); + self.setc(false); + + // ---- font (dropdown) and the buttons under it + self.setc(false); + self.cv().text(lx, fy, "FONT"); + let face = self.face(); + if !was_open && menu == 0 && self.hit(dx, fy - 4.0, dw, 18.0) && self.kit_ref().press && self.kit_ref().act == 0 { + self.app().font_open = true; + self.kit().press = false; + } + self.setc(false); + self.cv().boxr(dx, fy - 4.0, dw, 18.0); + let keep = self.cv().face; + self.cv().face = face; // the name is drawn in its own typeface + self.cv().text(dx + 6.0, fy, FONT_NAMES[face]); + self.cv().face = keep; + let (ax, ay) = (dx + dw - 10.0, fy + 3.0); + self.cv().line(ax - 3.0, ay - 1.0, ax, ay + 2.0); + self.cv().line(ax, ay + 2.0, ax + 3.0, ay - 1.0); + + // SET AS DEFAULT / RESET: the main part acts on THIS plug-in, the chevron opens a one-item menu for the global default + let rx = lx + bw + 8.0; + if self.btn(lx, by, bw - 14.0, 14.0, "SET AS DEFAULT", 0) { + self.save_as_default(false); + } + let reset_label = if self.app_ref().has_global { "RESET TO GLOBAL" } else { "RESET TO FACTORY" }; + if self.btn(rx, by, bw - 14.0, 14.0, reset_label, 0) { + self.reset_defaults(false); + } + for (cx, id) in [(lx + bw - 15.0, 1u8), (rx + bw - 15.0, 2u8)] { + if self.btn(cx, by, 15.0, 14.0, "", (menu == id) as u8) { + if menu == 0 { + self.app().def_menu = id; + self.app().font_open = false; + } + } + self.setc(menu == id); + if menu == id { + self.cv().setbg(); + } + let (ax, ay) = (cx + 7.0, by + 6.0); + self.cv().line(ax - 3.0, ay - 1.0, ax, ay + 2.0); + self.cv().line(ax, ay + 2.0, ax + 3.0, ay - 1.0); + self.setc(false); + } + if self.btn(lx, by + 18.0, bw, 14.0, "OPEN PRESETS", 0) { + open_folder(self.presets_dir()); + } + if self.btn(rx, by + 18.0, bw, 14.0, "OPEN SETTINGS", 0) { + open_folder(settings_dir()); + } + self.setc(false); + let (t0, note) = self.app_ref().note; + if self.kit_ref().now - t0 < 4.0 { + self.cv().text(lx, by + 38.0, note); + } else { + self.cv().text(lx, by + 38.0, "Fonts: SIL OFL 1.1. Saved with the project."); + } + + // ---- the open font list, on top of everything + if was_open { + let k = self.kit(); + k.press = real.0; + k.down = real.1; + k.rpress = real.2; + k.wheel = real.3; + k.mx = real.4; + k.my = real.5; + self.cv().setbg(); + self.cv().fill(dx, list_y, dw, list_h); + self.setc(false); + self.cv().boxr(dx, list_y, dw, list_h); + for (i, name) in FONT_NAMES.iter().enumerate() { + let y = list_y + 1.0 + i as f32 * FH; + let hov = real.4 >= dx && real.4 < dx + dw && real.5 >= y && real.5 < y + FH; + self.setc(false); + let on = i == face; + if on { + self.cv().fill(dx + 1.0, y, dw - 2.0, FH); + self.cv().setbg(); + } else if hov { + self.cv().boxr(dx + 2.0, y + 1.0, dw - 4.0, FH - 2.0); + } + let keep = self.cv().face; + self.cv().face = i; + self.cv().text(dx + 6.0, y + 4.0, name); + self.cv().face = keep; + } + self.setc(false); + } + + // ---- the open chevron menu (one item), on top of everything + if menu != 0 { + let k = self.kit(); + k.press = real.0; + k.down = real.1; + k.rpress = real.2; + k.wheel = real.3; + k.mx = real.4; + k.my = real.5; + let hov = real.4 >= item.x && real.4 < item.x + item.w && real.5 >= item.y && real.5 < item.y + item.h; + self.setc(false); + if hov { + self.cv().fill(item.x, item.y, item.w, item.h); + self.cv().setbg(); + } else { + self.cv().setbg(); + self.cv().fill(item.x, item.y, item.w, item.h); + self.setc(false); + self.cv().boxr(item.x, item.y, item.w, item.h); + } + self.cv().textc(item.x, item.y + 4.0, item.w, if menu == 1 { "SET AS GLOBAL DEFAULT" } else { "RESET GLOBAL DEFAULT" }); + self.setc(false); + } + } + + /// Text rows (11 units each) in a box whose frame the caller has drawn. Mouse wheel scrolls 3 rows per notch; when the + /// text overflows a thumb on the right edge shows the position and can be dragged. Rows are culled whole (no clipping). + fn scroll_rows(&mut self, r: Rect, rows: &[Row]) { + let Rect { x, y, w, h } = r; + let vis = (((h - 10.0) / 11.0).floor() as usize).max(1); + let max = rows.len().saturating_sub(vis); + let wheel = self.kit_ref().wheel; + if self.hit(x, y, w, h) && wheel != 0 { + let a = self.app(); + a.about_scroll = (a.about_scroll as i32 - wheel * 3).clamp(0, max as i32) as usize; + } + let (tx, ty, th) = (x + w - 8.0, y + 4.0, h - 8.0); + let thumb = (th * vis as f32 / rows.len().max(1) as f32).floor().max(14.0).min(th); + if max > 0 { + if self.hit(tx - 3.0, ty, 10.0, th) && self.kit_ref().press && self.kit_ref().act == 0 { + let k = self.kit(); + k.act = 140; + k.press = false; + self.about_scroll_drag_start(); + } + if self.kit_ref().act == 140 && self.kit_ref().down { + let f = ((self.kit_ref().my - ty - thumb * 0.5) / (th - thumb).max(1.0)).clamp(0.0, 1.0); + self.app().about_scroll = (f * max as f32 + 0.5).floor() as usize; + } + } + let a = self.app(); + a.about_scroll = a.about_scroll.min(max); + let scroll = a.about_scroll; + self.setc(false); + for (i, row) in rows.iter().skip(scroll).take(vis).enumerate() { + let yy = y + 7.0 + i as f32 * 11.0; + match row { + Row::Text(ind, t) => self.cv().text(x + 8.0 + ind, yy, t), + Row::Head(t) => { + self.cv().text(x + 8.0, yy, t); + if i + 1 < vis { + self.cv().fill(x + 8.0, yy + 13.0, w - 16.0 - if max > 0 { 8.0 } else { 0.0 }, 1.0); + } + } + Row::Pad => {} + } + } + if max > 0 { + self.cv().fill(tx + 3.0, ty, 1.0, th); // track + let top = ty + (th - thumb) * scroll as f32 / max as f32; + let act140 = self.kit_ref().act == 140; + self.setc(act140); + self.cv().fill(tx + 1.0, top.floor(), 5.0, thumb); + self.setc(false); + } + } + + /// Hook: a scrollbar drag started (plug-ins that track other viewport drags clear them here). + fn about_scroll_drag_start(&mut self) {} + + // ------------------------------------------------------------------ theme editor + fn begin_edit(&mut self, index: Option) { + let (pal, light) = (self.pal(), self.light()); + let (name, d, l) = match index.and_then(|i| self.app_ref().themes.get(i)) { + Some(t) => (t.name.clone(), t.dark, t.light), + None => (String::new(), self.app_ref().scheme_cols(pal, false), self.app_ref().scheme_cols(pal, true)), + }; + let tri = |a: [f32; 9], k: usize| [a[k * 3], a[k * 3 + 1], a[k * 3 + 2]]; + let a = self.app(); + a.edit = Some(ThemeEdit { + name, + col: [tri(d, 0), tri(d, 1), tri(d, 2), tri(l, 0), tri(l, 1), tri(l, 2)], + preview_light: light, + index, + picker: None, + osk: None, + }); + a.about = 0; + } + + fn delete_user(&mut self, i: usize) { + if i >= self.app_ref().themes.len() { + return; + } + let cur = self.pal(); + let a = self.app(); + a.themes.remove(i); + save_themes(&a.themes); + let gone = PALETTES.len() + i; + self.set_pal(if cur == gone { 0 } else if cur > gone { cur - 1 } else { cur }); + } + + fn save_edit(&mut self) { + let Some(e) = self.app().edit.take() else { return }; + let mut name = e.name.trim().to_string(); + if name.is_empty() { + name = format!("Custom {}", self.app_ref().themes.len() + 1); + } + let taken = |a: &AppState, n: &str, skip: Option| { + PALETTES.iter().any(|p| p.0.eq_ignore_ascii_case(n)) + || a.themes.iter().enumerate().any(|(i, u)| Some(i) != skip && u.name.eq_ignore_ascii_case(n)) + }; + let base = name.clone(); + let mut k = 2; + while taken(self.app_ref(), &name, e.index) { + name = format!("{base} {k}"); + k += 1; + } + let t = UserTheme { name, dark: flat(&e.col[0..3]), light: flat(&e.col[3..6]) }; + let a = self.app(); + let idx = match e.index.filter(|&i| i < a.themes.len()) { + Some(i) => { + a.themes[i] = t; + i + } + None => { + a.themes.push(t); + a.themes.len() - 1 + } + }; + save_themes(&a.themes); + self.set_pal(PALETTES.len() + idx); + let a = self.app(); + a.about = 3; + a.ap_scroll = (PALETTES.len() + idx).saturating_sub(4); + } + + fn cancel_edit(&mut self) { + let a = self.app(); + a.edit = None; + a.about = 3; + } + + /// One editor cell: label top left, centred value. Returns true when clicked. + fn tc_box(&mut self, x: f32, y: f32, w: f32, h: f32, lbl: &str, val: &str, lit: bool, hot: bool) -> bool { + let clicked = self.hit(x, y, w, h) && self.kit_ref().press; + self.setc(hot); + if lit { + self.cv().fill(x, y, w, h); + self.cv().setbg(); + } else { + self.cv().boxr(x, y, w, h); + } + self.cv().set_font(1); + self.cv().text(x + 3.0, y + 3.0, lbl); + self.cv().set_font(2); + self.cv().textc(x, y + (h * 0.4 + 1.0).floor(), w, val); + self.setc(false); + clicked + } + + /// Large check mark (save) or X (cancel) button. + fn tc_icon(&mut self, x: f32, y: f32, w: f32, h: f32, check: bool, lit: bool) -> bool { + let clicked = self.hit(x, y, w, h) && self.kit_ref().press; + self.setc(false); + if lit { + self.cv().fill(x, y, w, h); + self.cv().setbg(); + } else { + self.cv().boxr(x, y, w, h); + } + let (cx, cy) = ((x + w * 0.5).floor(), (y + h * 0.5).floor()); + for d in 0..4 { + let o = d as f32 - 1.5; + if check { + self.cv().line(cx - 11.0 + o, cy + 1.0, cx - 4.0 + o, cy + 8.0); + self.cv().line(cx - 4.0 + o, cy + 8.0, cx + 11.0 + o, cy - 9.0); + } else { + self.cv().line(cx - 9.0 + o, cy - 9.0, cx + 9.0 + o, cy + 9.0); + self.cv().line(cx - 9.0 + o, cy + 9.0, cx + 9.0 + o, cy - 9.0); + } + } + self.setc(false); + clicked + } + + fn tc_swatch(&mut self, x: f32, y: f32, w: f32, h: f32, slot: usize, interactive: bool) { + let Some(e) = &self.app_ref().edit else { return }; + let col = e.col[slot]; + let hot = e.picker.as_ref().map(|p| p.slot == slot).unwrap_or(false); + let clicked = interactive && self.hit(x, y, w, h) && self.kit_ref().press; + self.setc(hot); + self.cv().boxr(x, y, w, h); + self.cv().set_font(1); + self.cv().text(x + 3.0, y + 3.0, SLOT_SHORT[slot]); + self.setc(false); + self.cv().boxr(x + 3.0, y + 15.0, w - 6.0, h - 18.0); + self.cv().setrgb(col); + self.cv().fill(x + 4.0, y + 16.0, w - 8.0, h - 20.0); + self.cv().setrgb(contrast(col)); + self.cv().textc(x + 3.0, y + 20.0, w - 6.0, &format!("#{}", hex6(col))); + self.setc(false); + if clicked { + self.kit().press = false; + let (h_, s_, v_) = rgb_to_hsv(col); + if let Some(e) = &mut self.app().edit { + e.preview_light = slot >= 3; + e.picker = Some(Picker { slot, old: col, h: h_, s: s_, v: v_, drag: 0 }); + } + } + } + + /// The editor's cell group on the dummy page: theme name, dark and light swatches, preview switch, save / cancel. + fn theme_cells(&mut self, g: CellGrid) { + let interactive = self.app_ref().edit.as_ref().map(|e| e.picker.is_none() && e.osk.is_none()).unwrap_or(false); + let keep = self.app_ref().real_in; + if interactive { + self.unmask_in(); + } + let xs = [g.x0, g.x0 + g.px, g.x0 + 2.0 * g.px, g.x0 + 3.0 * g.px]; + let ys = [g.y0, g.y0 + g.py, g.y0 + 2.0 * g.py]; + for k in 0..3 { + self.tc_swatch(xs[k], ys[0], g.cw, g.ch, k, interactive); + self.tc_swatch(xs[k], ys[1], g.cw, g.ch, 3 + k, interactive); + } + let Some(e) = &self.app_ref().edit else { return }; + let pl = e.preview_light; + let name = e.name.clone(); + + if self.tc_box(xs[3], ys[0], g.cw, g.ch, "PREVIEW", if pl { "LIGHT" } else { "DARK" }, false, false) && interactive { + self.kit().press = false; + if let Some(e) = &mut self.app().edit { + e.preview_light = !e.preview_light; + } + } + if self.tc_box(xs[3], ys[1], g.cw, g.ch, "AUTO", "LIGHT", false, false) && interactive { + self.kit().press = false; + if let Some(e) = &mut self.app().edit { + // light = dark with BG and UI swapped, same accent + e.col[3] = e.col[1]; + e.col[4] = e.col[0]; + e.col[5] = e.col[2]; + } + } + + // name field (two cells wide) + let shown = if name.is_empty() { "Custom".to_string() } else { name.clone() }; + if self.tc_box(xs[0], ys[2], g.px + g.cw, g.ch, "THEME NAME", &shown, false, false) && interactive { + self.kit().press = false; + if let Some(e) = &mut self.app().edit { + e.osk = Some(Osk { kind: 0, text: name.clone() }); + } + } + if self.tc_icon(xs[2], ys[2], g.cw, g.ch, true, true) && interactive { + self.kit().press = false; + self.save_edit(); + } else if self.app_ref().edit.is_some() && self.tc_icon(xs[3], ys[2], g.cw, g.ch, false, false) && interactive { + self.kit().press = false; + self.cancel_edit(); + } + if interactive { + self.app().real_in = keep; + self.mask_in(); + } + } + + /// On-screen keyboard over `r` (REAPER swallows typing in plug-in windows as hotkeys). Capital letters and digits only; + /// in hex mode just 0-9 and A-F are enabled. + fn theme_osk(&mut self, r: Rect) { + let Some(e) = &self.app_ref().edit else { return }; + let Some(o) = &e.osk else { return }; + let (kind, mut text) = (o.kind, o.text.clone()); + let Rect { x, y, w, h } = r; + let max = if kind == 0 { 16 } else { 6 }; + self.setc(false); + self.cv().setbg(); + self.cv().fill(x, y, w, h); + self.setc(false); + self.cv().boxr(x, y, w, h); + self.cv().set_font(1); + self.cv().text(x + 8.0, y + 5.0, if kind == 0 { "THEME NAME" } else { "HEX COLOUR" }); + self.cv().boxr(x + 8.0, y + 16.0, w - 16.0, 14.0); + let caret = if blink(self.kit_ref().now) { "_" } else { " " }; + let shown = if kind == 1 { format!("#{text}{caret}") } else { format!("{text}{caret}") }; + self.cv().text(x + 12.0, y + 19.0, &shown); + let (pitch, kh) = (26.0, 15.0); + let x0 = x + ((w - (10.0 * pitch - 2.0)) * 0.5).floor(); + let prev_dk = self.kit_ref().dk; + let mut close = false; + let mut accept = false; + let rows = ["1234567890", "QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"]; + let offs = [0.0, 0.0, 0.5, 1.0]; + for (ri, row) in rows.iter().enumerate() { + let ky = y + 34.0 + ri as f32 * 17.0; + for (i, c) in row.chars().enumerate() { + let kx = x0 + (offs[ri] + i as f32) * pitch; + let ok = kind == 0 || c.is_ascii_hexdigit(); + self.set_dk(if ok { prev_dk } else { 0.35 }); + let s = c.to_string(); + if self.btn(kx, ky, pitch - 2.0, kh, &s, 0) && ok && text.chars().count() < max { + text.push(c); + } + } + } + self.set_dk(prev_dk); + let ky = y + 34.0 + 4.0 * 17.0; + if self.btn(x0 + 8.0 * pitch, y + 34.0 + 3.0 * 17.0, 2.0 * pitch - 2.0, kh, "DEL", 0) { + text.pop(); + } + self.set_dk(if kind == 0 { prev_dk } else { 0.35 }); + if self.btn(x0, ky, 4.0 * pitch - 2.0, kh, "SPACE", 0) && kind == 0 && text.chars().count() < max { + text.push(' '); + } + self.set_dk(prev_dk); + if self.btn(x0 + 4.0 * pitch, ky, 3.0 * pitch - 2.0, kh, "OK", 1) { + accept = true; + } + if self.btn(x0 + 7.0 * pitch, ky, 3.0 * pitch - 2.0, kh, "CANCEL", 0) { + close = true; + } + if accept { + if kind == 0 { + if let Some(e) = &mut self.app().edit { + e.name = text.trim().to_string(); + e.osk = None; + } + return; + } + if let (Some(c), Some(e)) = (parse6(&text), self.app().edit.as_mut()) { + if let Some(p) = e.picker.as_mut() { + let (h_, s_, v_) = rgb_to_hsv(c); + p.h = if s_ > 0.0 { h_ } else { p.h }; + p.s = s_; + p.v = v_; + } + e.osk = None; + } + return; + } + if let Some(e) = &mut self.app().edit { + if close { + e.osk = None; + } else if let Some(o) = &mut e.osk { + o.text = text; + } + } + } + + /// Colour picker overlay over `r` (266 x 128): saturation / value square, hue strip, hex field, OK / CANCEL. Edits the + /// slot live, so the whole dummy page re-colours while you drag. + fn theme_picker(&mut self, r: Rect) { + let Some(e) = &self.app_ref().edit else { return }; + let Some(p) = &e.picker else { return }; + let slot = p.slot; + let Rect { x, y, w, h } = r; + self.setc(false); + self.cv().setbg(); + self.cv().fill(x, y, w, h); + self.setc(false); + self.cv().boxr(x, y, w, h); + self.cv().set_font(1); + self.cv().text(x + 8.0, y + 6.0, &format!("{} (live preview)", SLOT_NAMES[slot])); + + let (sx, sy, sw, sh_) = (x + 8.0, y + 20.0, 120.0, 100.0); + let (hx, hw) = (sx + sw + 8.0, 14.0); + let (mx, my, down, press) = (self.kit_ref().mx, self.kit_ref().my, self.kit_ref().down, self.kit_ref().press); + let mut close_ok = false; + let mut close_cancel = false; + let hit = |ax: f32, ay: f32, aw: f32, ah: f32| mx >= ax && mx < ax + aw && my >= ay && my < ay + ah; + let mut ask_hex = false; + + let Some(e) = &mut self.app().edit else { return }; + let Some(p) = &mut e.picker else { return }; + if press { + if hit(sx, sy, sw, sh_) { + p.drag = 1; + } else if hit(hx, sy, hw, sh_) { + p.drag = 2; + } else if hit(hx + hw + 8.0, sy + 42.0, 106.0, 16.0) { + ask_hex = true; + } + } + if !down { + p.drag = 0; + } + if p.drag == 1 { + p.s = ((mx - sx) / (sw - 1.0)).clamp(0.0, 1.0); + p.v = (1.0 - (my - sy) / (sh_ - 1.0)).clamp(0.0, 1.0); + } else if p.drag == 2 { + p.h = ((my - sy) / (sh_ - 1.0)).clamp(0.0, 1.0); + } + let cur = hsv_to_rgb(p.h, p.s, p.v); + let ph = p.h; + let (ps, pv) = (p.s, p.v); + let old = p.old; + let hexshow = hex6(cur); + e.col[slot] = cur; + + // SV square (4 px cells) and hue strip + let cell = 4.0; + for iy in 0..(sh_ / cell) as i32 { + for ix in 0..(sw / cell) as i32 { + let s_ = (ix as f32 + 0.5) * cell / sw; + let v_ = 1.0 - (iy as f32 + 0.5) * cell / sh_; + self.cv().setrgb(hsv_to_rgb(ph, s_, v_)); + self.cv().fill(sx + ix as f32 * cell, sy + iy as f32 * cell, cell, cell); + } + } + for iy in 0..(sh_ / cell) as i32 { + self.cv().setrgb(hsv_to_rgb((iy as f32 + 0.5) * cell / sh_, 1.0, 1.0)); + self.cv().fill(hx, sy + iy as f32 * cell, hw, cell); + } + self.setc(false); + self.cv().boxr(sx - 1.0, sy - 1.0, sw + 2.0, sh_ + 2.0); + self.cv().boxr(hx - 1.0, sy - 1.0, hw + 2.0, sh_ + 2.0); + // markers: a ring on the square, a bar on the strip (contrast against what is under them) + let (cx, cy) = (sx + ps * (sw - 1.0), sy + (1.0 - pv) * (sh_ - 1.0)); + self.cv().setrgb(contrast(cur)); + self.cv().boxr((cx - 3.0).floor(), (cy - 3.0).floor(), 7.0, 7.0); + self.cv().setrgb(contrast(hsv_to_rgb(ph, 1.0, 1.0))); + self.cv().fill(hx, (sy + ph * (sh_ - 1.0)).floor() - 1.0, hw, 3.0); + + // old / new, hex, RGB, buttons + let rx = hx + hw + 8.0; + self.setc(false); + self.cv().text(rx, sy, "OLD"); + self.cv().text(rx + 56.0, sy, "NEW"); + self.cv().setrgb(old); + self.cv().fill(rx, sy + 10.0, 50.0, 22.0); + self.cv().setrgb(cur); + self.cv().fill(rx + 56.0, sy + 10.0, 50.0, 22.0); + self.setc(false); + self.cv().boxr(rx - 1.0, sy + 9.0, 52.0, 24.0); + self.cv().boxr(rx + 55.0, sy + 9.0, 52.0, 24.0); + self.setc(false); + self.cv().boxr(rx, sy + 42.0, 106.0, 16.0); + self.cv().text(rx + 4.0, sy + 46.0, &format!("#{hexshow} EDIT")); + self.setc(false); + let b = |v: f32| (v * 255.0 + 0.5) as u8; + self.cv().text(rx, sy + 66.0, &format!("R{:03} G{:03} B{:03}", b(cur[0]), b(cur[1]), b(cur[2]))); + let ok = self.btn(rx, sy + 84.0, 50.0, 16.0, "OK", 1); + let cn = self.btn(rx + 56.0, sy + 84.0, 50.0, 16.0, "CANCEL", 0); + if ask_hex { + if let Some(e) = &mut self.app().edit { + e.osk = Some(Osk { kind: 1, text: hexshow.clone() }); + } + } + if ok && press { + close_ok = true; + } + if cn && press { + close_cancel = true; + } + if close_cancel { + if let Some(e) = &mut self.app().edit { + e.col[slot] = old; + e.picker = None; + } + } else if close_ok { + if let Some(e) = &mut self.app().edit { + e.picker = None; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_saved_user_theme_keeps_its_look_after_the_builtin_table_grew() { + let mut a = AppState { themes: Vec::new(), ..AppState::new() }; + let t = UserTheme { name: "Mine".into(), dark: [0.1; 9], light: [0.9; 9] }; + // an old project: user themes were indices 20, 21, ... (the table had 20 entries then), the project carries the theme + let i = a.restore_custom(20, &encode(&t)); + assert_eq!(i, PALETTES.len(), "the user theme, not whatever built-in now sits at index 20"); + assert_eq!(a.themes.len(), 1); + assert_eq!(a.restore_custom(20, &encode(&t)), i, "restoring twice does not add a second copy"); + // a built-in index with no theme string stays itself, a stale out-of-range index falls back to Mono + assert_eq!(a.restore_custom(5, ""), 5); + assert_eq!(a.restore_custom(200, ""), 0); + // a user theme that is a built-in now (same name, any case) resolves to the built-in + let b = UserTheme { name: "BRICK".into(), dark: [0.3; 9], light: [0.7; 9] }; + assert_eq!(a.restore_custom(21, &encode(&b)), builtin_by_name("brick").unwrap()); + } + + #[test] + fn the_new_schemes_are_in_the_table_and_ultramarine_has_the_lighter_accent() { + for n in ["Brick", "Bob", "Carbon", "Olive", "Jade", "Honey", "Stealth"] { + assert!(builtin_by_name(n).is_some(), "{n}"); + } + assert_eq!(PALETTES.len(), 27); + let u = &PALETTES[builtin_by_name("Ultramarine").unwrap()]; + assert!((u.1[6] - 0x77 as f32 / 255.0).abs() < 0.001, "ultramarine accent {:?}", u.1); + // names are unique, ignoring case + let mut names: Vec = PALETTES.iter().map(|p| p.0.to_ascii_lowercase()).collect(); + names.sort(); + names.dedup(); + assert_eq!(names.len(), PALETTES.len()); + } + + #[test] + fn theme_encoding_roundtrips_and_hsv_inverts() { + let t = UserTheme { name: "Test|odd".into(), dark: [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0], light: [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 1.0] }; + let d = decode(&encode(&t)).unwrap(); + assert_eq!(d.name, "Test|odd"); + for k in 0..9 { + assert!((d.dark[k] - t.dark[k]).abs() < 1.0 / 255.0 && (d.light[k] - t.light[k]).abs() < 1.0 / 255.0); + } + for c in [[0.2, 0.5, 0.9], [1.0, 0.0, 0.0], [0.3, 0.3, 0.3]] { + let (h, s, v) = rgb_to_hsv(c); + let r = hsv_to_rgb(h, s, v); + for k in 0..3 { + assert!((r[k] - c[k]).abs() < 1e-4); + } + } + assert!(decode("nobar").is_none() && decode("x|123").is_none()); + } +} diff --git a/rust/satcomp-plugin/src/gui/canvas.rs b/rust/satcomp-ui/src/canvas.rs similarity index 60% rename from rust/satcomp-plugin/src/gui/canvas.rs rename to rust/satcomp-ui/src/canvas.rs index 98d91c6..e5db893 100644 --- a/rust/satcomp-plugin/src/gui/canvas.rs +++ b/rust/satcomp-ui/src/canvas.rs @@ -16,12 +16,12 @@ pub const FONT_SCALE: f32 = 0.86; /// Colour schemes: (name, dark [BG rgb, UI rgb, ACCENT rgb], light [same]). Generated from docs/colorscheme.md (itself from /// docs/colorthemesV2.svg). The index is persisted (`palette-v2`): append new schemes, do not reorder. -pub const PALETTES: [(&str, [f32; 9], [f32; 9]); 20] = [ +pub const PALETTES: [(&str, [f32; 9], [f32; 9]); 27] = [ ("Mono", [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]), ("Furnace", [0.2549, 0.0275, 0.0275, 1.0, 0.0, 0.251, 1.0, 0.4, 0.0], [1.0, 0.0, 0.251, 0.2549, 0.0275, 0.0275, 1.0, 0.4, 0.0]), ("Barracuda", [0.0784, 0.2196, 0.1961, 0.6431, 1.0, 0.9647, 0.0, 1.0, 0.898], [0.6431, 1.0, 0.9647, 0.0784, 0.2196, 0.1961, 0.0, 0.4745, 0.4275]), ("Cadmium", [0.3137, 0.3137, 0.3137, 1.0, 1.0, 1.0, 1.0, 0.451, 0.0], [1.0, 1.0, 1.0, 0.3137, 0.3137, 0.3137, 1.0, 0.451, 0.0]), - ("Ultramarine", [0.0, 0.102, 0.549, 1.0, 1.0, 1.0, 0.149, 0.3059, 1.0], [1.0, 1.0, 1.0, 0.0, 0.102, 0.549, 0.149, 0.3059, 1.0]), + ("Ultramarine", [0.0, 0.102, 0.549, 1.0, 1.0, 1.0, 0.4667, 0.5529, 0.9294], [1.0, 1.0, 1.0, 0.0, 0.102, 0.549, 0.4667, 0.5529, 0.9294]), ("Azure", [0.1686, 0.1961, 0.2353, 0.8157, 0.8588, 0.8941, 0.0, 0.8, 1.0], [0.8157, 0.8588, 0.8941, 0.1686, 0.1961, 0.2353, 0.0, 0.8, 1.0]), ("Magenta", [0.3098, 0.0, 0.4314, 1.0, 0.4196, 0.8471, 1.0, 0.0, 0.6824], [1.0, 0.4196, 0.8471, 0.3098, 0.0, 0.4314, 1.0, 0.0, 0.6824]), ("Bananas", [0.0, 0.0, 0.0, 1.0, 0.851, 0.0, 0.0, 0.5843, 1.0], [1.0, 0.851, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5843, 1.0]), @@ -37,10 +37,36 @@ pub const PALETTES: [(&str, [f32; 9], [f32; 9]); 20] = [ ("Berry", [0.4627, 0.1176, 0.2745, 1.0, 0.5961, 0.8196, 1.0, 0.298, 0.298], [1.0, 0.5961, 0.8196, 0.4627, 0.1176, 0.2745, 1.0, 0.298, 0.298]), ("Night Rider", [0.0392, 0.0, 0.2706, 1.0, 0.2627, 0.7529, 0.298, 0.9529, 1.0], [1.0, 0.2627, 0.7529, 0.0392, 0.0, 0.2706, 0.298, 0.9529, 1.0]), ("Suika", [0.6588, 0.0157, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.4275], [1.0, 1.0, 1.0, 0.6588, 0.0157, 0.0, 0.298, 1.0, 0.3882]), + ("Brick", [0.5098, 0.0039, 0.0039, 1.0, 0.9059, 0.7882, 1.0, 0.1922, 0.1922], [1.0, 0.9059, 0.7882, 0.5098, 0.0039, 0.0039, 0.9608, 0.3961, 0.3961]), + ("Bob", [0.0, 0.2392, 0.549, 1.0, 1.0, 1.0, 1.0, 0.3882, 0.1294], [1.0, 1.0, 1.0, 0.0, 0.2392, 0.549, 1.0, 0.3882, 0.1294]), + ("Carbon", [0.1216, 0.1216, 0.1216, 0.8667, 0.8784, 0.9333, 0.8745, 0.2, 0.2], [0.8667, 0.8784, 0.9333, 0.1216, 0.1216, 0.1216, 0.8745, 0.2, 0.2]), + ("Olive", [0.2, 0.1608, 0.0549, 0.8196, 0.8549, 0.7765, 0.7216, 0.4471, 0.4471], [0.8196, 0.8549, 0.7765, 0.2, 0.1608, 0.0549, 0.7216, 0.4471, 0.4471]), + ("Jade", [0.0235, 0.2353, 0.298, 0.0, 1.0, 0.498, 1.0, 0.051, 0.0], [0.0, 1.0, 0.498, 0.0235, 0.2353, 0.298, 1.0, 0.051, 0.0]), + ("Honey", [0.2039, 0.1725, 0.098, 1.0, 0.8235, 0.0, 1.0, 0.3255, 0.051], [1.0, 0.8235, 0.0, 0.2039, 0.1725, 0.098, 1.0, 0.3255, 0.051]), + ("Stealth", [0.1294, 0.1294, 0.1294, 0.302, 0.302, 0.302, 0.5608, 0.051, 0.051], [0.302, 0.302, 0.302, 0.1294, 0.1294, 0.1294, 0.5608, 0.051, 0.051]), ]; /// Selectable UI fonts (index persisted as `ui-font`: append, do not reorder). All are SIL OFL 1.1. -pub const FONT_NAMES: [&str; 6] = ["Fira Code", "JetBrains Mono", "Geist Mono", "Roboto Mono", "Oxygen Mono", "Doto"]; +pub const FONT_NAMES: [&str; 11] = ["Fira Code", "JetBrains Mono", "Geist Mono", "Roboto Mono", "Oxygen Mono", "Doto", "DM Mono", "Victor Mono", "Anonymous Pro", "Inconsolata", "Courier Prime"]; + +/// Per-typeface tuning, SAME ORDER as `FONT_NAMES`: `(size multiplier, vertical shift)`. +/// * size multiplier: 1.0 = unchanged. Fonts differ in cap height (Victor Mono is tall, Anonymous Pro small), so each is +/// scaled to land near Fira Code's cap height (about 0.71 em). Raise it if a font looks small, lower it if it looks big. +/// * vertical shift: in em of the scaled font; positive moves the text DOWN, negative UP (1 unit of the shift is the font +/// size, so 0.05 is about half a pixel at 100%). +pub const FONT_TUNE: [(f32, f32); 11] = [ + (1.00, 0.0), // Fira Code + (0.97, 0.0), // JetBrains Mono + (1.00, 0.0), // Geist Mono + (1.00, 0.0), // Roboto Mono + (0.97, 0.0), // Oxygen Mono + (1.00, 0.0), // Doto + (1.01, 0.0), // DM Mono + (0.89, 0.0), // Victor Mono + (1.11, 0.0), // Anonymous Pro + (1.14, 0.0), // Inconsolata (small capitals, narrow: scaled up to Fira's cap height) + (1.15, 0.0), // Courier Prime (smaller still, but wide: held at 1.15 so labels keep fitting their boxes) +]; pub fn font_family(i: usize) -> FontFamily { FontFamily::Name(format!("f{i}").into()) @@ -65,6 +91,52 @@ pub struct Canvas<'a> { pub face: usize, } +fn lum(c: [f32; 3]) -> f32 { + 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] +} + +fn hue_sat(c: [f32; 3]) -> (f32, f32) { + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let d = mx - mn; + if d <= 0.0 { + return (0.0, 0.0); + } + let h = if mx == c[0] { ((c[1] - c[2]) / d).rem_euclid(6.0) } else if mx == c[1] { (c[2] - c[0]) / d + 2.0 } else { (c[0] - c[1]) / d + 4.0 }; + (h * 60.0, d / mx) +} + +/// True when a scheme is neutral on all three swatches (background, UI colour and accent all have almost no saturation): +/// there is no hue to invert. One tinted swatch, or a theme whose swatches all lean into the same hue, still counts as colour. +pub fn is_grey_scheme(bk: [f32; 3], fg: [f32; 3], ac: [f32; 3]) -> bool { + [bk, fg, ac].iter().all(|&c| hue_sat(c).1 < 0.15) +} + +/// Colour of gain that is ADDED (spectrum gain area, upward-compressor lift): the inverse of the accent, kept readable on the background. +/// A dark inverse is lightened toward white (a light scheme: darkened toward black) until it stands off the background; neutral +/// schemes (see `is_grey_scheme`) and inverses that cannot be made to stand off use white, or black on a light scheme. +pub fn gain_colour(bk: [f32; 3], fg: [f32; 3], ac: [f32; 3]) -> [f32; 3] { + let dark_bg = lum(bk) < 0.5; + let plain = if dark_bg { [1.0; 3] } else { [0.0; 3] }; + if is_grey_scheme(bk, fg, ac) { + return plain; + } + let mut inv = [1.0 - ac[0], 1.0 - ac[1], 1.0 - ac[2]]; + for _ in 0..8 { + if (lum(inv) - lum(bk)).abs() >= 0.3 { + break; + } + for k in 0..3 { + inv[k] += (plain[k] - inv[k]) * 0.15; + } + } + let dist = (0..3).map(|k| (inv[k] - bk[k]).powi(2)).sum::().sqrt(); + if dist < 0.4 { + plain + } else { + inv + } +} + fn rgb(c: [f32; 3]) -> Color32 { Color32::from_rgb((c[0] * 255.0 + 0.5) as u8, (c[1] * 255.0 + 0.5) as u8, (c[2] * 255.0 + 0.5) as u8) } @@ -138,7 +210,7 @@ impl<'a> Canvas<'a> { 1 => 12.0, 2 => 14.0, _ => 18.0, - } * self.s * FONT_SCALE; + } * self.s * FONT_SCALE * FONT_TUNE[self.face].0; FontId::new(sz.max(5.0), font_family(self.face)) } @@ -152,7 +224,7 @@ impl<'a> Canvas<'a> { } pub fn text(&self, x: f32, y: f32, s: &str) { - let lift = TEXT_LIFT_EM * self.fid().size; + let lift = (TEXT_LIFT_EM - FONT_TUNE[self.face].1) * self.fid().size; self.p.text( Pos2::new(self.snap(self.ox + x * self.s), self.snap(self.oy + y * self.s - lift)), Align2::LEFT_TOP, @@ -187,3 +259,26 @@ impl<'a> Canvas<'a> { self.p.circle_filled(Pos2::new(self.ox + x * self.s, self.oy + y * self.s), r * self.s, self.col); } } + +#[cfg(test)] +mod gain_colour_tests { + use super::*; + + #[test] + fn gain_colour_keeps_its_hue_except_on_grey_schemes() { + for (name, d, l) in PALETTES.iter() { + for (mode, a) in [("dark", d), ("light", l)] { + let (bk, fg, ac) = ([a[0], a[1], a[2]], [a[3], a[4], a[5]], [a[6], a[7], a[8]]); + let g = gain_colour(bk, fg, ac); + let plain = g == [1.0; 3] || g == [0.0; 3]; + if is_grey_scheme(bk, fg, ac) { + assert!(plain, "{name} {mode}"); + } else { + assert!(!plain, "{name} {mode}: gain colour fell back to plain {g:?}"); + } + } + } + let a = &PALETTES[13]; // Ashen + assert!(is_grey_scheme([a.1[0]; 3], [a.1[3]; 3], [a.1[6]; 3])); + } +} diff --git a/rust/satcomp-ui/src/fft.rs b/rust/satcomp-ui/src/fft.rs new file mode 100644 index 0000000..f6cc03f --- /dev/null +++ b/rust/satcomp-ui/src/fft.rs @@ -0,0 +1,42 @@ +//! Plain radix-2 FFT for the spectrum views. + +/// In-place radix-2 complex FFT (n = 4096), bit-reversal included. +pub fn fft(re: &mut [f32], im: &mut [f32]) { + let n = re.len(); + let mut j = 0usize; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j ^= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut len = 2; + while len <= n { + let ang = -2.0 * std::f32::consts::PI / len as f32; + let (wr, wi) = (ang.cos(), ang.sin()); + let mut i = 0; + while i < n { + let (mut cr, mut ci) = (1.0f32, 0.0f32); + for k in 0..len / 2 { + let (a, b) = (i + k, i + k + len / 2); + let tr = re[b] * cr - im[b] * ci; + let ti = re[b] * ci + im[b] * cr; + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + let ncr = cr * wr - ci * wi; + ci = cr * wi + ci * wr; + cr = ncr; + } + i += len; + } + len <<= 1; + } +} diff --git a/rust/satcomp-ui/src/kit.rs b/rust/satcomp-ui/src/kit.rs new file mode 100644 index 0000000..ad51d18 --- /dev/null +++ b/rust/satcomp-ui/src/kit.rs @@ -0,0 +1,470 @@ +//! Immediate-mode widget kit: the interaction state (`Kit`) and the widgets (`Widgets`), port of the JSFX `@gfx` helpers. +//! +//! Parameters are addressed by slot number `n` (the JSFX slider number): the host plug-in maps a slot to a nih-plug +//! `ParamPtr` and formats its value; this kit does the dragging, snapping, double-click reset, wheel and drawing. +//! A plug-in implements `Widgets` for its per-frame GUI type, which must `Deref` to its own state that in turn derefs to +//! `Kit` (so widget code and page code both read `self.mx`, `self.press`, ...). + +use crate::canvas::Canvas; +use nih_plug::prelude::{GuiContext, ParamPtr}; + +/// Value range and drag behaviour of one parameter slot. +#[derive(Clone, Copy, Default)] +pub struct Meta { + pub min: f32, + pub max: f32, + pub def: f32, + /// 0 linear, 1 log, 2 sqrt + pub mode: u8, + /// bit 0: snap to min near the start of travel, bit 1: snap to max near the end + pub snap: u8, + pub step: f32, +} + +/// Interaction state shared by all widgets. +pub struct Kit { + pub meta: Vec, + pub touched: Vec, + /// the widget being dragged: 1..99 = slot number (vertical drag), >= 100 = viewport drags owned by the page + pub act: i32, + pub act_t: f32, + pub last_my: f32, + pub last_clk_n: i32, + pub last_clk_t: f64, + pub last_down: bool, + pub last_rdown: bool, + pub wacc: f32, + // per-frame input (logical units) + pub mx: f32, + pub my: f32, + pub down: bool, + pub press: bool, + pub rpress: bool, + pub wheel: i32, + pub shift: bool, + pub now: f64, + /// 1 = normal, 0.5 = dimmed (modules dimmed while bypassed) + pub dk: f32, +} + +impl Kit { + pub fn new(slots: usize) -> Self { + Self { + meta: vec![Meta::default(); slots], + touched: vec![false; slots], + act: 0, + act_t: 0.0, + last_my: 0.0, + last_clk_n: 0, + last_clk_t: 0.0, + last_down: false, + last_rdown: false, + wacc: 0.0, + mx: -1000.0, + my: -1000.0, + down: false, + press: false, + rpress: false, + wheel: 0, + shift: false, + now: 0.0, + dk: 1.0, + } + } + + /// Per-frame input snapshot (positions in logical canvas units). Computes press edges like the JSFX. + /// Returns true when the clock went backwards (the egui clock restarts from 0 whenever the editor window is reopened + /// while the state lives on): the owner must then re-base its own stored timestamps to `now`. + pub fn set_input(&mut self, mx: f32, my: f32, down: bool, rdown: bool, scroll: f32, shift: bool, now: f64) -> bool { + self.mx = mx; + self.my = my; + self.down = down; + self.press = down && !self.last_down; + self.last_down = down; + self.rpress = rdown && !self.last_rdown; + self.last_rdown = rdown; + self.shift = shift; + let restarted = now < self.now; + if restarted { + self.last_clk_t = now; + } + self.now = now; + // notch the scroll: a mouse wheel reports big steps, a trackpad many small ones + self.wacc += scroll; + self.wheel = 0; + if self.wacc.abs() >= 10.0 { + self.wheel = if self.wacc > 0.0 { 1 } else { -1 }; + self.wacc = 0.0; + } + restarted + } +} + +/// Widgets over `Kit`. `'c` is the canvas lifetime of the implementing GUI type. +pub trait Widgets<'c> { + fn kit(&mut self) -> &mut Kit; + fn kit_ref(&self) -> &Kit; + fn cv(&mut self) -> &mut Canvas<'c>; + /// the parameter behind slot `n` + fn param_ptr(&self, n: usize) -> Option; + fn host(&self) -> &dyn GuiContext; + /// widgets draw but must not write parameters (theme editor preview page) + fn masked(&self) -> bool { + false + } + /// display text of a slot's value + fn fmt(&self, n: usize, v: f32) -> String; + + // ------------------------------------------------------------------ params (slot-number addressing) + fn sget(&self, n: usize) -> f32 { + match self.param_ptr(n) { + Some(p) => { + let m = self.kit_ref().meta[n]; + m.min + (m.max - m.min) * unsafe { p.unmodulated_normalized_value() } + } + None => 0.0, + } + } + + fn sset(&mut self, n: usize, v: f32) { + if self.masked() { + return; // dummy widgets never write parameters + } + if let Some(p) = self.param_ptr(n) { + let m = self.kit().meta[n]; + let norm = ((v - m.min) / (m.max - m.min)).clamp(0.0, 1.0); + let first = !self.kit().touched[n]; + unsafe { + if first { + self.host().raw_begin_set_parameter(p); + self.kit().touched[n] = true; + } + self.host().raw_set_parameter_normalized(p, norm); + } + } + } + + fn end_touch(&mut self, n: usize) { + if self.masked() { + return; + } + if n < self.kit().touched.len() && self.kit().touched[n] { + if let Some(p) = self.param_ptr(n) { + unsafe { self.host().raw_end_set_parameter(p) }; + } + self.kit().touched[n] = false; + } + } + + /// set + release in one go (a click, not a drag) + fn click_set(&mut self, n: usize, v: f32) { + self.sset(n, v); + self.end_touch(n); + } + + fn setv(&mut self, n: usize, mut v: f32) { + let m = self.kit().meta[n]; + if m.step > 0.0 { + v = (v / m.step + 0.5).floor() * m.step; + } + v = v.clamp(m.min, m.max); + if v != self.sget(n) { + self.sset(n, v); + } + } + + fn n2t(&self, n: usize, v: f32) -> f32 { + let m = self.kit_ref().meta[n]; + let t = match m.mode { + 1 => (v.max(m.min) / m.min).ln() / (m.max / m.min).ln(), + 2 => ((v - m.min).max(0.0) / (m.max - m.min)).sqrt(), + _ => (v - m.min) / (m.max - m.min), + }; + t.clamp(0.0, 1.0) + } + + fn t2n(&self, n: usize, mut t: f32) -> f32 { + let m = self.kit_ref().meta[n]; + if m.snap & 1 != 0 && t < 0.03 { + t = 0.0; + } + if m.snap & 2 != 0 && t > 0.97 { + t = 1.0; + } + let mut v = match m.mode { + 1 => m.min * (t * (m.max / m.min).ln()).exp(), + 2 => m.min + (m.max - m.min) * t * t, + _ => m.min + (m.max - m.min) * t, + }; + if m.step > 0.0 { + v = (v / m.step + 0.5).floor() * m.step; + } + v.clamp(m.min, m.max) + } + + fn commit(&mut self, n: usize, t: f32) { + let v = self.t2n(n, t); + if v != self.sget(n) { + self.sset(n, v); + } + } + + fn hit(&self, x: f32, y: f32, w: f32, h: f32) -> bool { + let k = self.kit_ref(); + k.mx >= x && k.mx < x + w && k.my >= y && k.my < y + h + } + + fn dbl(&mut self, id: i32) -> bool { + let k = self.kit(); + let r = k.last_clk_n == id && k.now - k.last_clk_t < 0.35; + k.last_clk_n = if r { 0 } else { id }; + k.last_clk_t = k.now; + r + } + + fn begin_drag(&mut self, n: usize) { + let dbl = { + let k = self.kit(); + k.last_clk_n == n as i32 && k.now - k.last_clk_t < 0.35 + }; + if dbl { + let d = self.kit().meta[n].def; + self.click_set(n, d); + let k = self.kit(); + k.act = 0; + k.last_clk_n = 0; + } else { + let t = { + let v = self.sget(n); + self.n2t(n, v) + }; + let k = self.kit(); + k.act = n as i32; + k.act_t = t; + k.last_my = k.my; + k.last_clk_n = n as i32; + k.last_clk_t = k.now; + } + } + + fn wheel_adj(&mut self, n: usize) { + let (wheel, shift) = { + let k = self.kit(); + (k.wheel, k.shift) + }; + let cur = { + let v = self.sget(n); + self.n2t(n, v) + }; + let t = cur + if wheel > 0 { 1.0 } else { -1.0 } * if shift { 0.005 } else { 0.03 }; + self.commit(n, t.clamp(0.0, 1.0)); + self.end_touch(n); + } + + /// colour select: UI colour, or accent when `red`; honours the dim factor + fn setc(&mut self, red: bool) { + let dk = self.kit().dk; + let cv = self.cv(); + cv.dk = dk; + cv.setc(red); + } + + fn set_dk(&mut self, d: f32) { + self.kit().dk = d; + self.cv().dk = d; + } + + // ------------------------------------------------------------------ widgets + fn cell(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str) { + let hv = self.hit(x, y, w, h); + if hv && self.kit().press && self.kit().act == 0 { + self.begin_drag(n); + } + if hv && self.kit().wheel != 0 { + self.wheel_adj(n); + } + let v = self.sget(n); + let t = self.n2t(n, v); + let isact = self.kit().act == n as i32; + self.setc(isact); + let s = self.fmt(n, v); + let cv = self.cv(); + cv.boxr(x, y, w, h); + cv.set_font(1); + cv.text(x + 3.0, y + 3.0, lbl); + cv.set_font(2); + cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, &s); + cv.fill(x + 2.0, y + h - 4.0, ((t * (w - 4.0)).floor()).max(1.0), 2.0); + } + + /// inverted cell (lit block) for the gain-stage cells + fn cell_o(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str) { + let hv = self.hit(x, y, w, h); + if hv && self.kit().press && self.kit().act == 0 { + self.begin_drag(n); + } + if hv && self.kit().wheel != 0 { + self.wheel_adj(n); + } + let v = self.sget(n); + let t = self.n2t(n, v); + let isact = self.kit().act == n as i32; + self.setc(isact); + let s = self.fmt(n, v); + { + let cv = self.cv(); + cv.fill(x, y, w, h); + cv.setbg(); + cv.set_font(1); + cv.text(x + 3.0, y + 3.0, lbl); + cv.set_font(2); + cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, &s); + cv.fill(x + 2.0, y + h - 4.0, ((t * (w - 4.0)).floor()).max(1.0), 2.0); + } + self.setc(false); + } + + /// one param in a single short row (label left, value right, value bar on the bottom edge) + fn cell1(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str) { + let hv = self.hit(x, y, w, h); + if hv && self.kit().press && self.kit().act == 0 { + self.begin_drag(n); + } + if hv && self.kit().wheel != 0 { + self.wheel_adj(n); + } + let v = self.sget(n); + let t = self.n2t(n, v); + let isact = self.kit().act == n as i32; + self.setc(isact); + let s = self.fmt(n, v); + let cv = self.cv(); + cv.boxr(x, y, w, h); + cv.set_font(1); + let ty = y + ((h - 8.0) * 0.5).floor(); + cv.text(x + 3.0, ty, lbl); + cv.textr(x, ty, w - 3.0, &s); + cv.fill(x + 2.0, y + h - 3.0, ((t * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(false); + } + + /// two stacked params in one cell (label left, value right) + fn cell2(&mut self, na: usize, nb: usize, x: f32, y: f32, w: f32, h: f32, la: &str, lb: &str) { + let hh = (h * 0.5).floor(); + let ha = self.hit(x, y, w, hh); + let hb = self.hit(x, y + hh, w, h - hh); + if ha && self.kit().press && self.kit().act == 0 { + self.begin_drag(na); + } + if hb && self.kit().press && self.kit().act == 0 { + self.begin_drag(nb); + } + if ha && self.kit().wheel != 0 { + self.wheel_adj(na); + } + if hb && self.kit().wheel != 0 { + self.wheel_adj(nb); + } + let act = self.kit().act; + self.setc(act == na as i32 || act == nb as i32); + self.cv().boxr(x, y, w, h); + self.setc(false); + self.cv().fill(x, y + hh, w, 1.0); + self.cv().set_font(1); + self.setc(act == na as i32); + let va = self.sget(na); + let s = self.fmt(na, va); + let ta = self.n2t(na, va); + { + let cv = self.cv(); + cv.text(x + 3.0, y + 3.0, la); + cv.textr(x, y + 3.0, w - 3.0, &s); + cv.fill(x + 2.0, y + hh - 3.0, ((ta * (w - 4.0)).floor()).max(1.0), 1.0); + } + self.setc(act == nb as i32); + let vb = self.sget(nb); + let s = self.fmt(nb, vb); + let tb = self.n2t(nb, vb); + { + let cv = self.cv(); + cv.text(x + 3.0, y + hh + 3.0, lb); + cv.textr(x, y + hh + 3.0, w - 3.0, &s); + cv.fill(x + 2.0, y + h - 4.0, ((tb * (w - 4.0)).floor()).max(1.0), 2.0); + } + self.setc(false); + } + + /// lit: 0 off, 1 white, 2 red + fn btn(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8) -> bool { + let hv = self.hit(x, y, w, h); + let clicked = hv && self.kit().press && self.kit().act == 0; + if lit > 0 { + self.setc(lit > 1); + self.cv().fill(x, y, w, h); + self.cv().setbg(); + } else { + self.setc(false); + self.cv().boxr(x, y, w, h); + } + let cv = self.cv(); + cv.set_font(1); + cv.textc(x, y + ((h - 8.0) * 0.5).floor(), w, s); + self.setc(false); + clicked + } + + /// 12x12 close cross (draw view corner); bright on hover. + fn close_glyph(&mut self, x: f32, y: f32, hover: bool) { + let prev = self.kit().dk; + self.set_dk(prev * if hover { 1.0 } else { 0.6 }); + self.setc(false); + self.cv().line(x + 1.0, y + 1.0, x + 10.0, y + 10.0); + self.cv().line(x + 10.0, y + 1.0, x + 1.0, y + 10.0); + self.set_dk(prev); + } + + /// 12x12 symmetry glyph: an odd S-curve through a centre dot (the curve is mirrored through the origin). + fn sym_glyph(&mut self, x: f32, y: f32, on: bool, hover: bool) { + let prev = self.kit().dk; + self.set_dk(prev * if on || hover { 1.0 } else { 0.6 }); + self.setc(on); + let pts = [(0.0, 10.0), (3.0, 10.0), (5.0, 8.0), (6.0, 5.0), (7.0, 2.0), (9.0, 0.0), (12.0, 0.0)]; + for w in pts.windows(2) { + self.cv().line(x + w[0].0, y + w[0].1, x + w[1].0, y + w[1].1); + } + self.cv().fill(x + 5.0, y + 5.0, 2.0, 2.0); + self.set_dk(prev); + self.setc(false); + } + + /// module-active square: filled = active, outline = untouched; byp = outlined with an X + fn sqind(&mut self, x: f32, y: f32, s: f32, on: bool, lit: bool, byp: bool) { + if lit { + self.cv().setbg(); + } else { + self.setc(false); + } + { + let cv = self.cv(); + if byp { + cv.boxr(x, y, s, s); + cv.line(x, y, x + s - 1.0, y + s - 1.0); + cv.line(x + s - 1.0, y, x, y + s - 1.0); + } else if on { + cv.fill(x, y, s, s); + } else { + cv.boxr(x, y, s, s); + } + } + self.setc(false); + } + + /// click toggle of a 0/1 slot over a small square + fn sq_tog(&mut self, n: usize, x: f32, y: f32, s: f32) { + if self.hit(x - 3.0, y - 3.0, s + 6.0, s + 6.0) && self.kit().press && self.kit().act == 0 { + let v = if self.sget(n) > 0.5 { 0.0 } else { 1.0 }; + self.click_set(n, v); + self.kit().press = false; + } + } +} diff --git a/rust/satcomp-ui/src/lib.rs b/rust/satcomp-ui/src/lib.rs new file mode 100644 index 0000000..5dcb2c2 --- /dev/null +++ b/rust/satcomp-ui/src/lib.rs @@ -0,0 +1,36 @@ +//! Shared egui UI toolkit for the SatComp plug-in family. + +pub mod appearance; +pub mod canvas; +pub mod fft; +pub mod kit; +pub mod spectrum; + +use canvas::font_family; +use nih_plug_egui::egui::{self, FontData, FontDefinitions}; +use std::sync::Arc; + +/// Editor init: the embedded UI fonts (see `canvas::FONT_NAMES`, same order) and the egui style tweaks the canvas relies on. +pub fn init_ctx(ctx: &egui::Context) { + let mut fonts = FontDefinitions::default(); + let faces: [&'static [u8]; 11] = [ + include_bytes!("../assets/fonts/FiraCode-Regular.ttf"), + include_bytes!("../assets/fonts/JetBrainsMono-Regular.ttf"), + include_bytes!("../assets/fonts/GeistMono-Regular.ttf"), + include_bytes!("../assets/fonts/RobotoMono-Regular.ttf"), + include_bytes!("../assets/fonts/OxygenMono-Regular.ttf"), + include_bytes!("../assets/fonts/Doto-Black.ttf"), + include_bytes!("../assets/fonts/DMMono-Regular.ttf"), + include_bytes!("../assets/fonts/VictorMono-Regular.ttf"), + include_bytes!("../assets/fonts/AnonymousPro-Regular.ttf"), + include_bytes!("../assets/fonts/Inconsolata-Regular.ttf"), + include_bytes!("../assets/fonts/CourierPrime-Regular.ttf"), + ]; + for (i, bytes) in faces.iter().enumerate() { + fonts.font_data.insert(format!("f{i}"), Arc::new(FontData::from_static(bytes))); + fonts.families.insert(font_family(i), vec![format!("f{i}")]); + } + ctx.set_fonts(fonts); + ctx.tessellation_options_mut(|o| o.feathering = false); + ctx.style_mut(|s| s.animation_time = 0.0); +} diff --git a/rust/satcomp-ui/src/spectrum.rs b/rust/satcomp-ui/src/spectrum.rs new file mode 100644 index 0000000..e8aebe7 --- /dev/null +++ b/rust/satcomp-ui/src/spectrum.rs @@ -0,0 +1,118 @@ +//! FFT spectrum analyser for the viewports: 4096-point Hann window over the newest tap samples, smoothed in dB (fast attack, +//! slower release), then resampled to log-spaced screen columns with the usual +4.5 dB/oct tilt so pink noise reads flat. + +use crate::fft::fft; + +pub struct Spectrum { + win: Vec, + /// smoothed magnitude per bin in dB (2049 bins) + pub db: Vec, + t: f64, +} + +impl Default for Spectrum { + fn default() -> Self { + Self::new() + } +} + +impl Spectrum { + pub const N: usize = 4096; + + pub fn new() -> Self { + let win = (0..Self::N).map(|i| 0.5 - 0.5 * (2.0 * std::f32::consts::PI * i as f32 / Self::N as f32).cos()).collect(); + Self { win, db: vec![-140.0; Self::N / 2 + 1], t: 0.0 } + } + + /// Re-base the update clock (the egui clock restarts when the editor window is reopened). + pub fn rebase(&mut self, now: f64) { + self.t = now; + } + + /// Analyse at most every 30 ms. `head` = write position of the tap ring, `get(i)` reads sample `i` of it. + pub fn update(&mut self, now: f64, head: usize, get: impl Fn(usize) -> f32) { + if now - self.t < 0.03 { + return; + } + self.t = now; + let mut re = vec![0.0f32; Self::N]; + let mut im = vec![0.0f32; Self::N]; + let ix = head.wrapping_sub(Self::N); + for i in 0..Self::N { + re[i] = get(ix.wrapping_add(i)) * self.win[i]; + } + fft(&mut re, &mut im); + for k in 0..=Self::N / 2 { + let db = 8.6858896 * ((re[k] * re[k] + im[k] * im[k]).sqrt() * 0.0009765625 + 0.0000001).ln(); + let sp = &mut self.db[k]; + *sp += (db - *sp) * if db > *sp { 0.6 } else { 0.12 }; + } + } + + /// Level in dB (tilt-compensated) for `n` log-spaced columns from 20 Hz to 20 kHz. + pub fn columns(&self, n: usize, sample_rate: f32) -> Vec { + let bw = sample_rate / Self::N as f32; + let top = (Self::N / 2) as f32; + (0..n) + .map(|i| { + let flo = 20.0 * (i as f32 / n as f32 * 6.9077553).exp(); + let fhi = 20.0 * ((i + 1) as f32 / n as f32 * 6.9077553).exp(); + let bl = (flo / bw).min(top - 2.0); + let bh = (fhi / bw).min(top - 1.0); + let mut v; + if bh - bl < 1.0 { + let k = bl.floor() as usize; + let fr = bl - k as f32; + v = self.db[k] + (self.db[k + 1] - self.db[k]) * fr; + } else { + v = -140.0; + let (mut k, kk) = (bl.floor() as usize, bh.floor() as usize); + let mut cnt = 0; + while k <= kk && cnt < 512 { + v = v.max(self.db[k]); + k += 1; + cnt += 1; + } + } + v + 6.4921 * ((flo * fhi).sqrt() / 1000.0).ln() + }) + .collect() + } +} + +/// Screen x for a frequency on the 20 Hz .. 20 kHz log axis. +pub fn freq_to_x(f: f32, x0: f32, w: f32) -> f32 { + x0 + (f.max(20.0) / 20.0).ln() / 6.9077553 * w +} + +/// Frequency for a screen x on the 20 Hz .. 20 kHz log axis. +pub fn x_to_freq(x: f32, x0: f32, w: f32) -> f32 { + 20.0 * (((x - x0) / w).clamp(0.0, 1.0) * 6.9077553).exp() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_sine_peaks_at_its_log_column() { + let sr = 48000.0f32; + let mut sp = Spectrum::new(); + let sig: Vec = (0..8192).map(|i| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / sr).sin()).collect(); + for k in 0..30 { + sp.update(1.0 + k as f64 * 0.05, 8192, |i| sig[i % 8192]); + } + let cols = sp.columns(400, sr); + let peak = cols.iter().cloned().enumerate().fold((0, -999.0f32), |a, (i, v)| if v > a.1 { (i, v) } else { a }).0; + let expect = ((1000.0f32 / 20.0).ln() / 6.9077553 * 400.0) as i32; + assert!((peak as i32 - expect).abs() <= 3, "{peak} vs {expect}"); + } + + #[test] + fn axis_mapping_round_trips() { + for f in [20.0, 100.0, 1000.0, 20000.0] { + let x = freq_to_x(f, 10.0, 400.0); + assert!((x_to_freq(x, 10.0, 400.0) - f).abs() / f < 1e-3); + } + } +} diff --git a/rust/satlim-dsp/Cargo.toml b/rust/satlim-dsp/Cargo.toml new file mode 100644 index 0000000..fda8d9c --- /dev/null +++ b/rust/satlim-dsp/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "satlim-dsp" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +satcomp-dsp = { path = "../satcomp-dsp" } diff --git a/rust/satlim-dsp/src/engine.rs b/rust/satlim-dsp/src/engine.rs new file mode 100644 index 0000000..52eb4ef --- /dev/null +++ b/rust/satlim-dsp/src/engine.rs @@ -0,0 +1,602 @@ +//! SatLim engine: SAT (shared saturator, optionally oversampled) -> level into the ceiling (`ceiling - threshold`) -> +//! CLIP (oversampled hard clip at the ceiling, driven up to +6 dB into it) -> true-peak brickwall limiter -> OUT GAIN. +//! +//! OUT GAIN is after the limiter on purpose: the ceiling is what the limiter holds, the output gain is the owner's to +//! trim (a clipped -0.4 dBTP still has inter-sample peaks that a downstream converter may see). The reported latency is +//! always the sum of the saturator oversampler, the clipper oversampler and the limiter lookahead (0 with L.AHD off). +//! Stereo, f64 inside. + +use crate::params::LimParams; +use satcomp_dsp::delay::StereoDelay; +use satcomp_dsp::halfband::{self, Oversampler, Taps}; +use satcomp_dsp::level::{ms_step, one_pole, Matcher, DB_AMP, LN10_20}; +use satcomp_dsp::{Limiter, SatParams, Saturator, ScopeRing, TruePeak}; +use std::sync::Arc; + +/// Delay ring length: larger than the longest latency (30 + 30 + the limiter's 32 + 952 at the highest rates). +const RING: usize = 2048; + +pub struct LimEngine { + sr: f64, + sr_prev: f64, + p: LimParams, + dirty: bool, + first_set: bool, + snap: bool, + /// Smooth Drive / Bias / Mix (set false for null tests). + pub smoothing: bool, + sat: Saturator, + taps: Taps, + ov: [Oversampler; 2], + lim: Limiter, + tp: TruePeak, + /// the signal entering the clipper, delayed to line up with the limiter output (for the delta and the scope) + pre: StereoDelay, + dry: StereoDelay, + thr_g: f64, + thr_t: f64, + og: f64, + og_t: f64, + byp_s: f64, + sm_c: f64, + byp_c: f64, + rms_c: f64, + ceil: f64, + clip_k: f64, + clip_on: bool, + os: i32, + /// monitor what the clipper + limiter removed (UI -> audio) + pub delta_on: bool, + pub scope: Arc, + sc_len: usize, + sc_n: usize, + sc_o: f64, + sc_m: f64, + sc_p: f64, + // telemetry, audio -> UI. The shell takes the peaks with fetch_max and clears them. + /// output peak per channel (after OUT GAIN), linear + pub opk: [f64; 2], + /// output true peak (also while L.AHD is off), linear + pub tpk: f64, + /// post-saturator (after SAT GAIN) peak, linear + pub sat_out: f64, + /// decaying peak of the saturator input for the plot's live dot + pub sat_vz: f64, + /// limiter gain reduction peak, dB positive + pub gr_pk: f64, + /// what the clipper took off the loudest peak, dB positive (0 with CLIP off) + pub clip_gr_pk: f64, + /// smoothed output mean-square (RMS readout) + pub fms: f64, + /// loudness change across the saturator (before SAT GAIN), dB: the plot's SAT readout + pub sat_db: f64, + ims: f64, + sat_m: Matcher, + sat_req: bool, + sat_result: Option, + pub clip_f: bool, +} + +impl LimEngine { + pub fn new(sr: f64) -> Self { + let mut e = Self { + sr, + sr_prev: 0.0, + p: LimParams::default(), + dirty: true, + first_set: true, + snap: true, + smoothing: true, + sat: Saturator::new(), + taps: Taps::new(), + ov: [Oversampler::default(), Oversampler::default()], + lim: { + // 8x detection: what reaches this limiter is clipped / heavily shaped, all inter-sample peaks + let mut l = Limiter::new(sr); + l.set_hi(true); + l + }, + tp: TruePeak::with_precision(sr, true), + pre: StereoDelay::new(), + dry: StereoDelay::new(), + thr_g: 1.0, + thr_t: 1.0, + og: 1.0, + og_t: 1.0, + byp_s: 0.0, + sm_c: 0.0, + byp_c: 0.0, + rms_c: 0.0, + ceil: 1.0, + clip_k: 1.0, + clip_on: false, + os: 0, + delta_on: false, + scope: Arc::new(ScopeRing::new()), + sc_len: 96, + sc_n: 0, + sc_o: 0.0, + sc_m: 0.0, + sc_p: 0.0, + opk: [0.0; 2], + tpk: 0.0, + sat_out: 0.0, + sat_vz: 0.0, + gr_pk: 0.0, + clip_gr_pk: 0.0, + fms: 1e-9, + sat_db: 0.0, + ims: 1e-9, + sat_m: Matcher::default(), + sat_req: false, + sat_result: None, + clip_f: false, + }; + e.derive(); + e + } + + pub fn sample_rate(&self) -> f64 { + self.sr + } + + pub fn set_sample_rate(&mut self, sr: f64) { + self.sr = sr; + self.dirty = true; + } + + pub fn set_params(&mut self, p: &LimParams) { + if self.first_set { + // a fresh engine starts at the host's settings instead of gliding there from defaults + self.first_set = false; + self.p = *p; + self.sat.set_out_db(p.sat_gain); + self.lim.snap_on(true); + self.snap = true; + let sm = std::mem::replace(&mut self.smoothing, false); + self.derive(); + self.smoothing = sm; + return; + } + if *p != self.p { + if p.sat_gain != self.p.sat_gain { + self.sat.set_out_db(p.sat_gain); + } + self.p = *p; + self.derive(); // applied at once so latency() is valid before the first block + } + } + + /// PDC latency to report: saturator oversampler + clipper oversampler + limiter lookahead. + pub fn latency(&self) -> u32 { + (self.sat.latency() + halfband::latency(self.os) + self.lim.latency()) as u32 + } + + fn derive(&mut self) { + let p = self.p; + let sr = self.sr; + self.dirty = false; + if sr != self.sr_prev { + self.sr_prev = sr; + self.lim.set_sample_rate(sr); + self.tp = TruePeak::with_precision(sr, true); + self.sc_len = ((sr * ScopeRing::BUCKET_S).round() as usize).max(1); + self.sm_c = one_pole(sr, 0.02); + self.byp_c = one_pole(sr, 0.005); + self.rms_c = one_pole(sr, 0.3); + } + let sp: SatParams = p.sat(); + self.sat.derive(&sp, sr, self.snap, self.smoothing); + self.os = p.os.clamp(0, 3); + self.ceil = 10f64.powf(p.ceiling / 20.0); + self.lim.set_ceiling_db(p.ceiling); + self.lim.set_release_ms(p.release); + self.lim.set_clip(false); // the clipper is this engine's own (oversampled) + self.lim.set_lookahead(p.lookahead); + self.clip_on = p.clip > 0.0; + self.clip_k = 10f64.powf(p.clip * 0.01 * 6.0 / 20.0); + self.thr_t = ((p.ceiling - p.threshold) * LN10_20).exp(); + self.og_t = (p.out_gain * LN10_20).exp(); + if self.snap { + self.thr_g = self.thr_t; + self.og = self.og_t; + self.byp_s = if p.bypass { 1.0 } else { 0.0 }; + self.snap = false; + } + } + + /// Measure the saturator's loudness change for 3 s, then report the SAT GAIN that cancels it (a second call cancels). + pub fn request_sat_match(&mut self) { + self.sat_req = true; + } + + pub fn sat_matching(&self) -> bool { + self.sat_m.active + } + + /// Seconds measured so far (0..3). + pub fn sat_match_progress(&self) -> f64 { + self.sat_m.t + } + + /// The finished match, once (the shell writes it to the SAT GAIN parameter). + pub fn take_sat_result(&mut self) -> Option { + self.sat_result.take() + } + + pub fn begin_block(&mut self, n: usize) { + if self.dirty || self.sr != self.sr_prev { + self.derive(); + } + self.sat.begin_block(); + let vz_d = (-(n as f64) / (self.sr * 0.15)).exp(); + self.sat_vz = self.sat.blk.max(self.sat_vz * vz_d); + self.sat.blk = 0.0; + // loudness change across the saturator, and the 3 s level match that writes SAT GAIN (only while there is signal) + let gate = self.ims > 0.000001; + if gate { + self.sat_db = 4.3429448 * (self.sat.ms.max(1e-12) / self.ims.max(1e-12)).ln(); + } + if self.sat_req { + let was = self.sat_m.active; + self.sat_m.start(); + if was { + self.sat_m.stop(); // a second click cancels + } + self.sat_req = false; + } + if self.sat_m.active && gate { + if let Some(avg) = self.sat_m.step(self.sat_db, n as f64 / self.sr) { + let v = (avg.clamp(-24.0, 12.0) * 10.0 + 0.5).floor() * 0.1; + self.sat.set_out_db(v); + self.sat_result = Some(v); + } + } + } + + pub fn process(&mut self, left: &mut [f32], right: &mut [f32]) { + let n = left.len().min(right.len()); + self.begin_block(n); + for i in 0..n { + let (l, r) = self.tick(left[i] as f64, right[i] as f64); + left[i] = l as f32; + right[i] = r as f32; + } + let g = self.lim.gmin.max(1e-6); + self.gr_pk = self.gr_pk.max(-g.ln() * DB_AMP); + self.lim.gmin = 1.0; + } + + #[inline] + pub fn tick(&mut self, in_l: f64, in_r: f64) -> (f64, f64) { + let inp = [in_l, in_r]; + self.dry.advance(); + self.dry.put(inp); + self.pre.advance(); + + // SAT, then the level that maps the threshold onto the ceiling + let s = self.sat.tick(inp, self.smoothing); + ms_step(&mut self.ims, inp[0], inp[1], self.rms_c); + self.sat_out = self.sat_out.max(s[0].abs().max(s[1].abs())); + self.thr_g += (self.thr_t - self.thr_g) * self.sm_c; + let t = [s[0] * self.thr_g, s[1] * self.thr_g]; + self.pre.put(t); + + // CLIP: hard clip at the ceiling in the oversampled domain (always through the filters: constant latency) + let (k, c, on) = (self.clip_k, self.ceil, self.clip_on); + let mut cl = [0.0f64; 2]; + for ch in 0..2 { + cl[ch] = self.ov[ch].process_fn(&self.taps, self.os, t[ch], |v| if on { (v * k).clamp(-c, c) } else { v }); + } + + // what the clipper took off: how far the pre-clip peak stood above the clipped one at the same instant, counted + // only above the ceiling. Oversampled, the two also differ by the filters alone (near a zero crossing of the + // clipped signal that ratio is anything), so the clipped side never counts as lower than the ceiling. At x1 a + // clipped sample is exactly the ceiling: the same number as the plain ratio. + if on { + let td = self.pre.tap(halfband::latency(self.os)); + let (pt, pc) = (td[0].abs().max(td[1].abs()), cl[0].abs().max(cl[1].abs()).max(c)); + if pt > pc * 1.0001 { + self.clip_gr_pk = self.clip_gr_pk.max(8.6858896 * (pt / pc).ln()); + } + } + + // LIMITER + let lo = self.lim.tick(cl, true); + let lat_pre = halfband::latency(self.os) + self.lim.latency(); + let pd = self.pre.tap(lat_pre); + self.og += (self.og_t - self.og) * self.sm_c; + let y = [lo[0] * self.og, lo[1] * self.og]; + + // monitors and bypass + let removed = [pd[0] - lo[0], pd[1] - lo[1]]; + let proc = if self.delta_on { removed } else { y }; + self.byp_s += ((if self.p.bypass { 1.0 } else { 0.0 }) - self.byp_s) * self.byp_c; + let dd = self.dry.tap(self.sat.latency() + lat_pre); + let out = if self.byp_s > 1e-9 { [proc[0] + (dd[0] - proc[0]) * self.byp_s, proc[1] + (dd[1] - proc[1]) * self.byp_s] } else { proc }; + + // telemetry + self.opk[0] = self.opk[0].max(out[0].abs()); + self.opk[1] = self.opk[1].max(out[1].abs()); + if out[0].abs() > 0.9999 || out[1].abs() > 0.9999 { + self.clip_f = true; + } + // true peak at all times: with L.AHD off the limiter only holds the sample peaks, and the readout must show what got past + let pkv = self.tp.tick(out); + self.tpk = self.tpk.max(pkv); + ms_step(&mut self.fms, out[0], out[1], self.rms_c); + let ao = out[0].abs().max(out[1].abs()); + // scope: output, the peak the limiter was handed (after the clipper), the peak before the clipper + let am = self.lim.last_in[0].abs().max(self.lim.last_in[1].abs()) * self.og; + self.sc_o = self.sc_o.max(ao); + self.sc_m = self.sc_m.max(am).max(ao); + self.sc_p = self.sc_p.max((pd[0].abs().max(pd[1].abs())) * self.og).max(am).max(ao); + self.sc_n += 1; + if self.sc_n >= self.sc_len { + self.scope.push3(self.sc_o as f32, self.sc_m as f32, self.sc_p as f32); + self.sc_o = 0.0; + self.sc_m = 0.0; + self.sc_p = 0.0; + self.sc_n = 0; + } + (out[0], out[1]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f64::consts::PI; + + const SR: f64 = 48000.0; + + fn noise(n: usize, seed: u64, amp: f64) -> Vec { + let mut s = seed; + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((((s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0) * amp) as f32 + }) + .collect() + } + + fn run(p: &LimParams, x: &[f32]) -> (Vec, LimEngine) { + let mut e = LimEngine::new(SR); + e.set_params(p); + let (mut l, mut r) = (x.to_vec(), x.to_vec()); + for (cl, cr) in l.chunks_mut(256).zip(r.chunks_mut(256)) { + e.process(cl, cr); + } + (l, e) + } + + fn db(x: f64) -> f64 { + 20.0 * x.max(1e-12).log10() + } + + #[test] + fn quiet_signal_is_an_exact_delayed_copy_at_x1() { + for look in [true, false] { + let p = LimParams { ceiling: 0.0, lookahead: look, ..LimParams::default() }; + let x = noise(20000, 3, 0.4); + let (y, e) = run(&p, &x); + let lat = e.latency() as usize; + assert_eq!(lat, if look { 104 } else { 0 }); + for i in lat..x.len() { + assert_eq!(y[i], x[i - lat], "look {look} sample {i}"); + } + } + } + + #[test] + fn latency_adds_the_saturator_the_clipper_and_the_limiter() { + for (os, extra) in [(0, 0), (1, 48), (2, 56), (3, 60)] { + let mut e = LimEngine::new(SR); + e.set_params(&LimParams { os, ..LimParams::default() }); + assert_eq!(e.latency() as usize, 104 + extra, "os {os}"); + e.set_params(&LimParams { os, lookahead: false, ..LimParams::default() }); + assert_eq!(e.latency() as usize, extra, "os {os}, no lookahead"); + } + } + + #[test] + fn bypass_is_the_input_at_the_reported_latency() { + let p = LimParams { os: 2, drive: 60.0, threshold: -12.0, clip: 80.0, bypass: true, ..LimParams::default() }; + let x = noise(20000, 5, 0.5); + let (y, e) = run(&p, &x); + let lat = e.latency() as usize; + for i in lat + 100..x.len() { + assert!((y[i] - x[i - lat]).abs() < 1e-6, "sample {i}"); + } + } + + #[test] + fn the_output_holds_the_ceiling_before_out_gain() { + // hot programme, threshold -14 lifts it 13 dB into a -1 dB ceiling + for (os, look, clip) in [(0, true, 0.0), (2, true, 60.0), (0, false, 0.0), (3, false, 100.0)] { + let p = LimParams { ceiling: -1.0, threshold: -14.0, os, lookahead: look, clip, release: 40.0, ..LimParams::default() }; + let x = noise(48000, 11, 0.9); + let (y, e) = run(&p, &x); + let pk = y[4000..].iter().fold(0.0f32, |m, v| m.max(v.abs())) as f64; + // sample peaks: exact with the lookahead off; the true-peak limiter keeps the interpolated peaks near the ceiling + // and the filtered clipper can ring a little over it + assert!(db(pk) < -1.0 + 0.3, "os {os} look {look} clip {clip}: peak {:.2} dB", db(pk)); + // (with the lookahead off only the sample peaks are held: the readout is still the true peak, and reads over) + assert!(!look || db(e.tpk) < -1.0 + 0.6, "os {os} look {look} clip {clip}: true peak {:.2} dB", db(e.tpk)); + assert!(db(pk) > -2.5, "it limits close to the ceiling, not far below it: {:.2}", db(pk)); + } + } + + #[test] + fn out_gain_is_after_the_ceiling() { + let p = LimParams { ceiling: -1.0, threshold: -10.0, out_gain: -3.0, ..LimParams::default() }; + let x: Vec = (0..48000).map(|i| (0.9 * (2.0 * PI * 1000.0 * i as f64 / SR).sin()) as f32).collect(); + let (y, _) = run(&p, &x); + let pk = y[4000..].iter().fold(0.0f32, |m, v| m.max(v.abs())) as f64; + assert!(db(pk) < -4.0 + 0.2 && db(pk) > -4.4, "{:.2}", db(pk)); + } + + #[test] + fn clip_takes_the_spikes_so_the_limiter_ducks_less() { + let mut x = vec![0.0f32; 48000]; + for (i, v) in x.iter_mut().enumerate() { + let t = i as f64 / SR; + *v = (0.3 * (2.0 * PI * 200.0 * t).sin()) as f32; + if i % 4800 == 2400 { + *v += 3.0; + } + } + let base = LimParams { ceiling: -1.0, lookahead: true, ..LimParams::default() }; + let (_, off) = run(&LimParams { clip: 0.0, ..base }, &x); + let (_, on) = run(&LimParams { clip: 100.0, ..base }, &x); + assert!(off.gr_pk > 6.0, "limiter alone ducks on the spikes: {}", off.gr_pk); + assert!(on.gr_pk < off.gr_pk * 0.6, "clip on {} vs off {}", on.gr_pk, off.gr_pk); + } + + #[test] + fn delta_is_what_the_clipper_and_limiter_removed() { + let x = noise(24000, 17, 0.9); + let p = LimParams { ceiling: -1.0, threshold: -12.0, clip: 50.0, ..LimParams::default() }; + let mut e = LimEngine::new(SR); + e.set_params(&p); + e.delta_on = true; + let (mut l, mut r) = (x.clone(), x.clone()); + for (cl, cr) in l.chunks_mut(256).zip(r.chunks_mut(256)) { + e.process(cl, cr); + } + let rms = |v: &[f32]| (v[4000..].iter().map(|a| (*a as f64).powi(2)).sum::() / (v.len() - 4000) as f64).sqrt(); + assert!(rms(&l) > 0.05, "heavy limiting leaves a real delta: {}", rms(&l)); + // nothing to remove on a quiet signal + let q = noise(24000, 19, 0.05); + let mut e = LimEngine::new(SR); + e.set_params(&LimParams { ceiling: 0.0, ..LimParams::default() }); + e.delta_on = true; + let (mut l, mut r) = (q.clone(), q.clone()); + for (cl, cr) in l.chunks_mut(256).zip(r.chunks_mut(256)) { + e.process(cl, cr); + } + assert!(rms(&l) < 1e-9, "{}", rms(&l)); + } + + #[test] + fn telemetry_reads_the_stages() { + let p = LimParams { ceiling: -1.0, threshold: -10.0, drive: 30.0, ..LimParams::default() }; + let x = noise(24000, 23, 0.8); + let (_, e) = run(&p, &x); + assert!(e.gr_pk > 3.0, "{}", e.gr_pk); + assert!(e.sat_out > 0.2 && e.opk[0] > 0.5 && e.tpk >= e.opk[0] as f64 - 1e-9, "{} {:?} {}", e.sat_out, e.opk, e.tpk); + assert!(e.scope.head() > 100); + } + + #[test] + fn sat_match_measures_for_three_seconds_then_reports_the_gain_that_cancels_the_change() { + let p = LimParams { drive: 60.0, ceiling: 0.0, ..LimParams::default() }; + let mut e = LimEngine::new(SR); + e.set_params(&p); + e.request_sat_match(); + let x = noise(48000 * 4, 29, 0.3); + let (mut l, mut r) = (x.clone(), x.clone()); + let mut got = None; + for (cl, cr) in l.chunks_mut(256).zip(r.chunks_mut(256)) { + e.process(cl, cr); + if let Some(v) = e.take_sat_result() { + got = Some(v); + } + } + let v = got.expect("the measurement finishes within 4 s"); + assert!(v < -1.0 && v > -24.0, "drive 60 on noise is louder, the match turns it down: {v}"); + assert!((v + e.sat_db).abs() < 0.6, "match {v} vs measured change {}", e.sat_db); + assert!(e.take_sat_result().is_none()); + } + + #[test] + fn the_clipper_and_the_limiter_report_their_own_reduction() { + let mut x = vec![0.0f32; 48000]; + for (i, v) in x.iter_mut().enumerate() { + *v = (0.3 * (2.0 * PI * 200.0 * i as f64 / SR).sin()) as f32; + if i % 4800 == 2400 { + *v += 3.0; + } + } + let base = LimParams { ceiling: -1.0, ..LimParams::default() }; + let (_, off) = run(&LimParams { clip: 0.0, ..base }, &x); + let (_, on) = run(&LimParams { clip: 100.0, ..base }, &x); + assert!(off.clip_gr_pk < 0.01, "no clip, no clip reduction: {}", off.clip_gr_pk); + assert!(off.gr_pk > 6.0); + assert!(on.clip_gr_pk > 6.0, "the clipper takes the spike: {}", on.clip_gr_pk); + assert!(on.gr_pk < off.gr_pk * 0.6, "so the limiter has less to do: {} vs {}", on.gr_pk, off.gr_pk); + } + + #[test] + fn the_clip_reduction_readout_stays_sane_when_oversampled() { + // spikes of 3.3 into a -1 dB ceiling: the clipper takes about 11 dB at every oversampling setting + let mut x = vec![0.0f32; 48000]; + for (i, v) in x.iter_mut().enumerate() { + *v = (0.3 * (2.0 * PI * 200.0 * i as f64 / SR).sin()) as f32; + if i % 4800 == 2400 { + *v += 3.0; + } + } + for os in 0..4 { + let (_, e) = run(&LimParams { ceiling: -1.0, clip: 100.0, os, ..LimParams::default() }, &x); + assert!(e.clip_gr_pk > 5.0 && e.clip_gr_pk < 11.6, "os {os}: {}", e.clip_gr_pk); + } + // full-band noise far over the ceiling: never more than the input stood above it (peak 0.9 * 11 dB lift = 11.1 dB over) + let n = noise(48000, 31, 0.9); + for os in 0..4 { + let (_, e) = run(&LimParams { ceiling: -1.0, threshold: -12.0, clip: 100.0, os, ..LimParams::default() }, &n); + assert!(e.clip_gr_pk > 6.0 && e.clip_gr_pk < 11.2, "noise os {os}: {}", e.clip_gr_pk); + } + } + + #[test] + fn switching_the_lookahead_on_mid_stream_lets_nothing_over_the_ceiling() { + let p0 = LimParams { ceiling: -1.0, threshold: -12.0, lookahead: false, ..LimParams::default() }; + let mut e = LimEngine::new(SR); + e.set_params(&p0); + let mut l: Vec = (0..48000).map(|i| (0.9 * (2.0 * PI * 1000.0 * i as f64 / SR).sin()) as f32).collect(); + let mut r = l.clone(); + let mut pk = 0.0f32; + for (i, (a, b)) in l.chunks_mut(64).zip(r.chunks_mut(64)).enumerate() { + if i == 375 { + e.set_params(&LimParams { lookahead: true, ..p0 }); + } + e.process(a, b); + pk = a.iter().fold(pk, |m, v| m.max(v.abs())); + } + assert!(db(pk as f64) <= -1.0 + 1e-3, "peak {:.2} dB", db(pk as f64)); + } + + #[test] + fn the_peak_readout_is_true_peak_with_the_lookahead_off_too() { + // fs/4 tone sampled 45 degrees off its crests: the sample-peak limiter holds the samples at the ceiling, the true peak is 3 dB above + let x: Vec = (0..24000).map(|i| (2.0 * (PI * 0.5 * i as f64 + PI / 4.0).sin()) as f32).collect(); + let (y, e) = run(&LimParams { ceiling: -1.0, lookahead: false, ..LimParams::default() }, &x); + let pk = y[4000..].iter().fold(0.0f32, |m, v| m.max(v.abs())) as f64; + assert!(db(pk) <= -1.0 + 1e-3, "samples held: {:.2}", db(pk)); + assert!(db(e.tpk) > 1.5, "the readout shows the inter-sample over: {:.2}", db(e.tpk)); + } + + #[test] + fn the_scope_buckets_are_ordered_output_then_limiter_then_clipper() { + let mut x = vec![0.0f32; 24000]; + for (i, v) in x.iter_mut().enumerate() { + *v = (0.4 * (2.0 * PI * 300.0 * i as f64 / SR).sin()) as f32; + if i % 2400 == 1200 { + *v += 2.5; + } + } + for (clip, want_lim, want_clip) in [(0.0, true, false), (100.0, false, true)] { + let (_, e) = run(&LimParams { ceiling: -1.0, clip, ..LimParams::default() }, &x); + let head = e.scope.head(); + let (mut saw_lim, mut saw_clip) = (false, false); + for i in 20..head { + let (o, m, p) = e.scope.get3(i); + assert!(o <= m + 1e-6 && m <= p + 1e-6, "clip {clip} bucket {i}: {o} {m} {p}"); + saw_lim |= m > o * 1.05; + saw_clip |= p > m * 1.05; + } + assert_eq!((saw_lim, saw_clip), (want_lim, want_clip), "clip {clip}"); + } + } +} diff --git a/rust/satlim-dsp/src/lib.rs b/rust/satlim-dsp/src/lib.rs new file mode 100644 index 0000000..210bf4d --- /dev/null +++ b/rust/satlim-dsp/src/lib.rs @@ -0,0 +1,8 @@ +//! DSP for SatLim: the SatComp saturator module into an oversampled clipper and a true-peak brickwall limiter, built from +//! the shared `satcomp-dsp` blocks. + +pub mod engine; +pub mod params; + +pub use engine::LimEngine; +pub use params::LimParams; diff --git a/rust/satlim-dsp/src/params.rs b/rust/satlim-dsp/src/params.rs new file mode 100644 index 0000000..0a7010a --- /dev/null +++ b/rust/satlim-dsp/src/params.rs @@ -0,0 +1,81 @@ +//! SatLim parameter set (plain f64 values; the plug-in shell maps its nih-plug parameters onto this). + +use satcomp_dsp::shapers::{Curve, SHAPER_COUNT}; +use satcomp_dsp::SatParams; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct LimParams { + // SAT (the SatComp saturator module, verbatim) + pub shape: i32, + pub curve: Curve, + /// ASYM per shaper, 0..100 %; the active one is `asym[shape]` + pub asym: [f64; SHAPER_COUNT], + pub drive: f64, + pub bias: f64, + pub sat_hp: f64, + pub sat_lp: f64, + pub tone: f64, + pub sat_mix: f64, + /// dB after the saturator (SAT GAIN) + pub sat_gain: f64, + /// oversampling of the saturator and the clipper: 0 x1, 1 x2, 2 x4, 3 x8 + pub os: i32, + // LIMITER + /// lookahead + true-peak detection on (latency) or off (zero latency, sample peak, instant attack) + pub lookahead: bool, + /// dBTP the output is held under (before OUT GAIN) + pub ceiling: f64, + /// dB: the input level that is mapped onto the ceiling, so the signal is lifted by `ceiling - threshold` + pub threshold: f64, + /// ms, the slow end of the program-dependent release (the fast end stays at 15 ms or below) + pub release: f64, + /// 0..100 %: oversampled hard clip at the ceiling, driven up to +6 dB into it. 0 = off + pub clip: f64, + /// dB after the limiter: free by design, the way StandardClip's output gain is + pub out_gain: f64, + pub bypass: bool, +} + +impl Default for LimParams { + fn default() -> Self { + Self { + shape: 0, + curve: Curve::linear(), + asym: [100.0; SHAPER_COUNT], + drive: 0.0, + bias: 0.0, + sat_hp: 20.0, + sat_lp: 20000.0, + tone: 20000.0, + sat_mix: 100.0, + sat_gain: 0.0, + os: 0, + lookahead: true, + ceiling: -0.3, + threshold: 0.0, + release: 80.0, + clip: 0.0, + out_gain: 0.0, + bypass: false, + } + } +} + +impl LimParams { + pub fn sat(&self) -> SatParams { + SatParams { + shape: self.shape, + curve: self.curve, + drive: self.drive, + bias: self.bias, + hp: self.sat_hp, + lp: self.sat_lp, + tone: self.tone, + os: self.os, + mix: self.sat_mix, + out_db: self.sat_gain, + asym: Some(self.asym[(self.shape.max(0) as usize).min(SHAPER_COUNT - 1)]), + steep: false, + } + } +} diff --git a/rust/satlim-plugin/Cargo.toml b/rust/satlim-plugin/Cargo.toml new file mode 100644 index 0000000..67ce11e --- /dev/null +++ b/rust/satlim-plugin/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "satlim" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-or-later" +publish = false + +[lib] +crate-type = ["cdylib", "lib"] + +[dependencies] +nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", features = ["vst3"] } +satcomp-dsp = { path = "../satcomp-dsp" } +satlim-dsp = { path = "../satlim-dsp" } +satcomp-ui = { path = "../satcomp-ui" } +nih_plug_egui = { path = "../vendor/nih_plug_egui" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +parking_lot = "0.12" +include_dir = "0.7" + +[target.'cfg(any(target_os = "macos", windows))'.dependencies] +rfd = { version = "0.15", default-features = false } + +[features] +# `cargo run -p satlim --features standalone --bin satlim-standalone` opens the editor in a plain window (dev aid) +standalone = ["nih_plug/standalone"] + +[[bin]] +name = "satlim-standalone" +path = "src/standalone.rs" +required-features = ["standalone"] diff --git a/rust/satlim-plugin/presets/Baked.json b/rust/satlim-plugin/presets/Baked.json new file mode 100644 index 0000000..a48a1c1 --- /dev/null +++ b/rust/satlim-plugin/presets/Baked.json @@ -0,0 +1,22 @@ +{ + "format": "satlim-preset", + "version": 1, + "name": "Baked", + "params": { + "bias": 0.0, + "ceiling": -0.4, + "clip": 25.0, + "drive": 30.5, + "lookahead": 1.0, + "os": 2.0, + "out_gain": 0.0, + "release": 35.0, + "sat_gain": 0.0, + "sat_hp": 81.0, + "sat_lp": 7450.0, + "sat_mix": 30.0, + "shape": 12.0, + "threshold": -2.0, + "tone": 20000.0 + } +} diff --git a/rust/satlim-plugin/presets/Drums_Crunch.json b/rust/satlim-plugin/presets/Drums_Crunch.json new file mode 100644 index 0000000..50f4775 --- /dev/null +++ b/rust/satlim-plugin/presets/Drums_Crunch.json @@ -0,0 +1,22 @@ +{ + "format": "satlim-preset", + "version": 1, + "name": "Drums_Crunch", + "params": { + "shape": 13.0, + "drive": 30.0, + "bias": 0.0, + "sat_hp": 20.0, + "sat_lp": 20000.0, + "tone": 20000.0, + "sat_mix": 30.0, + "sat_gain": 0.0, + "os": 2.0, + "lookahead": 0.0, + "ceiling": -1.0, + "threshold": -6.0, + "release": 30.0, + "clip": 20.0, + "out_gain": 0.0 + } +} diff --git a/rust/satlim-plugin/presets/Faulty_Gate.json b/rust/satlim-plugin/presets/Faulty_Gate.json new file mode 100644 index 0000000..b5640cb --- /dev/null +++ b/rust/satlim-plugin/presets/Faulty_Gate.json @@ -0,0 +1,40 @@ +{ + "format": "satlim-preset", + "version": 1, + "name": "Faulty Gate", + "params": { + "bias": 0.0, + "ceiling": -0.3, + "clip": 20.0, + "drive": 15.0, + "lookahead": 1.0, + "os": 2.0, + "out_gain": 0.0, + "release": 18.0, + "sat_gain": 0.0, + "sat_hp": 80.0, + "sat_lp": 12010.0, + "sat_mix": 100.0, + "shape": 14.0, + "threshold": -4.0, + "tone": 20000.0 + }, + "curve": [ + [ + -1.0, + -1.0 + ], + [ + -0.8205, + -0.2384 + ], + [ + 0.8205, + 0.2384 + ], + [ + 1.0, + 1.0 + ] + ] +} diff --git a/rust/satlim-plugin/presets/Master_Clean.json b/rust/satlim-plugin/presets/Master_Clean.json new file mode 100644 index 0000000..3bb99e1 --- /dev/null +++ b/rust/satlim-plugin/presets/Master_Clean.json @@ -0,0 +1,12 @@ +{ + "format": "satlim-preset", + "version": 1, + "name": "Master_Clean", + "params": { + "ceiling": -1.0, + "threshold": -4.0, + "release": 80.0, + "lookahead": 1.0, + "os": 2.0 + } +} diff --git a/rust/satlim-plugin/presets/Master_Loud.json b/rust/satlim-plugin/presets/Master_Loud.json new file mode 100644 index 0000000..a296bcc --- /dev/null +++ b/rust/satlim-plugin/presets/Master_Loud.json @@ -0,0 +1,13 @@ +{ + "format": "satlim-preset", + "version": 1, + "name": "Master_Loud", + "params": { + "ceiling": -0.5, + "threshold": -8.0, + "release": 40.0, + "clip": 60.0, + "lookahead": 1.0, + "os": 3.0 + } +} diff --git a/rust/satlim-plugin/presets/Peak_Limiter.json b/rust/satlim-plugin/presets/Peak_Limiter.json new file mode 100644 index 0000000..054299b --- /dev/null +++ b/rust/satlim-plugin/presets/Peak_Limiter.json @@ -0,0 +1,22 @@ +{ + "format": "satlim-preset", + "version": 1, + "name": "Peak Limiter", + "params": { + "bias": 0.0, + "ceiling": -0.3, + "clip": 0.0, + "drive": 0.0, + "lookahead": 1.0, + "os": 2.0, + "out_gain": 0.0, + "release": 25.0, + "sat_gain": 0.0, + "sat_hp": 20.0, + "sat_lp": 9680.0, + "sat_mix": 0.0, + "shape": 1.0, + "threshold": -6.0, + "tone": 20000.0 + } +} diff --git a/rust/satlim-plugin/presets/README.md b/rust/satlim-plugin/presets/README.md new file mode 100644 index 0000000..b9a93c7 --- /dev/null +++ b/rust/satlim-plugin/presets/README.md @@ -0,0 +1,8 @@ +# Factory presets + +Every `*.json` file in this folder is embedded into the plug-in at build time and listed under FACTORY +in the preset dropdown (sorted by file name; `INIT` is always first and built in). + +Format: `{ "format": "satlim-preset", "version": 1, "name": "...", "params": { "": , ... } }`. +Parameter ids are the ones in `src/params.rs` (generated by `tools/gen_lparams.py`). Missing ids fall back to the default. +Bypass is never stored. `lookahead` is 1 (on) / 0 (off, zero latency). diff --git a/rust/satlim-plugin/src/gui/mod.rs b/rust/satlim-plugin/src/gui/mod.rs new file mode 100644 index 0000000..d0aef59 --- /dev/null +++ b/rust/satlim-plugin/src/gui/mod.rs @@ -0,0 +1,68 @@ +//! SatLim editor: egui on the shared satcomp-ui canvas / widget kit, same logical-grid approach as SatComp. + +mod ui; +#[cfg(test)] +mod smoke; + +use crate::params::SatLimParams; +use crate::Shared; +use nih_plug::prelude::Editor; +use nih_plug_egui::create_egui_editor; +use nih_plug_egui::egui::{self, LayerId}; +use satcomp_ui::canvas::{Canvas, FONT_NAMES}; +use satcomp_ui::init_ctx; +use std::sync::Arc; +use std::time::Duration; +use ui::{Env, Gui, State}; + +/// Logical grid (units); the window scales it in quarter steps. +pub const W: f32 = 340.0; +pub const H: f32 = 504.0; + +/// One editor frame: map the egui input into logical canvas units, draw the whole UI. +pub(crate) fn run_frame(ctx: &egui::Context, setter: &nih_plug::prelude::ParamSetter, st: &mut State, params: &SatLimParams, shared: &Shared) { + let screen = ctx.screen_rect(); + let s = ((screen.width() / W).min(screen.height() / H) * 4.0).floor() / 4.0; + let s = s.max(0.5); + let ox = ((screen.width() - W * s) * 0.5).floor(); + let oy = ((screen.height() - H * s) * 0.5).floor(); + let ppp = ctx.pixels_per_point(); + let (pos, down, rdown, scroll, shift, now) = ctx.input(|i| { + (i.pointer.latest_pos(), i.pointer.primary_down(), i.pointer.secondary_down(), i.raw_scroll_delta.y, i.modifiers.shift, i.time) + }); + let (mx, my) = match pos { + Some(p) => ((p.x - ox) / s, (p.y - oy) / s), + None => (-1000.0, -1000.0), + }; + st.set_input(mx, my, down, rdown, scroll, shift, now); + st.ptr_pt = pos.map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0)); + st.win_pt = (screen.width(), screen.height()); + + let painter = ctx.layer_painter(LayerId::background()); + let cv = Canvas::new(&painter, ppp, ox, oy, s, st.colors(), st.face); + painter.rect_filled(screen, 0.0, cv.bg_color()); + // Theme editor: the whole window is a static page (default params, constant meter values); the real params and shared + // state are not touched. + let (dp, ds) = (st.dummy_params.clone(), st.dummy_shared.clone()); + let editing = st.app.editing(); + if editing { + st.fill_dummy(); + } + let (pr, sr): (&SatLimParams, &Shared) = if editing { (&*dp, &*ds) } else { (params, shared) }; + let env = Env { params: pr, setter, shared: sr, dsp: pr.to_dsp() }; + let mut g = Gui { s: st, cv, env }; + g.frame(); + ctx.request_repaint_after(Duration::from_millis(16)); +} + +pub fn create(params: Arc, shared: Arc) -> Option> { + let (pal, light) = ui::initial_palette(¶ms); + let face = params.font.load(std::sync::atomic::Ordering::Relaxed).clamp(0, FONT_NAMES.len() as i32 - 1) as usize; + let state = State::new(pal, light, face, ¶ms); + let editor_state = params.editor_state.clone(); + let look_params = params.clone(); + create_egui_editor(editor_state, state, move |ctx, st| { + init_ctx(ctx); + st.sync_look(&look_params); + }, move |ctx, setter, st| run_frame(ctx, setter, st, ¶ms, &shared)) +} diff --git a/rust/satlim-plugin/src/gui/smoke.rs b/rust/satlim-plugin/src/gui/smoke.rs new file mode 100644 index 0000000..8527b9b --- /dev/null +++ b/rust/satlim-plugin/src/gui/smoke.rs @@ -0,0 +1,453 @@ +//! Headless smoke test of the editor: drives the page with a scripted mouse against a recording fake host and checks that +//! it neither panics nor behaves non-deterministically, and that the expected parameter writes happen. +//! (nih-plug keeps its parameter setters crate-private, so values are not echoed back; the host write log is what is checked.) + +use super::ui::State; +use crate::params::SatLimParams; +use crate::Shared; +use nih_plug::prelude::*; +use nih_plug_egui::egui::{self, Event, Modifiers, PointerButton, Pos2, RawInput, Rect, Vec2}; +use std::sync::Arc; + +#[derive(Default)] +struct FakeHost { + log: parking_lot::Mutex>, +} + +impl GuiContext for FakeHost { + fn plugin_api(&self) -> PluginApi { + PluginApi::Vst3 + } + fn request_resize(&self) -> bool { + true + } + unsafe fn raw_begin_set_parameter(&self, _p: ParamPtr) {} + unsafe fn raw_set_parameter_normalized(&self, p: ParamPtr, n: f32) { + self.log.lock().push(format!("{} {:.3}", p.name(), n)); + } + unsafe fn raw_end_set_parameter(&self, _p: ParamPtr) {} + fn get_state(&self) -> nih_plug::wrapper::state::PluginState { + nih_plug::wrapper::state::PluginState { version: String::new(), params: Default::default(), fields: Default::default() } + } + fn set_state(&self, _s: nih_plug::wrapper::state::PluginState) {} +} + +struct Rig { + ctx: egui::Context, + host: Arc, + params: Arc, + shared: Arc, + st: State, + t: f64, + hash: u64, + /// hash of the last frame alone, and whether the fake audio thread keeps pushing scope buckets + last: u64, + feed: bool, +} + +impl Rig { + fn new() -> Self { + Self::with_params(|_| {}) + } + + /// A rig whose parameters start from `tweak` (nih-plug's setters are sealed, so state is set before the params are shared). + fn with_params(tweak: impl FnOnce(&mut SatLimParams)) -> Self { + let ctx = egui::Context::default(); + satcomp_ui::init_ctx(&ctx); + let mut p = SatLimParams::from_defaults(None); // hermetic: ignore this machine's defaults file + tweak(&mut p); + let params = Arc::new(p); + Self { ctx, host: Arc::new(FakeHost::default()), shared: Arc::new(Shared::new()), st: State::new(0, false, 0, ¶ms), params, t: 1.0, hash: 0xcbf29ce484222325, last: 0, feed: true } + } + + fn frame(&mut self, events: Vec) { + self.t += 0.03; + // some audio-side telemetry so meters and the scope draw + let n = if self.feed { (self.t * 10.0) as f32 } else { 3.0 }; // frozen telemetry once the fake audio stops + let ord = std::sync::atomic::Ordering::Relaxed; + self.shared.opk[0].store(0.5 + 0.3 * n.sin(), ord); + self.shared.opk[1].store(0.4 + 0.3 * n.cos(), ord); + self.shared.tpk.store(0.6 + 0.3 * n.sin(), ord); + self.shared.gr_pk.store(2.0 + n.cos().abs() * 3.0, ord); + self.shared.clip_gr_pk.store(1.0 + n.sin().abs() * 2.0, ord); + self.shared.sat_pk.store(0.5, ord); + self.shared.sat_vz.store(0.4, ord); + self.shared.fms.store(0.05, ord); + if self.feed { + // buckets arrive in host-block sized chunks of 5-9, each a pure function of its absolute index + let chunk = 5 + (n as usize % 5); + for _ in 0..chunk { + let i = self.shared.scope.head() as f32; + let v = 0.3 + 0.2 * (i * 0.1).sin() + 0.1 * (i * 0.37).sin(); + self.shared.scope.push3(v, v * 1.25, v * 1.5); + } + } + let raw = RawInput { time: Some(self.t), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(510.0, 756.0))), events, ..Default::default() }; + let setter = ParamSetter::new(&*self.host); + let (p, sh) = (self.params.clone(), self.shared.clone()); + let st = &mut self.st; + let full = self.ctx.run(raw, |ctx| super::run_frame(ctx, &setter, st, &p, &sh)); + let mut fh: u64 = 0xcbf29ce484222325; + for b in format!("{:?}", full.shapes).bytes() { + self.hash ^= b as u64; + self.hash = self.hash.wrapping_mul(0x100000001b3); + fh ^= b as u64; + fh = fh.wrapping_mul(0x100000001b3); + } + self.last = fh; + } + + /// logical (1.5 px per unit) position + fn at(x: f32, y: f32) -> Pos2 { + Pos2::new(x * 1.5, y * 1.5) + } + + fn click(&mut self, x: f32, y: f32) { + let p = Self::at(x, y); + self.frame(vec![Event::PointerMoved(p)]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]); + self.frame(vec![]); + } + + /// the host closed and reopened the editor: egui's clock restarts from zero while the UI state lives on + fn reopen_editor(&mut self) { + self.t = 0.0; + // a reopened editor is a new egui context (its history panics if the clock runs backwards) + self.ctx = egui::Context::default(); + satcomp_ui::init_ctx(&self.ctx); + } + + fn rclick(&mut self, x: f32, y: f32) { + let p = Self::at(x, y); + self.frame(vec![Event::PointerMoved(p)]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]); + self.frame(vec![]); + } + + fn drag(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) { + let p0 = Self::at(x0, y0); + self.frame(vec![Event::PointerMoved(p0)]); + self.frame(vec![Event::PointerButton { pos: p0, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + for i in 1..=5 { + let f = i as f32 / 5.0; + self.frame(vec![Event::PointerMoved(Self::at(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f))]); + } + let p1 = Self::at(x1, y1); + self.frame(vec![Event::PointerButton { pos: p1, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]); + self.frame(vec![]); + } + + fn log(&self) -> Vec { + self.host.log.lock().clone() + } +} + +fn script() -> (u64, Vec) { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(317.0, 196.0); // oversampling x8 + r.drag(41.0, 388.0, 41.0, 358.0); // DRIVE + r.click(281.0, 270.0); // L.AHEAD off + r.drag(281.0, 303.0, 281.0, 288.0); // CEILING + r.drag(281.0, 335.0, 281.0, 355.0); // THRESHOLD (default is the top of its range: drag down) + r.drag(281.0, 390.0, 281.0, 375.0); // CLIP + r.drag(281.0, 472.0, 281.0, 458.0); // OUT GAIN + r.click(247.0, 14.0); // DELTA + r.click(247.0, 14.0); + r.click(300.0, 14.0); // BYPASS on + r.click(300.0, 14.0); // and off + r.click(80.0, 197.0); // shaper selector menu + r.click(80.0, 197.0); + r.click(110.0, 171.0); // scope row: SRC + r.drag(150.0, 80.0, 190.0, 100.0); // scope: window / ceiling drag + r.click(197.0, 38.0); // preset dropdown + r.click(197.0, 38.0); + r.click(60.0, 12.0); // About page on + for _ in 0..3 { + r.frame(vec![]); + } + r.click(60.0, 12.0); // and off + r.rclick(332.0, 496.0); // grip: size menu + r.rclick(332.0, 496.0); + r.reopen_editor(); + r.frame(vec![]); + (r.hash, r.log()) +} + +#[test] +fn the_editor_runs_scripted_input_and_is_deterministic() { + let (h1, _) = script(); + let (h2, log) = script(); + assert_eq!(h1, h2, "frames differ between two identical runs"); + for want in ["Oversampling", "Drive", "Lookahead", "Ceiling", "Threshold", "Clip", "Out Gain", "Bypass"] { + assert!(log.iter().any(|l| l.starts_with(want)), "no write to {want}: {log:?}"); + } +} + +#[test] +fn the_oversampling_buttons_write_x8() { + let mut r = Rig::new(); + for _ in 0..3 { + r.frame(vec![]); + } + r.click(317.0, 196.0); + let log = r.log(); + // x8 = 3 of 0..3 -> normalised 1.0 + assert!(log.iter().any(|l| l.starts_with("Oversampling") && l.ends_with("1.000")), "{log:?}"); +} + +#[test] +fn the_look_ahead_button_switches_it_off() { + let mut r = Rig::new(); + for _ in 0..3 { + r.frame(vec![]); + } + r.click(281.0, 270.0); + assert!(r.log().iter().any(|l| l.starts_with("Lookahead") && l.ends_with("0.000")), "{:?}", r.log()); +} + +#[test] +fn the_about_page_stays_quiet_and_writes_nothing() { + // the editing flag is set through the About > Appearance flow; here just make sure many frames with the About page + // open (which hosts it) neither panic nor change parameters + let mut r = Rig::new(); + r.click(60.0, 12.0); + for _ in 0..30 { + r.frame(vec![]); + } + assert!(r.log().is_empty(), "{:?}", r.log()); +} + +#[test] +fn clicking_the_sat_readout_requests_the_level_match_and_its_result_writes_sat_gain() { + let mut r = Rig::new(); + for _ in 0..3 { + r.frame(vec![]); + } + r.click(100.0, 358.0); // the SAT readout in the plot's bottom right corner + assert!(r.shared.sat_req.swap(false, std::sync::atomic::Ordering::Relaxed), "no match request"); + r.shared.sat_result.store(-3.5, std::sync::atomic::Ordering::Relaxed); + r.shared.sat_result_new.store(true, std::sync::atomic::Ordering::Release); + r.frame(vec![]); + assert!(r.log().iter().any(|l| l.starts_with("Sat Gain")), "{:?}", r.log()); +} + +#[test] +fn clicking_the_output_bars_cycles_the_range_without_writing_parameters() { + let mut r = Rig::new(); + for _ in 0..3 { + r.frame(vec![]); + } + for _ in 0..5 { + r.click(205.0, 300.0); + } + assert!(r.log().is_empty(), "{:?}", r.log()); +} + +#[test] +fn the_scope_outline_mode_draws_and_differs_from_solid() { + let run = |solid: bool| { + let mut r = Rig::with_params(|p| p.fft_solid = Arc::new(std::sync::atomic::AtomicBool::new(solid))); + for _ in 0..6 { + r.frame(vec![]); + } + r.hash + }; + assert_ne!(run(true), run(false), "outline and solid should draw differently"); + assert_eq!(run(false), run(false)); +} + +#[test] +fn the_appearance_page_has_the_scope_fill_switch_on_its_own_row() { + let mut r = Rig::new(); + r.click(60.0, 12.0); // About + r.click(182.0, 38.0); // APPEARANCE tab + for _ in 0..3 { + r.frame(vec![]); + } + assert!(r.params.fft_solid.load(std::sync::atomic::Ordering::Relaxed), "solid by default"); + r.click(146.0, 86.0); // OUTLINE (second row under COLOR MODE) + assert!(!r.params.fft_solid.load(std::sync::atomic::Ordering::Relaxed), "OUTLINE should switch the fill off"); + r.click(210.0, 86.0); // SOLID + assert!(r.params.fft_solid.load(std::sync::atomic::Ordering::Relaxed)); + assert!(r.log().is_empty(), "UI-only setting, no host writes: {:?}", r.log()); +} + +#[test] +fn the_scope_holds_perfectly_still_when_the_audio_stops() { + let mut r = Rig::new(); + for _ in 0..80 { + r.frame(vec![]); + } + r.feed = false; + for _ in 0..300 { + r.frame(vec![]); // the eased read position settles on the head + } + r.frame(vec![]); + let a = r.last; + for _ in 0..5 { + r.frame(vec![]); + assert_eq!(r.last, a, "the picture moved with no new audio"); + } +} + +#[test] +fn the_scope_advances_while_audio_runs_without_redrawing_old_columns() { + // two rigs fed the same buckets, one frame apart in time: after the second has had longer to settle, both pictures are + // made of the same stable columns shifted along, so an unchanged tail of the picture exists. Cheap proxy: the number of + // distinct frame hashes over a run stays at most one per frame (never a flicker pair within one frame), and the picture + // changes on most frames while running. + let mut r = Rig::new(); + for _ in 0..40 { + r.frame(vec![]); + } + let mut seen = std::collections::HashSet::new(); + for _ in 0..60 { + r.frame(vec![]); + seen.insert(r.last); + } + assert!(seen.len() >= 40, "the picture should advance on most frames: {} distinct of 60", seen.len()); +} + +#[test] +fn preferences_defaults_are_per_plugin_with_a_global_one_behind_a_chevron() { + use satcomp_ui::appearance::{clear_defaults, clear_defaults_for, load_defaults, load_defaults_for}; + use std::sync::atomic::Ordering::Relaxed; + let dir = std::env::temp_dir().join(format!("satcomp-defaults-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + std::env::set_var("SATCOMP_DATA_DIR", &dir); + clear_defaults(); + clear_defaults_for("satlim"); + let mut r = Rig::new(); + r.click(60.0, 12.0); // About + r.click(182.0, 38.0); // PREFERENCES tab + for _ in 0..3 { + r.frame(vec![]); + } + // SET AS DEFAULT (the main part of the button) saves for THIS plug-in only + r.click(208.0, 64.0); // LIGHT + r.click(90.0, 435.0); // SET AS DEFAULT + let own = load_defaults_for("satlim").expect("the plug-in's own default"); + assert!(own.light, "the current look is what gets saved"); + assert_eq!((own.pal, own.face), (0, 0)); + assert!((own.scale - 1.0).abs() < 1e-6, "SatLim opens at 100%"); + assert!(load_defaults().is_none(), "the main button does not touch the global default"); + // the chevron opens a one-item menu: SET AS GLOBAL DEFAULT + r.click(140.0, 64.0); // DARK again + r.click(158.0, 435.0); // chevron + assert!(r.st.app.def_menu == 1, "the chevron opens the menu"); + r.click(80.0, 449.0); // SET AS GLOBAL DEFAULT + assert!(r.st.app.def_menu == 0, "picking closes the menu"); + let global = load_defaults().expect("the global default"); + assert!(!global.light); + assert!(load_defaults_for("satlim").unwrap().light, "the plug-in's own default wins over the global one"); + // a new instance picks up its own default, a project restore would then overwrite it + assert!(SatLimParams::from_defaults(load_defaults_for("satlim")).light.load(Relaxed)); + // RESET (main part): drops the plug-in's own default, this instance takes what a new one would get now (the global look) + r.click(208.0, 64.0); // LIGHT + assert!(r.params.light.load(Relaxed)); + r.click(240.0, 435.0); + assert!(!r.params.light.load(Relaxed), "back on the global look"); + assert!(!load_defaults_for("satlim").unwrap().light && load_defaults().is_some()); + // RESET GLOBAL DEFAULT (its chevron): nothing left, the factory look + r.click(314.0, 435.0); + r.click(240.0, 449.0); + assert!(load_defaults().is_none() && load_defaults_for("satlim").is_none(), "everything cleared"); + // a click outside an open menu only closes it + r.click(158.0, 435.0); + r.click(30.0, 300.0); + assert!(r.st.app.def_menu == 0 && load_defaults().is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_font_dropdown_opens_over_the_page_and_picks_a_face() { + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(); + r.click(60.0, 12.0); // About + r.click(182.0, 38.0); // PREFERENCES tab + for _ in 0..3 { + r.frame(vec![]); + } + let pal = r.params.palette_v2.load(Relaxed); + r.click(150.0, 413.0); // the FONT dropdown + assert!(r.st.app.font_open, "the list should be open"); + r.click(150.0, 350.0); // 8th entry, Victor Mono (the list is 11 rows now), drawn over the scheme list + assert_eq!(r.params.font.load(Relaxed), 7, "Victor Mono"); + assert!(!r.st.app.font_open, "picking closes the list"); + assert_eq!(r.params.palette_v2.load(Relaxed), pal, "the click must not reach the scheme list under the open list"); + r.click(150.0, 413.0); + r.click(20.0, 300.0); // a click elsewhere closes it without changing anything + assert!(!r.st.app.font_open); + assert_eq!(r.params.font.load(Relaxed), 7); + assert!(r.log().is_empty(), "UI-only, no host writes: {:?}", r.log()); +} + +#[test] +fn the_theme_editor_page_has_a_filled_scope_in_stacking_order() { + let r = Rig::new(); + r.st.fill_dummy(); + let ring = &r.st.dummy_shared.scope; + assert!(ring.head() > 1000, "the mock scope should hold a couple of seconds"); + let h = ring.head(); + let mut peak = 0.0f32; + for i in h - 1000..h { + let (out, handed, pre) = ring.get3(i % satcomp_dsp::ScopeRing::LEN); + assert!(out <= handed + 1e-6 && handed <= pre + 1e-6, "bucket {i}: {out} {handed} {pre}"); + peak = peak.max(pre); + } + assert!(peak > 1.0, "hits should reach over the ceiling so the removal shows"); + let before = ring.head(); + r.st.fill_dummy(); + assert_eq!(ring.head(), before, "filled once, then still"); +} + +#[test] +fn the_dice_rolls_a_different_scheme_each_time_and_scrolls_the_list_to_it() { + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(); + r.click(60.0, 12.0); // About + r.click(182.0, 38.0); // PREFERENCES tab + for _ in 0..3 { + r.frame(vec![]); + } + let n = r.st.app.n_schemes() as i32; + assert!(n >= 27, "the built-in table has grown to 27: {n}"); + let mut seen = std::collections::BTreeSet::new(); + let mut prev = r.params.palette_v2.load(Relaxed); + for _ in 0..12 { + r.click(110.0, 109.0); // the dice, right of the COLOR SCHEME label + let now = r.params.palette_v2.load(Relaxed); + assert!(now >= 0 && now < n, "scheme {now} of {n}"); + assert_ne!(now, prev, "a roll never lands on the current scheme"); + // the list follows the roll: the new scheme is among the visible rows (14 on this page; the scroll is clamped to the last screen) + let sc = r.st.app.ap_scroll as i32; + assert!(now >= sc && now < sc + 14, "scheme {now} not visible with the list at {sc}"); + seen.insert(now); + prev = now; + } + assert!(seen.len() >= 4, "twelve rolls should land on several different schemes: {seen:?}"); + assert!(r.log().is_empty(), "UI-only, no host writes"); +} + +#[test] +fn the_logo_and_the_title_light_up_under_the_pointer() { + // the picture with the pointer parked on an empty spot, on the logo, on the title: three different frames + let frame_with_pointer_at = |x: f32, y: f32| { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.frame(vec![Event::PointerMoved(Rig::at(x, y))]); + r.frame(vec![]); + r.last + }; + let (idle, logo, title) = (frame_with_pointer_at(200.0, 120.0), frame_with_pointer_at(22.0, 15.0), frame_with_pointer_at(80.0, 15.0)); + assert_ne!(idle, logo, "the logo should invert under the pointer"); + assert_ne!(idle, title, "the title should get a highlight under the pointer"); + assert_ne!(logo, title); +} diff --git a/rust/satlim-plugin/src/gui/ui.rs b/rust/satlim-plugin/src/gui/ui.rs new file mode 100644 index 0000000..4df8f3b --- /dev/null +++ b/rust/satlim-plugin/src/gui/ui.rs @@ -0,0 +1,1820 @@ +//! SatLim editor: the SatComp sat module (plot, draw view, cells) on the shared widget kit, the transient scope, the +//! limiter column and the meters. Immediate mode with the same `act` / `press` drag logic as SatComp. + +use satcomp_ui::canvas::Canvas; +use satcomp_ui::kit::{Kit, Meta, Widgets}; +use satcomp_ui::appearance::{self, AppState, AppearanceUi, CellGrid, Rect}; +use crate::params::{SatLimParams, SLOTS, TABLE}; +use crate::presets::{self, Preset}; +use crate::Shared; +use super::{H, W}; +use nih_plug::prelude::*; +use satcomp_dsp::shapers::{Curve, ShaperLut, CUSTOM, MAX_PTS, MIN_GAP, SHAPER_NAMES}; +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +enum MenuKind { + Shape, + Palette, + Size, + Preset, +} + +/// kind: 0 selectable item, 1 header (dim, not selectable), 2 separator +#[derive(Clone)] +struct MItem { + label: String, + kind: u8, + id: i32, +} + +/// Output VU ranges: (dB span, dB values labelled), cycled by clicking the bars. +const VU_RANGES: [(f32, &[i32]); 4] = [(48.0, &[-6, -12, -24, -36]), (24.0, &[-3, -6, -12, -18]), (12.0, &[-2, -4, -6, -9]), (6.0, &[-1, -2, -3, -4, -5])]; + +/// ASYM slider drag (viewport-style act id: released with the mouse) +const ACT_ASYM: i32 = 145; +const MENU_ROWS: usize = 18; +const MENU_ROW_H: f32 = 14.0; + +/// Window scale steps (percent of the W x H base size). +const SIZES: [f32; 6] = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5]; + +struct Menu { + kind: MenuKind, + x: f32, + y: f32, + items: Vec, + checked: i32, + scroll: usize, +} + +/// Outcome of a file dialog on its worker thread. +pub enum Dlg { + Pending, + Cancelled, + Loaded(Preset), + Saved(String), +} + +mod scope; + +pub struct State { + /// widget interaction state (satcomp-ui); `State` derefs to it + pub kit: Kit, + /// packed scope settings (see scope.rs) + scope_cfg: i32, + /// scope viewport drag start: (mouse x, mouse y, window step, ceiling step) + scope_drag: (f32, f32, usize, usize), + /// eased read position in the scope ring (buckets) and the time of the last scope frame + scope_pos: f64, + scope_t: f64, + /// ASYM drag anchor: (mouse y, value 0..1) at the press + asym_drag: (f32, f32), + /// colour themes, theme editor and About-page state (satcomp-ui) + pub app: AppState, + pub dummy_params: Arc, + pub dummy_shared: Arc, + pub pal: usize, + pub light: bool, + /// UI font index (FONT_NAMES) + pub face: usize, + /// time of a logo click waiting out the double-click window (then it cycles the colour scheme) + logo_pend: f64, + // interaction + vt1: usize, + vt2: usize, + menu: Option, + // per-frame input (logical units) + // meters + gr_disp: f32, + /// the clipper's reduction (dB): decaying display value, and its readout copy + clip_disp: f32, + rd_clip: f32, + gr_hold: f32, + gr_hold_t: f64, + gr_ri: usize, + ovl: f32, + ovr: f32, + hl_l: f32, + hl_r: f32, + hl_l_t: f64, + hl_r_t: f64, + opk_max: f32, + clip_lat: bool, + clip_t: f64, + /// output VU range index (VU_RANGES) + vu_ri: usize, + /// post-saturator level meter: decaying level and the last time it clipped (accent, held 1 s) + sat_lv: f32, + sat_clip_t: f64, + /// limiter gain reduction (dB): decaying display value + // readouts (refresh ~8x/s) + rd_last: f64, + rd_tick: bool, + rd_gr: f32, + rd_pk: f32, + rd_rms: f32, + rd_sat: f32, + // sat plot + lut: ShaperLut, + /// custom-curve draw mode (pencil) and the point being dragged + curve_edit: bool, + /// draw view tool: true = symmetry (odd curve), false = free draw + sym_mode: bool, + /// shape was observed as Custom since the draw view opened (host writes land a frame or more later) + edit_seen: bool, + cpt: usize, + // window resize grip + resizing: bool, + resize_off: (f32, f32), + pub ptr_pt: (f32, f32), + /// egui screen size in points (what the host window has actually become so far) + pub win_pt: (f32, f32), + // presets + factory: Vec, + user: Vec<(String, std::path::PathBuf)>, + /// 1 = load dialog, 2 = save dialog (run after the frame is drawn, they block) + pending: u8, + /// result slot of a file dialog running on a worker thread (never block the UI/host thread in a modal) + dlg: Option>>, + /// preset the edit marker compares against (cached by name), and the post-load settle time + base: Option<(String, Preset)>, + hold_until: f64, +} + +impl State { + /// Per-frame input snapshot (positions in logical canvas units). Computes press edges like the JSFX. + pub fn set_input(&mut self, mx: f32, my: f32, down: bool, rdown: bool, scroll: f32, shift: bool, now: f64) { + // The egui clock restarts from 0 whenever the editor window is reopened, but this State lives on. Re-base every + // stored timestamp, otherwise `now - last` stays negative and the ~8 Hz readouts (PK, RMS, GR) stay frozen. + if self.kit.set_input(mx, my, down, rdown, scroll, shift, now) { + self.rd_last = now; + self.hl_l_t = now; + self.hl_r_t = now; + self.gr_hold_t = now; + self.sat_clip_t = -10.0; + self.hold_until = now; + self.scope_t = now; + } + } + + pub fn new(pal: usize, light: bool, face: usize, params: &SatLimParams) -> Self { + let mut kit = Kit::new(SLOTS); + let meta = &mut kit.meta; + for &(n, _, mn, mx, df) in TABLE { + meta[n] = Meta { min: mn, max: mx, def: df, mode: 0, snap: 0, step: 1.0 }; + } + let mut sp = |n: usize, mode: u8, snap: u8, step: f32| { + meta[n].mode = mode; + meta[n].snap = snap; + meta[n].step = step; + }; + sp(2, 0, 0, 0.5); + sp(3, 0, 0, 1.0); + sp(4, 1, 1, 1.0); + sp(5, 1, 2, 10.0); + sp(6, 1, 2, 10.0); + sp(8, 0, 0, 0.1); + sp(9, 0, 0, 0.1); + sp(10, 0, 0, 1.0); + sp(11, 0, 0, 1.0); + sp(22, 0, 0, 0.1); + sp(25, 0, 0, 1.0); + sp(27, 0, 0, 0.1); + let mut st = Self { + kit, + pal, + light, + face, + scope_cfg: params.scope.load(Ordering::Relaxed), + scope_drag: (0.0, 0.0, 0, 0), + scope_pos: 0.0, + scope_t: 0.0, + asym_drag: (0.0, 0.0), + app: AppState::new(), + dummy_params: Arc::new(SatLimParams::from_defaults(None)), + dummy_shared: Arc::new(Shared::new()), + logo_pend: -1.0, + vt1: 0, + vt2: 0, + menu: None, + gr_disp: 0.0, + clip_disp: 0.0, + rd_clip: 0.0, + gr_hold: 0.0, + gr_hold_t: 0.0, + gr_ri: 0, + ovl: 0.0, + ovr: 0.0, + hl_l: 0.0, + hl_r: 0.0, + hl_l_t: 0.0, + hl_r_t: 0.0, + opk_max: 0.0, + clip_lat: false, + clip_t: -10.0, + vu_ri: 0, + sat_lv: 0.0, + sat_clip_t: -10.0, + rd_last: 0.0, + rd_tick: false, + rd_gr: 0.0, + rd_pk: 0.0, + rd_rms: 0.0, + rd_sat: 0.0, + lut: ShaperLut::new(0), + curve_edit: false, + sym_mode: true, + edit_seen: false, + cpt: 0, + resizing: false, + resize_off: (0.0, 0.0), + ptr_pt: (0.0, 0.0), + win_pt: (W, H), + factory: presets::factory(), + user: presets::scan_user(), + pending: 0, + dlg: None, + base: None, + hold_until: 0.0, + }; + st.restore_custom(params); + st + } +} + +impl State { + /// Colours the canvas draws with: the editor preview while editing, else the active scheme. + pub fn colors(&self) -> [f32; 9] { + self.app.colors(self.pal, self.light) + } + + /// nih-plug builds the editor (and so this state) when the plug-in is created, BEFORE the host restores the project's + /// saved parameters. Re-read the saved look every time the window opens, otherwise a project reopens on the defaults. + pub fn sync_look(&mut self, params: &SatLimParams) { + let (pal, light) = initial_palette(params); + self.pal = pal; + self.light = light; + self.face = (params.font.load(Ordering::Relaxed).max(0) as usize).min(satcomp_ui::canvas::FONT_NAMES.len() - 1); + self.scope_cfg = params.scope.load(Ordering::Relaxed); + self.restore_custom(params); + } + + /// A project that used a user theme: resolve it from the themes file or the project copy. + pub fn restore_custom(&mut self, params: &SatLimParams) { + let pal = self.app.restore_custom(self.pal, ¶ms.custom_theme.lock()); + if pal != self.pal || pal >= satcomp_ui::canvas::PALETTES.len() { + self.pal = pal; + params.palette_v2.store(pal as i32, Ordering::Relaxed); + } + } + + /// Constant meter / readout values for the dummy page (set every frame, the draw code then settles on them). + pub fn fill_dummy(&self) { + let d = &self.dummy_shared; + d.gr_pk.store(3.5, Ordering::Relaxed); + d.opk[0].store(1.0, Ordering::Relaxed); + d.opk[1].store(0.5, Ordering::Relaxed); + d.clip.store(true, Ordering::Relaxed); + d.fms.store(0.05, Ordering::Relaxed); + d.sat_db.store(2.0, Ordering::Relaxed); + d.sat_vz.store(0.3, Ordering::Relaxed); + d.sat_pk.store(0.4, Ordering::Relaxed); + d.tpk.store(0.9, Ordering::Relaxed); + d.clip_gr_pk.store(1.0, Ordering::Relaxed); + // an active-looking scope: drum hits every half second (alternating strong / softer) with some of each hit taken off + // by the clipper and the limiter. Filled once; the ring then never moves, so the picture stands still. + if d.scope.head() == 0 { + for i in 0..1600u32 { + let phase = (i % 250) as f32; + let amp = if (i / 250) % 2 == 0 { 1.0 } else { 0.7 }; + let pre = 0.08 + 1.2 * amp * (-phase / 30.0).exp() + 0.04 * ((i as f32) * 0.9).sin().abs(); + let handed = pre.min(1.1); + let out = handed.min(0.85); + d.scope.push3(out, handed, pre); + } + } + } +} + +impl Deref for State { + type Target = Kit; + fn deref(&self) -> &Kit { + &self.kit + } +} +impl DerefMut for State { + fn deref_mut(&mut self) -> &mut Kit { + &mut self.kit + } +} + +pub struct Env<'a> { + pub params: &'a SatLimParams, + pub setter: &'a ParamSetter<'a>, + pub shared: &'a Shared, + pub dsp: satlim_dsp::LimParams, +} + +pub struct Gui<'a> { + pub s: &'a mut State, + pub cv: Canvas<'a>, + pub env: Env<'a>, +} + +impl<'a> Widgets<'a> for Gui<'a> { + fn kit(&mut self) -> &mut Kit { + &mut self.s.kit + } + fn kit_ref(&self) -> &Kit { + &self.s.kit + } + fn cv(&mut self) -> &mut Canvas<'a> { + &mut self.cv + } + fn param_ptr(&self, n: usize) -> Option { + self.env.params.ptr(n) + } + fn host(&self) -> &dyn GuiContext { + self.env.setter.raw_context + } + fn masked(&self) -> bool { + self.s.app.edit.is_some() + } + fn fmt(&self, n: usize, v: f32) -> String { + self.fmt_slot(n, v) + } +} + +impl<'a> AppearanceUi<'a> for Gui<'a> { + fn app(&mut self) -> &mut AppState { + &mut self.s.app + } + fn app_ref(&self) -> &AppState { + &self.s.app + } + fn pal(&self) -> usize { + self.s.pal + } + fn light(&self) -> bool { + self.s.light + } + fn face(&self) -> usize { + self.s.face + } + fn commit_scheme(&mut self, pal: usize, encoded: String) { + self.s.pal = pal; + self.env.params.palette_v2.store(pal as i32, Ordering::Relaxed); + // a user theme is also stored in the project, so it survives a machine without the themes file + *self.env.params.custom_theme.lock() = encoded; + self.apply_pal(); + } + fn commit_light(&mut self, light: bool) { + self.s.light = light; + self.env.params.light.store(light, Ordering::Relaxed); + self.apply_pal(); + } + fn plugin_key(&self) -> &'static str { + "satlim" + } + fn presets_dir(&self) -> Option { + crate::presets::user_dir() + } + fn scale_now(&self) -> f32 { + self.cur_scale() + } + fn set_scale(&mut self, scale: f32) { + self.request_scale(scale); + } + fn factory_scale(&self) -> f32 { + 1.0 + } + fn factory_fill_solid(&self) -> bool { + true + } + fn commit_face(&mut self, face: usize) { + self.s.face = face; + self.env.params.font.store(face as i32, Ordering::Relaxed); + self.cv.face = face; + } + fn fft_solid(&self) -> Option { + Some(self.env.params.fft_solid.load(Ordering::Relaxed)) + } + fn commit_fft_solid(&mut self, solid: bool) { + self.env.params.fft_solid.store(solid, Ordering::Relaxed); + } + fn fill_label(&self) -> &'static str { + "SCOPE FILL" + } + fn about_paras(&self) -> &'static [&'static [&'static str]] { + ABOUT_TEXT + } + fn changelog(&self) -> &'static [(&'static str, &'static [&'static str])] { + CHANGELOG + } + fn manual_pdf(&self) -> Option<(&'static str, &'static [u8])> { + // the file must exist for the crate's current version (docs/manual/build.py), or the plug-in does not compile + Some(( + concat!("SatLim-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf"), + include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/manual/SatLim-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf")), + )) + } + fn draw_flow(&mut self, r: Rect, byp: bool) { + self.draw_flow_at(r.x, r.y, r.w, r.h, byp); + } + fn about_scroll_drag_start(&mut self) { + self.vt1 = 0; + self.vt2 = 0; + } +} + +impl<'a> Deref for Gui<'a> { + type Target = State; + fn deref(&self) -> &State { + self.s + } +} +impl<'a> DerefMut for Gui<'a> { + fn deref_mut(&mut self) -> &mut State { + self.s + } +} + +/// About page copy (docs/abouttextcopy.md). Each inner slice is one paragraph, each string one source line. +const ABOUT_TEXT: &[&[&str]] = &[ + &["A 2-stage clipper/limiter with waveshaping saturator", "When you need to nuke it from orbit B)"], + &["Use tube with low drive for warm saturation, opt for destruction with tri-fold, or annihilate with a custom asymmetric waveshape.", "[Click] the top-right pencil icon to enter custom draw mode.", "[Click] the lower-right SAT value to auto-match the gain."], + &["Turn on lookahead for brickwall, true peak limiting. Lowering the threshold chews the input signal deeper. Clip exposes and bricks more transients in the mix."], + &["Balance threshold (limiter) and clip (clipper) to dial in the desired loudness and character."], + &["A shorter release gives a denser, punchier result while introducing distortion artifacts, a longer release is smoother with lower distortion."], + &["Transient/GR meter: solid = limiter gain reduction, striped = clipper gain reduction."], + &["[Double-click] slider resets the parameter to its default value", "[Click] GR meter cycles its range", "[Click] clip meter resets the readout", "[Left/Right-click] top-left icon cycles the colour theme", "[Double-click] top-left icon switches between dark and light mode"], +]; + +/// Changelog, newest first. Keep each entry to two short sentences or fewer. +const CHANGELOG: &[(&str, &[&str])] = &[ + ("v0.1", &["First version: the SatComp saturator, an oversampled clipper (CLIP, x1 to x8) and a true-peak brickwall limiter with a transient scope.", "L.AHEAD off gives a zero-latency limiter. OUT GAIN sits after the limiter on purpose.", "The limiter and the TRU.PK readout detect true peaks at 8x, with L.AHEAD on or off, so inter-sample peaks of a clipped or folded signal are caught. Bypass is a plain bypass."]), +]; + +/// Crate version for the header: "0.4" for 0.4.0, "0.4.1" for a patch release. +/// Palette index and light flag to start with (`palette-v2`; -1 = not set yet = the first scheme, dark). +pub fn initial_palette(p: &crate::params::SatLimParams) -> (usize, bool) { + let v2 = p.palette_v2.load(Ordering::Relaxed); + if v2 >= 0 { + return (v2 as usize, p.light.load(Ordering::Relaxed)); // >= 20 = a user theme, resolved in State::restore_custom + } + (0, false) +} + +fn version_short() -> String { + if cfg!(test) { + return "TEST".into(); // keeps the UI golden independent of release version bumps + } + let v = env!("CARGO_PKG_VERSION"); + v.strip_suffix(".0").unwrap_or(v).to_string() +} + + +impl<'a> Gui<'a> { + /// Push the active scheme's colours into the canvas. + fn apply_pal(&mut self) { + let a = self.app.scheme_cols(self.pal, self.light); + self.cv.bk = [a[0], a[1], a[2]]; + self.cv.fg = [a[3], a[4], a[5]]; + self.cv.ac = [a[6], a[7], a[8]]; + } + + // ------------------------------------------------------------------ params (slider-number addressing) + fn refresh_dsp(&mut self) { + self.env.dsp = self.env.params.to_dsp(); + } + + // ------------------------------------------------------------------ formatting + fn fmt_slot(&self, n: usize, v: f32) -> String { + match n { + 2 | 25 | 11 => format!("{:.0}%", v), + 3 => format!("{:+.0}%", v), + 4 => { + if v <= 20.5 { + "OFF".into() + } else { + format!("{:.0}Hz", v) + } + } + 5 | 6 => { + if v >= 19900.0 { + "OFF".into() + } else if n != 6 && v < 1000.0 { + format!("{:.0}Hz", v) + } else { + format!("{:.1}k", v * 0.001) + } + } + 8 | 9 => format!("{:.1}dB", v), + 10 => format!("{:.0}ms", v), + 22 | 27 => format!("{:+.1}dB", v), + _ => format!("{:.1}", v), + } + } + + // ------------------------------------------------------------------ widgets + fn open_menu(&mut self, kind: MenuKind, x: f32, y: f32, items: Vec, checked: usize) { + let items = items.into_iter().enumerate().map(|(i, label)| MItem { label, kind: 0, id: i as i32 }).collect(); + self.menu = Some(Menu { kind, x, y, items, checked: checked as i32, scroll: 0 }); + } + + /// shape selector: [<] NAME [>] + fn selector(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32) { + let aw = 16.0; + let cy = y + h * 0.5; + let hv = self.hit(x, y, w, h); + let mut sel = (self.sget(n) + 0.5).floor() as i32; + if hv && self.wheel != 0 { + self.click_set(n, (sel + if self.wheel > 0 { -1 } else { 1 }).clamp(0, CUSTOM) as f32); + } + if hv && self.press && self.act == 0 { + if self.mx < x + aw { + self.click_set(n, if sel <= 0 { CUSTOM as f32 } else { (sel - 1) as f32 }); + } else if self.mx >= x + w - aw { + self.click_set(n, if sel >= CUSTOM { 0.0 } else { (sel + 1) as f32 }); + } else { + let items = SHAPER_NAMES.iter().map(|s| s.to_string()).collect(); + self.open_menu(MenuKind::Shape, x, y + h, items, sel as usize); + } + self.press = false; + } + sel = (self.sget(n) + 0.5).floor() as i32; + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.fill(x + aw, y, 1.0, h); + self.cv.fill(x + w - aw - 1.0, y, 1.0, h); + self.cv.tri((x + aw * 0.5 + 2.0, cy - 3.0), (x + aw * 0.5 + 2.0, cy + 3.0), (x + aw * 0.5 - 2.0, cy)); + self.cv.tri((x + w - aw * 0.5 - 2.0, cy - 3.0), (x + w - aw * 0.5 - 2.0, cy + 3.0), (x + w - aw * 0.5 + 2.0, cy)); + self.cv.set_font(2); + let name = SHAPER_NAMES[sel.clamp(0, CUSTOM) as usize].to_uppercase(); + self.cv.textc(x + aw, y + ((h - 8.0) * 0.5).floor(), w - 2.0 * aw, &name); + } + + + /// header logo: left click = next colour scheme, right click = scheme dropdown + fn logo(&mut self, x: f32, y: f32) { + let hv = self.hit(x - 3.0, y - 3.0, 27.0, 27.0); + if hv && self.press && self.act == 0 { + // single click = next scheme (after the double-click window), double click = light/dark + if self.logo_pend >= 0.0 && self.now - self.logo_pend < 0.3 { + self.logo_pend = -1.0; + self.set_light(!self.light); + } else { + self.logo_pend = self.now; + } + self.press = false; + } + if self.logo_pend >= 0.0 && self.now - self.logo_pend >= 0.3 { + self.logo_pend = -1.0; + let n = self.app.n_schemes(); + self.set_pal((self.pal + 1) % n); + } + if hv && self.rpress { + self.logo_pend = -1.0; + let mut items = vec![MItem { label: format!("MODE: {}", if self.light { "LIGHT" } else { "DARK" }), kind: 0, id: 1000 }]; + items.push(MItem { label: String::new(), kind: 2, id: -1 }); + items.extend((0..self.app.n_schemes()).map(|i| MItem { label: self.app.scheme_name(i), kind: 0, id: i as i32 })); + self.menu = Some(Menu { kind: MenuKind::Palette, x, y: y + 22.0, items, checked: self.pal as i32, scroll: 0 }); + } + // plug-in icon in a square box: fill = BG, stroke = UI (so light mode inverts it with the scheme) + self.setc(false); + // hovering inverts the icon (a plate in the UI colour, or back to the outline in light mode): it is clickable + if self.light != hv { + // light mode inverts the icon: UI-coloured plate, BG-coloured glyph + self.cv.fill(x - 3.0, y - 3.0, 27.0, 27.0); + self.cv.setbg(); + } else { + self.cv.boxr(x - 3.0, y - 3.0, 27.0, 27.0); + self.setc(false); + } + self.cv.boxr(x + 6.0, y + 6.0, 9.0, 9.0); + let l = |c: &Canvas, a: f32, b: f32, cc: f32, d: f32| c.line(x + a, y + b, x + cc, y + d); + // four corner brackets round the inner square + for (sx, sy) in [(0.5f32, 0.5f32), (20.5, 0.5), (0.5, 20.5), (20.5, 20.5)] { + let (dx, dy) = (if sx < 10.0 { 1.0 } else { -1.0 }, if sy < 10.0 { 1.0 } else { -1.0 }); + l(&self.cv, sx, sy, sx + 7.0 * dx, sy); + l(&self.cv, sx, sy, sx, sy + 7.0 * dy); + } + } + + + // ------------------------------------------------------------------ meters + fn draw_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { + let g = self.env.shared.gr_pk.swap(0.0, Ordering::Relaxed); + let cg = self.env.shared.clip_gr_pk.swap(0.0, Ordering::Relaxed); + self.gr_disp = g.max(self.gr_disp * 0.9); + self.clip_disp = cg.max(self.clip_disp * 0.9); + // the bar is the total reduction: the limiter's part as solid accent from the top, the clipper's hatched right under it + let total = self.gr_disp + self.clip_disp; + if g + cg >= self.gr_hold { + self.gr_hold = g + cg; + self.gr_hold_t = self.now; + } else if self.now - self.gr_hold_t > 1.0 { + self.gr_hold = (self.gr_hold - 0.4).max(0.0); + } + if self.hit(x, y, w, h) && self.press && self.act == 0 { + self.gr_ri = if self.gr_ri >= 3 { 0 } else { self.gr_ri + 1 }; + self.press = false; + } + let rng = |i: usize| [3.0f32, 6.0, 12.0, 18.0][i.min(3)]; + while self.gr_ri < 3 && total > rng(self.gr_ri) { + self.gr_ri += 1; + } + let rg = rng(self.gr_ri); + self.setc(false); + self.cv.boxr(x, y, w, h); + self.setc(true); + let lim_h = ((h - 2.0) * (self.gr_disp / rg).min(1.0)).floor(); + let all_h = ((h - 2.0) * (total / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, lim_h); + let mut ry = y + 1.0 + lim_h; + while ry < y + 1.0 + all_h { + self.cv.fill(x + 1.0, ry, w - 2.0, 1.0); // hatched: every other row + ry += 2.0; + } + self.setc(false); + let hp = y + 1.0 + ((h - 3.0) * (self.gr_hold / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, hp, w - 2.0, 1.0); + self.cv.set_font(1); + // total GR as a number in a window at the top of the bar (positive, like the bar) + self.cv.setbg(); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, 11.0); + self.setc(false); + self.cv.fill(x + 1.0, y + 12.0, w - 2.0, 1.0); + let gs = format!("{:.1}", self.rd_gr + self.rd_clip); + self.cv.textc(x, y + 3.0, w, &gs); + let mj = if rg == 3.0 { 1.0 } else if rg == 6.0 { 2.0 } else if rg == 12.0 { 3.0 } else { 6.0 }; + let stp = if rg <= 6.0 { 0.5 } else { 1.0 }; + let cnt = (rg / stp) as i32; + for j in 1..=cnt { + let v = j as f32 * stp; + let ty = y + 1.0 + (h - 2.0) * (v / rg); + let major = v == v.floor() && (v.floor() % mj) == 0.0; + if major { + self.cv.fill(x + w - 5.0, ty, 4.0, 1.0); + let s = format!("{}", v as i32); + self.cv.text(x + 2.0, (ty - 4.0).min(y + h - 11.0), &s); + } else { + self.cv.fill(x + w - 3.0, ty, 2.0, 1.0); + } + } + } + + /// Post-saturator level (summed channels), segmented (-48..0 dB). The clip lamp is a block at the top of the bar, the + /// height of the GR value window, in the accent colour while the saturator output is over 0 dBFS and for 1 s after. + fn sat_vu(&mut self, x: f32, y: f32, w: f32, h: f32) { + let pk = self.env.shared.sat_pk.swap(0.0, Ordering::Relaxed); + self.sat_lv = pk.max(self.sat_lv * 0.85); + if pk >= 1.0 { + self.sat_clip_t = self.now; + } + let clip = self.now - self.sat_clip_t < 1.0; + let lamp = 12.0; + let (by, bh) = (y + lamp + 1.0, h - lamp - 1.0); + let lvf = |v: f32| ((8.6858896 * v.max(0.0000001).ln() + 48.0) / 48.0).clamp(0.0, 1.0); + self.setc(false); + self.cv.boxr(x, by, w, bh); + // 2 px segments, 1 px gaps, filled from the bottom + let segs = ((bh - 2.0) / 3.0).floor() as i32; + let on = (segs as f32 * lvf(self.sat_lv)).ceil() as i32; + for i in 0..on.min(segs) { + self.cv.fill(x + 1.0, by + bh - 1.0 - 2.0 - i as f32 * 3.0, w - 2.0, 2.0); + } + self.setc(clip); + if clip { + self.cv.fill(x, y, w, lamp); + } else { + self.cv.boxr(x, y, w, lamp); + } + self.setc(false); + } + + /// Stereo output level, vertical: two bars with peak holds over a selectable range (click the bars to cycle 48 / 24 / 12 / + /// 6 dB), small dB labels in the background colour on top of the bars, and a clip lamp at the top (accent after any over + /// 0 dBFS; click it to reset the lamp and the peak readout). The true / sample peak readout is tracked here too. + fn out_vu(&mut self, x: f32, y: f32, w: f32, h: f32) { + let sh = self.env.shared; + let pa = sh.opk[0].swap(0.0, Ordering::Relaxed); + let pb = sh.opk[1].swap(0.0, Ordering::Relaxed); + let tp = sh.tpk.swap(0.0, Ordering::Relaxed); + if sh.clip.swap(false, Ordering::Relaxed) { + self.clip_lat = true; + self.clip_t = self.now; + } + let lamp = 12.0; + let (by, bh) = (y + lamp + 1.0, h - lamp - 1.0); + if self.hit(x, y, w, lamp) && self.press && self.act == 0 { + self.opk_max = 0.0; + self.clip_lat = false; + self.hl_l = 0.0; + self.hl_r = 0.0; + self.press = false; + } + if self.hit(x, by, w, bh) && self.press && self.act == 0 { + self.vu_ri = (self.vu_ri + 1) % VU_RANGES.len(); + self.press = false; + } + self.ovl = pa.max(self.ovl * 0.85); + self.ovr = pb.max(self.ovr * 0.85); + let now = self.now; + if pa >= self.hl_l { + self.hl_l = pa; + self.hl_l_t = now; + } else if now - self.hl_l_t > 1.0 { + self.hl_l *= 0.9; + } + if pb >= self.hl_r { + self.hl_r = pb; + self.hl_r_t = now; + } else if now - self.hl_r_t > 1.0 { + self.hl_r *= 0.9; + } + self.opk_max = self.opk_max.max(tp); + let (rng, labels) = VU_RANGES[self.vu_ri]; + let bw = ((w - 3.0) * 0.5).floor(); + let lvf = |v: f32| ((8.6858896 * v.max(0.0000001).ln() + rng) / rng).clamp(0.0, 1.0); + self.setc(false); + self.cv.boxr(x, by, w, bh); + for (i, (lv, hl)) in [(self.ovl, self.hl_l), (self.ovr, self.hl_r)].into_iter().enumerate() { + let bx = x + 1.0 + i as f32 * (bw + 1.0); + let fh = ((bh - 2.0) * lvf(lv)).floor(); + if fh > 0.0 { + self.cv.fill(bx, by + bh - 1.0 - fh, bw, fh); + } + if hl > 0.0001 { + self.cv.fill(bx, by + bh - 2.0 - ((bh - 3.0) * lvf(hl)).floor(), bw, 1.0); + } + } + // dB labels (no sign) in the background colour on top of the bars, ticks beside them + self.cv.set_font(1); + for &db in labels { + let ty = by + bh - 1.0 - ((bh - 2.0) * ((db as f32 + rng) / rng)).floor(); + self.setc(false); + self.cv.fill(x + w, ty, 3.0, 1.0); + self.cv.setbg(); + self.cv.text(x + 2.0, (ty - 4.0).min(by + bh - 11.0), &format!("{}", -db)); + } + let clip = self.clip_lat; + self.setc(clip); + if clip { + self.cv.fill(x, y, w, lamp); + } else { + self.cv.boxr(x, y, w, lamp); + } + self.setc(false); + } + + // ------------------------------------------------------------------ sat plot + /// BIAS over ASYM as one stacked group (like HP / LP). ASYM is the current shaper's share of its even part (the part that + /// carries DC and sub-audio pulses): one value per shaper, stored in the project / presets (not a host parameter). + /// Drag, wheel, double-click = 100 %. + fn bias_asym(&mut self, x: f32, y: f32, w: f32, h: f32) { + let hh = (h * 0.5).floor(); + let shape = ((self.sget(1) + 0.5).floor() as i32).clamp(0, CUSTOM) as usize; + let cell = self.env.params.asym.clone(); + let get = || satcomp_dsp::shapers::asym_from(&cell.lock())[shape] as f32; + let set = |v: f32| { + let mut g = cell.lock(); + if g.len() < SHAPER_NAMES.len() { + g.resize(SHAPER_NAMES.len(), 100.0); + } + g[shape] = v.clamp(0.0, 100.0); + }; + // top half: BIAS (an ordinary slider) + let ha = self.hit(x, y, w, hh); + if ha && self.press && self.act == 0 { + self.begin_drag(3); + } + if ha && self.wheel != 0 { + self.wheel_adj(3); + } + // bottom half: ASYM + let hb = self.hit(x, y + hh, w, h - hh); + if hb && self.press && self.act == 0 { + if self.dbl(170) { + set(100.0); + } else { + self.act = ACT_ASYM; + self.asym_drag = (self.my, get() * 0.01); + } + self.press = false; + } + if hb && self.wheel != 0 { + let d = if self.wheel > 0 { 1.0 } else { -1.0 } * if self.shift { 0.5 } else { 3.0 }; + set((get() + d).round()); + } + if self.act == ACT_ASYM && self.down { + let k = if self.shift { 0.0008 } else { 0.006 }; + let t = (self.asym_drag.1 + (self.asym_drag.0 - self.my) * k).clamp(0.0, 1.0); + set((t * 100.0).round()); + } + let act = self.act; + self.setc(act == 3 || act == ACT_ASYM); + self.cv.boxr(x, y, w, h); + self.setc(false); + self.cv.fill(x, y + hh, w, 1.0); + self.cv.set_font(1); + self.setc(act == 3); + let vb = self.sget(3); + let sb = self.fmt(3, vb); + let tb = self.n2t(3, vb); + self.cv.text(x + 3.0, y + 3.0, "BIAS"); + self.cv.textr(x, y + 3.0, w - 3.0, &sb); + self.cv.fill(x + 2.0, y + hh - 3.0, ((tb * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(act == ACT_ASYM); + let v = get(); + self.cv.text(x + 3.0, y + hh + 3.0, "ASYM"); + self.cv.textr(x, y + hh + 3.0, w - 3.0, &format!("{:.0}%", v)); + self.cv.fill(x + 2.0, y + h - 4.0, (((v * 0.01) * (w - 4.0)).floor()).max(1.0), 2.0); + self.setc(false); + } + + fn draw_plot(&mut self, x: f32, y: f32, w: f32, h: f32) { + let sh = self.env.shared; + let dsp = self.env.dsp; + let sat_on = dsp.drive > 0.0 || dsp.bias != 0.0; + let pre = (dsp.drive * 0.01 * 36.0 * 0.11512925).exp() as f32; + let bias = (dsp.bias * 0.01) as f32; + self.lut.sync(dsp.shape, &dsp.curve); + // static curve as heard: the shaper minus the part of its even half that ASYM removes + let ak = dsp.asym[(dsp.shape.max(0) as usize).min(dsp.asym.len() - 1)] * 0.01; + let eff = move |l: &ShaperLut, v: f64| { + let r = 0.5 * (1.0 - ak); + l.eval(v) * (1.0 - r) - r * l.eval(-v) + }; + // pencil (top right): toggles the custom-curve draw view; entering selects the Custom shaper so edits are audible + let pen = self.hit(x + w - 14.0, y + 2.0, 12.0, 12.0); + if pen && self.press && self.act == 0 { + self.curve_edit = !self.curve_edit; + self.edit_seen = false; + if self.curve_edit { + self.click_set(1, CUSTOM as f32); + // symmetry is the default tool, unless the stored curve is lopsided: opening must not alter it + self.sym_mode = self.env.params.curve_snapshot().is_odd(); + } + self.press = false; + } + if self.curve_edit { + if (self.sget(1) + 0.5).floor() as i32 == CUSTOM { + self.edit_seen = true; + } else if self.edit_seen { + self.curve_edit = false; // another shaper was chosen + } + } + let hv = self.hit(x, y, w, h) && !self.curve_edit; + let tb = self.hit(x + w - 84.0, y + h - 14.0, 82.0, 12.0); + if hv && self.press && self.act == 0 { + if tb { + self.env.shared.sat_req.store(true, Ordering::Relaxed); // measure 3 s, then write SAT GAIN + self.press = false; + } else { + self.begin_drag(27); + } + } + if hv && self.wheel != 0 { + self.wheel_adj(27); + } + self.setc(self.act == 27); + self.cv.boxr(x, y, w, h); + for i in 0..(w / 2.0).floor() as i32 { + self.cv.fill(x + i as f32 * 2.0, y + (h / 2.0).floor(), 1.0, 1.0); + } + for i in 0..(h / 2.0).floor() as i32 { + self.cv.fill(x + (w / 2.0).floor(), y + i as f32 * 2.0, 1.0, 1.0); + } + if self.curve_edit { + self.close_glyph(x + w - 14.0, y + 2.0, pen); + } else { + self.pencil_glyph(x + w - 14.0, y + 2.0, false, pen); + } + if self.curve_edit { + self.draw_curve_edit(x, y, w, h); + return; + } + let pk = sh.sat_vz.load(Ordering::Relaxed).min(1.0); + let n = 64; + let (mut lx, mut ly) = (0.0, 0.0); + for i in 0..=n { + let vx = -1.0 + 2.0 * i as f32 / n as f32; + let mut vy = if sat_on { eff(&self.lut, (vx * pre + bias) as f64) as f32 } else { vx }; + vy = vy.clamp(-1.0, 1.0); + let px = x + (vx + 1.0) * 0.5 * (w - 1.0); + let py = y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0); + self.setc(sat_on && pk > 0.002 && vx.abs() <= pk); + if i > 0 { + self.cv.line(lx, ly, px, py); + } + lx = px; + ly = py; + } + if sat_on && pk > 0.002 { + self.setc(true); + let vy = (eff(&self.lut, (pk * pre + bias) as f64) as f32).clamp(-1.0, 1.0); + self.cv.fill(x + (pk + 1.0) * 0.5 * (w - 1.0) - 1.0, y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0) - 1.0, 3.0, 3.0); + let vy = (eff(&self.lut, (-pk * pre + bias) as f64) as f32).clamp(-1.0, 1.0); + self.cv.fill(x + (1.0 - pk) * 0.5 * (w - 1.0) - 1.0, y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0) - 1.0, 3.0, 3.0); + self.setc(false); + } + // SAT OUT level marker on the left edge (-24..+12 dB) + let tot = self.sget(27); + let ty = y + (1.0 - (tot.clamp(-24.0, 12.0) + 24.0) / 36.0) * (h - 3.0); + self.setc(self.act == 27); + self.cv.fill(x + 1.0, ty, 7.0, 2.0); + if self.act == 27 { + for i in 0..(w / 3.0).floor() as i32 { + self.cv.fill(x + i as f32 * 3.0, ty, 1.0, 1.0); + } + } + self.setc(false); + self.cv.set_font(1); + let s = format!("OUT {:+.1}dB", tot); + self.cv.text(x + 3.0, y + 3.0, &s); + let s = if self.env.shared.sat_meas.load(Ordering::Relaxed) { + self.setc(appearance::blink(self.now)); + format!("MEAS {:.1}s", self.env.shared.sat_mt.load(Ordering::Relaxed)) + } else { + format!("SAT {:+.1}dB", self.rd_sat) + }; + self.cv.textr(x, y + h - 14.0, w - 3.0, &s); + self.setc(false); + } + + /// 12x12 pencil icon; lit while the draw view is open, bright on hover. + fn pencil_glyph(&mut self, x: f32, y: f32, on: bool, hover: bool) { + let prev = self.dk; // keep the bypass dimming of the surrounding module + self.set_dk(prev * if on || hover { 1.0 } else { 0.6 }); + self.setc(on); + let l = |s: &Self, a: f32, b: f32, c: f32, d: f32| s.cv.line(x + a, y + b, x + c, y + d); + l(self, 8.0, 1.0, 10.0, 3.0); // eraser cap + l(self, 8.0, 1.0, 1.0, 8.0); // body + l(self, 10.0, 3.0, 3.0, 10.0); + l(self, 1.0, 8.0, 0.0, 11.0); // tip + l(self, 3.0, 10.0, 0.0, 11.0); + self.set_dk(prev); + self.setc(false); + } + + /// Draw view of the custom curve (unity input, independent of drive/bias). Tools (top right, left of the close cross): + /// symmetry (default) draws the right half and mirrors it through the origin, `f(-x) = -f(x)`, the pencil draws free. + /// Left click empty space = add a point (and drag it), drag = move, double click = remove. + /// The two end points are fixed in x and cannot be removed. + fn draw_curve_edit(&mut self, x: f32, y: f32, w: f32, h: f32) { + let mut c = self.env.params.curve_snapshot(); + let before = c; + // tool icons left of the close cross: free draw (pencil), symmetry + let (pen_x, sym_x) = (x + w - 28.0, x + w - 42.0); + let (hp, hs) = (self.hit(pen_x, y + 2.0, 12.0, 12.0), self.hit(sym_x, y + 2.0, 12.0, 12.0)); + if self.press && self.act == 0 { + if hp && self.sym_mode { + self.sym_mode = false; + self.press = false; + } else if hs && !self.sym_mode { + // free -> symmetric keeps the odd part of the curve (what a symmetric curve can hold) + c = Curve::from_odd_half(&c.odd_half()); + self.sym_mode = true; + self.press = false; + } + } + let sym = self.sym_mode; + // domain [-1,1]^2 is inset so end points and the icons never collide (symmetric margins keep the centre cross true) + let (ex, ey, ew, eh) = (x + 9.0, y + 14.0, w - 18.0, h - 28.0); + let (px, py) = (|vx: f32| ex + (vx + 1.0) * 0.5 * (ew - 1.0), |vy: f32| ey + (1.0 - (vy + 1.0) * 0.5) * (eh - 1.0)); + let to_v = |mx: f32, my: f32| (((mx - ex) / (ew - 1.0)) * 2.0 - 1.0, 1.0 - ((my - ey) / (eh - 1.0)) * 2.0); + // working list: the whole curve, or in symmetry mode its right half (x > 0, ending at x = 1); the left is derived + let mut hv: Vec<(f32, f32)> = if sym { c.pts().iter().cloned().filter(|p| p.0 > 0.0).collect() } else { c.pts().to_vec() }; + if sym && hv.is_empty() { + hv.push((1.0, 1.0)); + } + let cap = if sym { MAX_PTS / 2 } else { MAX_PTS }; + let interior = |i: usize, n: usize| if sym { i + 1 < n } else { i > 0 && i + 1 < n }; + let xlo = |hv: &Vec<(f32, f32)>, i: usize| if i == 0 { if sym { 0.0 } else { -1.0 } } else { hv[i - 1].0 }; + // a point is picked on its own spot, or in symmetry mode on its mirror image + let pick = |s: &Self, hv: &Vec<(f32, f32)>| -> Option { + let mut best: Option<(usize, f32)> = None; + for (i, &(vx, vy)) in hv.iter().enumerate() { + let mut d = ((s.kit.mx - px(vx)).powi(2) + (s.kit.my - py(vy)).powi(2)).sqrt(); + if sym { + d = d.min(((s.kit.mx - px(-vx)).powi(2) + (s.kit.my - py(-vy)).powi(2)).sqrt()); + } + if d <= 6.0 && best.map_or(true, |b| d < b.1) { + best = Some((i, d)); + } + } + best.map(|b| b.0) + }; + let in_box = self.hit(x, y, w, h) && !self.hit(sym_x, y + 2.0, 56.0, 12.0); + if in_box && self.press && self.act == 0 { + let n = hv.len(); + if let Some(i) = pick(self, &hv) { + if self.dbl(200 + i as i32) && interior(i, n) { + hv.remove(i); + self.last_clk_n = 0; + } else { + self.act = 160; + self.cpt = i; + } + } else if n < cap { + let (mut vx, mut vy) = to_v(self.mx, self.my); + if sym && vx < 0.0 { + vx = -vx; + vy = -vy; + } + let at = if sym { hv.iter().position(|p| p.0 > vx) } else { (1..n).find(|&k| hv[k].0 > vx) }.unwrap_or(n - 1); + let room = vx - xlo(&hv, at) >= MIN_GAP && hv[at].0 - vx >= MIN_GAP; + if room { + hv.insert(at, (vx, vy.clamp(-1.0, 1.0))); + self.act = 160; + self.cpt = at; + self.last_clk_n = 0; // a creating click never counts towards a double click + } + } + self.vt1 = 0; + self.vt2 = 0; + self.press = false; + } + if self.act == 160 && self.down && self.cpt < hv.len() { + let (mut vx, mut vy) = to_v(self.mx, self.my); + let i = self.cpt; + if sym { + // dragging the ghost half moves the real point the other way round + if vx < 0.0 { + vx = -vx; + vy = -vy; + } + } + let n = hv.len(); + if interior(i, n) { + hv[i].0 = vx.clamp(xlo(&hv, i) + MIN_GAP, hv[i + 1].0 - MIN_GAP); + } + hv[i].1 = vy.clamp(-1.0, 1.0); + } + c = if sym { Curve::from_odd_half(&hv) } else { Curve::from_points(&hv) }; + if c != before { + *self.env.params.custom_curve.lock() = c.pts().to_vec(); + } + // identity reference (dotted), the curve, then the points + let prev = self.dk; + self.set_dk(prev * 0.5); + self.setc(false); + for i in 0..(ew / 3.0).floor() as i32 { + let vx = -1.0 + 2.0 * i as f32 / (ew / 3.0).floor(); + self.cv.fill(px(vx), py(vx), 1.0, 1.0); // identity + self.cv.fill(px(vx), py(1.0), 1.0, 1.0); // domain frame (+-1) + self.cv.fill(px(vx), py(-1.0), 1.0, 1.0); + self.cv.fill(px(1.0), py(vx), 1.0, 1.0); + self.cv.fill(px(-1.0), py(vx), 1.0, 1.0); + } + self.set_dk(prev); + let n = 96; + let (mut lx, mut ly) = (px(-1.0), py(c.eval(-1.0) as f32)); + for i in 1..=n { + let vx = -1.0 + 2.0 * i as f32 / n as f32; + let (qx, qy) = (px(vx), py(c.eval(vx as f64) as f32)); + self.cv.line(lx, ly, qx, qy); + lx = qx; + ly = qy; + } + let hot = if self.act == 160 { Some(self.cpt) } else { pick(self, &hv) }; + let nh = hv.len(); + for (i, &(vx, vy)) in hv.iter().enumerate() { + let (qx, qy) = (px(vx).round(), py(vy).round()); + self.setc(hot == Some(i)); + let end = if sym { i + 1 == nh } else { i == 0 || i + 1 == nh }; + if end { + self.cv.boxr(qx - 2.0, qy - 2.0, 5.0, 5.0); // y-only end points + } else { + self.cv.fill(qx - 2.0, qy - 2.0, 5.0, 5.0); + } + if sym { + // the mirrored partner: a dim outline you can grab just the same + let (gx, gy) = (px(-vx).round(), py(-vy).round()); + let pd = self.dk; + self.set_dk(pd * 0.6); + self.cv.boxr(gx - 2.0, gy - 2.0, 5.0, 5.0); + self.set_dk(pd); + } + } + self.setc(false); + // tools: pencil (free draw), symmetry + self.pencil_glyph(pen_x, y + 2.0, !sym, hp); + self.sym_glyph(sym_x, y + 2.0, sym, hs); + self.cv.set_font(1); + self.cv.text(x + 3.0, y + 3.0, "DRAW"); + self.cv.textr(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, MAX_PTS)); + } + + // ------------------------------------------------------------------ comp plot + + + // ------------------------------------------------------------------ EQ page + + + + + + + + + + // ------------------------------------------------------------------ window size + fn cur_scale(&self) -> f32 { + self.env.params.editor_state.size().0 as f32 / W + } + + /// Ask the host to resize the editor to `scale` x the W x H base size (aspect locked). + fn request_scale(&mut self, scale: f32) { + let sc = scale.clamp(SIZES[0], SIZES[SIZES.len() - 1]); + if (sc - self.cur_scale()).abs() > 0.001 { + self.env.params.editor_state.set_requested_size(((W * sc).round() as u32, (H * sc).round() as u32)); + } + } + + /// Bottom-right grip: drag = aspect-locked resize in 25% steps, right-click = size menu. + fn resize_grip(&mut self) { + let (gx, gy, gw, gh) = (W - 16.0, H - 16.0, 16.0, 16.0); + let hv = self.hit(gx, gy, gw, gh); + if hv && self.press && self.act == 0 { + self.resizing = true; + // distance from the pointer to the window's bottom-right corner, in window points + self.resize_off = (self.win_pt.0 - self.ptr_pt.0, self.win_pt.1 - self.ptr_pt.1); + self.press = false; + } + if hv && self.rpress { + let items = SIZES.iter().map(|v| format!("{:.0}%", v * 100.0)).collect(); + let cur = SIZES.iter().position(|v| (v - self.cur_scale()).abs() < 0.13).unwrap_or(0); + self.open_menu(MenuKind::Size, gx - 40.0, gy - 90.0, items, cur); + } + if self.resizing { + if self.down { + // Absolute target (pointer + fixed corner offset), independent of the lagging render + // scale. Only issue a new request once the host window has caught up with the last one, + // otherwise stale pointer/size pairs make the target overshoot and the window loops. + let (cw, _) = self.env.params.editor_state.size(); + let caught_up = (self.win_pt.0 - cw as f32).abs() < 1.5; + if caught_up { + let w = (self.ptr_pt.0 + self.resize_off.0) / W; + let h = (self.ptr_pt.1 + self.resize_off.1) / H; + self.request_scale((w.min(h) * 4.0).round() / 4.0); + } + } else { + self.resizing = false; + } + } + self.set_dk(1.0); + self.setc(self.resizing); + for o in [4.0, 8.0, 12.0] { + self.cv.line(W - 1.0, H - 1.0 - o, W - 1.0 - o, H - 1.0); + } + self.setc(false); + } + + // ------------------------------------------------------------------ popup menu (replaces gfx_showmenu) + /// (x, y, w, h, visible rows) of the open menu, clamped to the canvas. + fn menu_geom(&self) -> Option<(f32, f32, f32, f32, usize)> { + let m = self.menu.as_ref()?; + let tw = m.items.iter().map(|i| self.cv.text_w(&i.label)).fold(0.0, f32::max); + let rows = m.items.len().min(MENU_ROWS); + let (mw, mh) = (tw + 26.0, MENU_ROW_H * rows as f32 + 2.0); + let x = m.x.min(560.0 - mw).max(0.0); + let y = m.y.min(336.0 - mh).max(0.0); + Some((x, y, mw, mh, rows)) + } + + fn menu_frame(&mut self) { + let Some((x, y, mw, mh, rows)) = self.menu_geom() else { return }; + let inside = self.hit(x, y, mw, mh); + let row = ((self.my - y - 1.0) / MENU_ROW_H).floor() as i32; + let mut chosen: Option<(i32, u8)> = None; + let mut close = false; + let (wheel, press, rpress) = (self.wheel, self.press, self.rpress); + if let Some(m) = self.menu.as_mut() { + if wheel != 0 && m.items.len() > rows { + let max = m.items.len() - rows; + m.scroll = (m.scroll as i32 - wheel).clamp(0, max as i32) as usize; + } + if press { + if inside && row >= 0 && (row as usize) < rows { + if let Some(it) = m.items.get(m.scroll + row as usize) { + if it.kind == 0 { + chosen = Some((it.id, match m.kind { + MenuKind::Shape => 0, + MenuKind::Palette => 1, + MenuKind::Size => 2, + MenuKind::Preset => 3, + })); + } else { + return self.eat_menu_input(); + } + } + } + close = true; + } + if rpress { + close = true; + } + } + if close || chosen.is_some() { + self.menu = None; + if let Some((id, kind)) = chosen { + match kind { + 0 => self.click_set(1, id as f32), + 1 if id >= 1000 => self.set_light(!self.light), + 1 => self.set_pal(id as usize), + 2 => self.request_scale(SIZES[(id as usize).min(SIZES.len() - 1)]), + _ => self.preset_action(id), + } + } + } + self.eat_menu_input(); + } + + fn eat_menu_input(&mut self) { + self.press = false; + self.rpress = false; + self.wheel = 0; + } + + fn menu_draw(&mut self) { + let Some((x, y, mw, mh, rows)) = self.menu_geom() else { return }; + let Some(m) = self.menu.as_ref() else { return }; + let items: Vec = m.items.iter().skip(m.scroll).take(rows).cloned().collect(); + let checked = m.checked; + let (more_up, more_down) = (m.scroll > 0, m.scroll + rows < m.items.len()); + self.cv.dk = 1.0; + self.cv.setbg(); + self.cv.fill(x, y, mw, mh); + self.setc(false); + self.cv.boxr(x, y, mw, mh); + self.cv.set_font(1); + let hov = ((self.my - y - 1.0) / MENU_ROW_H).floor() as i32; + for (i, it) in items.iter().enumerate() { + let iy = y + 1.0 + i as f32 * MENU_ROW_H; + match it.kind { + 2 => { + self.setc(false); + self.cv.fill(x + 4.0, iy + 6.0, mw - 8.0, 1.0); + } + 1 => { + self.cv.dk = 0.5; + self.setc(false); + self.cv.text(x + 6.0, iy + 1.0, &it.label); + self.cv.dk = 1.0; + } + _ => { + let hot = self.hit(x, y, mw, mh) && hov == i as i32; + self.setc(false); + if hot { + self.cv.fill(x + 1.0, iy, mw - 2.0, MENU_ROW_H); + self.cv.setbg(); + } + if it.id == checked { + self.cv.fill(x + 5.0, iy + 5.0, 4.0, 4.0); + } + self.cv.text(x + 14.0, iy + 1.0, &it.label); + } + } + } + self.setc(false); + if more_up { + self.cv.tri((x + mw - 10.0, y + 7.0), (x + mw - 4.0, y + 7.0), (x + mw - 7.0, y + 3.0)); + } + if more_down { + self.cv.tri((x + mw - 10.0, y + mh - 7.0), (x + mw - 4.0, y + mh - 7.0), (x + mw - 7.0, y + mh - 3.0)); + } + } + + // ------------------------------------------------------------------ presets + fn preset_name(&self) -> String { + self.env.params.preset_name.lock().clone() + } + + fn set_preset_name(&mut self, n: &str) { + *self.env.params.preset_name.lock() = n.to_string(); + } + + /// Write every stored parameter of `p` (missing ids -> default). Bypass / Gain Match are left alone. + fn apply_preset(&mut self, p: &Preset) { + for &(n, id, mn, mx, df) in TABLE { + if presets::EXCLUDED.contains(&id) { + continue; + } + let v = p.params.get(id).copied().unwrap_or(df).clamp(mn, mx); + self.click_set(n, v); + } + // absent curve = linear (deterministic: loading a preset never keeps the previous preset's curve) + let c = Curve::from_points(&p.curve); + *self.env.params.custom_curve.lock() = c.pts().to_vec(); + *self.env.params.asym.lock() = satcomp_dsp::shapers::asym_from(&p.asym).iter().map(|&v| v as f32).collect(); + self.set_preset_name(&p.name); + self.base = None; + self.hold_until = self.now + 0.6; + } + + /// True when the live parameters differ from the loaded preset (drives the *NAME* marker). + fn is_modified(&mut self) -> bool { + if self.now < self.hold_until { + return false; // host parameter writes land a few frames late after a load + } + let cur = self.preset_name(); + let key = if cur.is_empty() { "INIT".to_string() } else { cur }; + if self.base.as_ref().map(|b| b.0 != key).unwrap_or(true) { + let p = if key == "INIT" && self.factory.iter().all(|f| f.name != "INIT") { + Some(Preset::init()) + } else { + self.preset_index().and_then(|i| self.preset_at(i)) + }; + self.base = p.map(|p| (key, p)); + } + let Some((_, b)) = &self.base else { return false }; + for &(n, id, mn, mx, df) in TABLE { + if presets::EXCLUDED.contains(&id) { + continue; + } + let want = b.params.get(id).copied().unwrap_or(df).clamp(mn, mx); + let have = self.sget(n); + if (want - have).abs() > 2e-4 * want.abs().max(have.abs()) + 1e-4 { + return true; + } + } + Curve::from_points(&b.curve) != self.env.params.curve_snapshot() || satcomp_dsp::shapers::asym_from(&b.asym) != self.env.params.asym_snapshot() + } + + fn capture(&self, name: &str) -> Preset { + let params = TABLE + .iter() + .filter(|e| !presets::EXCLUDED.contains(&e.1)) + .map(|e| (e.1.to_string(), self.sget(e.0))) + .collect(); + let mut p = Preset::new(name, params); + let c = self.env.params.curve_snapshot(); + if c != Curve::linear() { + p.curve = c.pts().to_vec(); + } + let a = self.env.params.asym_snapshot(); + if a.iter().any(|&v| v != 100.0) { + p.asym = a.iter().map(|&v| v as f32).collect(); + } + p + } + + fn preset_count(&self) -> usize { + self.factory.len() + self.user.len() + } + + fn preset_at(&self, i: usize) -> Option { + if i < self.factory.len() { + Some(self.factory[i].clone()) + } else { + let (name, path) = self.user.get(i - self.factory.len())?; + presets::load_file(path).map(|mut p| { + p.name = name.clone(); + p + }) + } + } + + fn preset_index(&self) -> Option { + let cur = self.preset_name(); + let cur = if cur.is_empty() { "INIT".to_string() } else { cur }; + self.factory + .iter() + .position(|p| p.name == cur) + .or_else(|| self.user.iter().position(|u| u.0 == cur).map(|i| i + self.factory.len())) + } + + fn step_preset(&mut self, dir: i32) { + self.user = presets::scan_user(); + let n = self.preset_count() as i32; + let next = match self.preset_index() { + Some(i) => (i as i32 + dir).rem_euclid(n), + None => if dir > 0 { 0 } else { n - 1 }, + }; + if let Some(p) = self.preset_at(next as usize) { + self.apply_preset(&p); + } + } + + fn open_preset_menu(&mut self, x: f32, y: f32) { + self.user = presets::scan_user(); + let mut items = vec![ + MItem { label: "Initialize preset".into(), kind: 0, id: 1 }, + MItem { label: "Load preset...".into(), kind: 0, id: 0 }, + MItem { label: String::new(), kind: 2, id: -1 }, + MItem { label: "FACTORY".into(), kind: 1, id: -1 }, + ]; + // factory[0] is the built-in INIT: it is the "Initialize preset" entry above, so not listed twice + for (i, p) in self.factory.iter().enumerate().skip(1) { + items.push(MItem { label: p.name.clone(), kind: 0, id: 1000 + i as i32 }); + } + if !self.user.is_empty() { + items.push(MItem { label: String::new(), kind: 2, id: -1 }); + items.push(MItem { label: "USER".into(), kind: 1, id: -1 }); + for (i, u) in self.user.iter().enumerate() { + items.push(MItem { label: u.0.clone(), kind: 0, id: 2000 + i as i32 }); + } + } + let checked = match self.preset_index() { + Some(0) => 1, + Some(i) if i < self.factory.len() => 1000 + i as i32, + Some(i) => 2000 + (i - self.factory.len()) as i32, + None => -1, + }; + self.menu = Some(Menu { kind: MenuKind::Preset, x, y, items, checked, scroll: 0 }); + } + + fn preset_action(&mut self, id: i32) { + match id { + 0 => self.pending = 1, + 1 => self.apply_preset(&Preset::init()), + 1000..=1999 => { + if let Some(p) = self.preset_at((id - 1000) as usize) { + self.apply_preset(&p); + } + } + 2000.. => { + if let Some(p) = self.preset_at(self.factory.len() + (id - 2000) as usize) { + self.apply_preset(&p); + } + } + _ => {} + } + } + + /// File dialogs run on a worker thread: a modal NSSavePanel started inside our frame callback re-enters + /// the host window's event handling (resign-key) while the editor state is borrowed, which aborted REAPER. + /// rfd dispatches the panel to the main thread itself; the result is picked up by `poll_dialog`. + fn run_pending(&mut self) { + let what = std::mem::take(&mut self.pending); + if what == 0 || self.dlg.is_some() { + return; + } + let slot = Arc::new(parking_lot::Mutex::new(Dlg::Pending)); + self.dlg = Some(slot.clone()); + match what { + 1 => { + std::thread::spawn(move || { + let r = presets::open_dialog().and_then(|path| { + presets::load_file(&path).map(|mut p| { + if let Some(stem) = path.file_stem() { + p.name = stem.to_string_lossy().into_owned(); + } + p + }) + }); + *slot.lock() = r.map_or(Dlg::Cancelled, Dlg::Loaded); + }); + } + 2 => { + let cur = self.preset_name(); + let def = if cur.is_empty() || cur == "INIT" { "My preset".to_string() } else { cur }; + let snapshot = self.capture(&def); // parameters as of the click + std::thread::spawn(move || { + let r = presets::save_dialog(&def).and_then(|path| { + let name = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or(def); + let mut p = snapshot; + p.name = name.clone(); + presets::save_file(&path, &p).ok().map(|_| name) + }); + *slot.lock() = r.map_or(Dlg::Cancelled, Dlg::Saved); + }); + } + _ => self.dlg = None, + } + } + + /// Apply the outcome of a finished file dialog (called every frame). + fn poll_dialog(&mut self) { + let Some(slot) = self.dlg.clone() else { return }; + let r = std::mem::replace(&mut *slot.lock(), Dlg::Pending); + match r { + Dlg::Pending => return, + Dlg::Loaded(p) => self.apply_preset(&p), + Dlg::Saved(name) => { + self.set_preset_name(&name); + self.base = None; + self.user = presets::scan_user(); + } + Dlg::Cancelled => {} + } + self.dlg = None; + } + + /// Header preset bar (save icon | name | prev next) and the window-scale button. + fn preset_bar(&mut self) { + let (y, h) = (32.0, 16.0); // the logo box ends at 29: a 3 unit gap above, 4 to the scope below + // save icon + if self.btn(10.0, y, 26.0, h, "", 0) { + self.pending = 2; + } + self.setc(false); + self.cv.boxr(18.0, y + 3.0, 10.0, 10.0); + self.cv.fill(21.0, y + 3.0, 4.0, 3.0); + self.cv.boxr(20.0, y + 8.0, 6.0, 5.0); + // name -> dropdown + let name = self.preset_name(); + let shown = if name.is_empty() || name == "INIT" { "-- INIT --".to_string() } else { name }; + let hv = self.hit(36.0, y, 244.0, h); + if hv && self.press && self.act == 0 { + self.open_preset_menu(36.0, y + h); + self.press = false; + } + self.setc(false); + self.cv.boxr(36.0, y, 244.0, h); + self.cv.set_font(2); + let modified = self.is_modified(); + let mut t = shown; + while self.cv.text_w(&t) > if modified { 226.0 } else { 238.0 } && t.chars().count() > 3 { + t.pop(); + } + if modified { + t = format!("*{t}*"); + } + self.cv.textc(36.0, y + ((h - 8.0) * 0.5).floor(), 244.0, &t); + // prev / next + for (i, dir) in [(0, -1), (1, 1)] { + let x = 280.0 + i as f32 * 25.0; + if self.btn(x, y, 25.0, h, "", 0) { + self.step_preset(dir); + } + self.setc(false); + let (cx, cy) = (x + 12.5, y + h * 0.5); + if dir < 0 { + self.cv.tri((cx + 2.0, cy - 3.0), (cx + 2.0, cy + 3.0), (cx - 2.0, cy)); + } else { + self.cv.tri((cx - 2.0, cy - 3.0), (cx - 2.0, cy + 3.0), (cx + 2.0, cy)); + } + } + } + + // ------------------------------------------------------------------ about page + /// Signal-flow diagram: IN > SAT > CLIP > LIM > OUT GAIN > OUT. Dots move along the path; their size follows the live + /// output level (the stages before the limiter add the gain reduction back, so they read hotter). + fn draw_flow_at(&mut self, x: f32, y: f32, w: f32, h: f32, byp: bool) { + let prev = self.dk; + let sh = self.env.shared; + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.set_font(1); + self.cv.text(x + 6.0, y + 5.0, "SIGNAL FLOW"); + let lvf = |v: f32| ((8.6858896 * v.max(1e-7).ln() + 48.0) / 48.0).clamp(0.0, 1.0); + let lo = lvf(self.ovl.max(self.ovr)); + let gr = self.gr_disp; + let lp = (lo + gr / 48.0).min(1.0); + let sig = lo > 0.01; + let sat_on = sh.sat_vz.load(Ordering::Relaxed) > 0.02; + let clip_on = self.sget(11) > 0.5; + let names = ["IN", "SAT", "CLIP", "LIM", "OUT GAIN", "OUT"]; + let bw = [26.0, 34.0, 38.0, 34.0, 58.0, 30.0]; + let lit = [false, sat_on, clip_on, gr > 0.1, false, false]; + let n = names.len(); + let gap = (w - 24.0 - bw.iter().sum::()) / (n - 1) as f32; + let (cy, bh) = (y + 50.0, 22.0); + let mut bx = [0.0f32; 6]; + let mut cx = x + 12.0; + for i in 0..n { + bx[i] = cx; + cx += bw[i] + gap; + } + let phase = ((self.now * 26.0) as f32) % 6.0; + let dot = |c: &Canvas, px: f32, py: f32, lv: f32| { + if sig && lv > 0.02 { + let s = (1.0 + lv * 2.99).floor(); + c.fill((px - s * 0.5).floor(), (py - s * 0.5).floor() + 0.5, s, s); + } + }; + self.setc(false); + for i in 0..n - 1 { + let (g0, g1) = (bx[i] + bw[i], bx[i + 1]); + self.cv.fill(g0, cy, g1 - g0 - 3.0, 1.0); + self.cv.tri((g1 - 4.0, cy - 3.0), (g1 - 4.0, cy + 4.0), (g1, cy + 0.5)); + let lv = if i < 3 { lp } else { lo }; + let mut px = g0 + phase; + while px < g1 - 4.0 { + dot(&self.cv, px, cy, lv); + px += 6.0; + } + } + for i in 0..n { + let (bxl, byt) = (bx[i], cy - bh * 0.5 + 0.5); + if lit[i] { + self.setc(false); + self.cv.fill(bxl, byt, bw[i], bh); + self.cv.setbg(); + } else { + self.setc(false); + self.cv.fill(bxl + 1.0, byt + 1.0, bw[i] - 2.0, bh - 2.0); // clear the line under the box + self.cv.setbg(); + self.cv.fill(bxl + 1.0, byt + 1.0, bw[i] - 2.0, bh - 2.0); + self.setc(false); + self.cv.boxr(bxl, byt, bw[i], bh); + } + self.cv.textc(bxl, byt + 7.0, bw[i], names[i]); + self.setc(false); + } + self.set_dk(prev); + let s = format!("GR {:.1}", gr); + self.cv.textc(bx[3] - 10.0, cy - bh * 0.5 - 14.0, bw[3] + 20.0, &s); + self.cv.text(x + 6.0, y + h - 15.0, if sig { "DOT SIZE = LEVEL" } else { "PLAY AUDIO TO SEE THE FLOW" }); + let _ = byp; + } + + // ------------------------------------------------------------------ main frame + pub fn frame(&mut self) { + let sh = self.env.shared; + // Theme editor: every widget draws as a dummy with the input masked; only the editor cells and the picker get it. + let editing = self.app.editing(); + self.begin_frame_editing(); + if editing { + self.logo_pend = -1.0; + self.curve_edit = false; + self.menu = None; + } + // readouts refresh ~8x/s + self.rd_tick = self.now - self.rd_last >= 0.12; + if self.rd_tick { + self.rd_last = self.now; + self.rd_gr = self.gr_disp; + self.rd_clip = self.clip_disp; + self.rd_pk = self.opk_max; + self.rd_rms = sh.fms.load(Ordering::Relaxed); + self.rd_sat = sh.sat_db.load(Ordering::Relaxed); + } + // a finished sat level match writes SAT GAIN (the audio thread cannot set parameters) + if sh.sat_result_new.swap(false, Ordering::Acquire) { + let v = sh.sat_result.load(Ordering::Relaxed); + self.click_set(27, v); + } + self.refresh_dsp(); + self.menu_frame(); + + // drag update (single active widget). act 1..99 = slider number (vertical drag); act >= 100 = viewport drags + if self.act != 0 && self.act < 100 { + let a = self.act as usize; + if self.down { + let t_new = (self.act_t + (self.last_my - self.my) * if self.shift { 0.0008 } else { 0.006 }).clamp(0.0, 1.0); + self.act_t = t_new; + self.commit(a, t_new); + } else { + self.end_touch(a); + self.act = 0; + } + } + if self.act >= 100 && !self.down { + let (v1, v2) = (self.vt1, self.vt2); + if v1 > 0 { + self.end_touch(v1); + } + if v2 > 0 { + self.end_touch(v2); + } + self.act = 0; + } + self.last_my = self.my; + + let byp = self.sget(26) > 0.5; + let look = self.sget(12) > 0.5; + + // ---------- header row: logo, title, size, DELTA, BYPASS + self.set_dk(1.0); + self.logo(13.0, 5.0); + self.setc(false); + self.cv.set_font(2); + let title = format!("SATLIM {}", version_short()); + let tw = self.cv.text_w(&title); + if self.hit(42.0, 5.0, tw + 4.0, 21.0) && self.press && self.act == 0 { + self.app.about = if self.app.about == 0 { 1 } else { 0 }; + self.app.about_scroll = 0; + self.press = false; + } + // hovering highlights the title (a UI-coloured rectangle behind it, the text in the background colour): it opens About + if self.hit(42.0, 5.0, tw + 4.0, 21.0) { + self.cv.fill(42.0, 8.0, tw + 4.0, 15.0); + self.cv.setbg(); + } + self.cv.text(44.0, 12.0, &title); + self.setc(false); + let label = format!("{:.0}%", self.cur_scale() * 100.0); + if self.btn(176.0, 7.0, 42.0, 17.0, &label, 0) { + let cur = SIZES.iter().position(|v| (v - self.cur_scale()).abs() < 0.13).unwrap_or(0); + let items = SIZES.iter().map(|v| format!("{:.0}%", v * 100.0)).collect(); + self.open_menu(MenuKind::Size, 176.0, 24.0, items, cur); + } + let delta = sh.delta_on.load(Ordering::Relaxed); + if self.btn(222.0, 7.0, 50.0, 17.0, "DELTA", if delta { 2 } else { 0 }) { + sh.delta_on.store(!delta, Ordering::Relaxed); + } + if self.btn(274.0, 7.0, 56.0, 17.0, "BYPASS", byp as u8) { + self.click_set(26, if byp { 0.0 } else { 1.0 }); + } + + // ---------- preset row (the About tabs take its place while the About page is open) + let ab = self.app.about > 0; + if !ab { + self.preset_bar(); + } + self.set_dk(if byp { 0.5 } else { 1.0 }); + if ab { + self.draw_about(Rect::new(10.0, 54.0, 320.0, 438.0), byp); + } + + if !ab { + // ---------- transient scope (what the clipper and limiter removed stacks on the output in the accent colour) + self.draw_scope(10.0, 52.0, 320.0, 112.0); + self.scope_row(10.0, 163.0, 320.0); + + // ---------- SAT module + self.selector(1, 10.0, 188.0, 130.0, 16.0); + self.draw_plot(10.0, 208.0, 130.0, 156.0); + // the theme editor's dummy page keeps the plot, the meters (shorter) and the limiter readouts; its cell group + // takes the place of the sat cells + let mh = if editing { 146.0 } else { 282.0 }; + if editing { + self.theme_cells(CellGrid { x0: 10.0, y0: 368.0, cw: 62.0, ch: 38.0, px: 68.0, py: 42.0 }); + } else { + self.cell(2, 10.0, 368.0, 62.0, 38.0, "DRIVE"); + self.bias_asym(78.0, 368.0, 62.0, 38.0); + self.cell2(4, 5, 10.0, 410.0, 62.0, 38.0, "HP", "LP"); + self.cell(6, 78.0, 410.0, 62.0, 38.0, "TONE"); + self.cell(25, 10.0, 452.0, 62.0, 38.0, "SAT MIX"); + self.cell_o(27, 78.0, 452.0, 62.0, 38.0, "SAT GAIN"); + } + // sat out, GR and output meters + self.sat_vu(146.0, 208.0, 20.0, mh); + self.draw_meter(170.0, 208.0, 24.0, mh); + self.out_vu(198.0, 208.0, 26.0, mh); + } + + // ---------- limiter column: oversampling, readouts, L.AHEAD, cells (the thin About layout hides them) + self.set_dk(1.0); + let (cx, cw) = (232.0, 98.0); + if !ab { + // OVERSAMPL sits on the shape selector's row, centred over the meter bars; x1..x8 share that row at the column width + self.cv.set_font(1); + self.set_dk(if byp { 0.5 } else { 1.0 }); // full UI colour like the other components, dimmed on bypass like them + self.setc(false); + self.cv.textc(146.0, 192.0, 78.0, "OVERSAMPLE"); + self.set_dk(if byp { 0.5 } else { 1.0 }); + let os_i = (self.sget(7) + 0.5).floor() as i32; + for i in 0..4 { + let l = ["x1", "x2", "x4", "x8"][i as usize]; + let (bx, bx2) = (cx + (cw * i as f32 / 4.0).floor(), cx + (cw * (i + 1) as f32 / 4.0).floor()); + if self.btn(bx, 188.0, bx2 - bx + 1.0, 16.0, l, (os_i == i) as u8) { + self.click_set(7, i as f32); + } + } + self.set_dk(1.0); + self.cv.set_font(1); + // GR (the limiter) and CLIP (the clipper) stay in the UI colour at all times; only the true peak turns accent on a clip + self.setc(false); + self.cv.text(cx, 214.0, "GR"); + let s1 = if byp { "-----dB".to_string() } else { format!("{:04.1}dB", self.rd_gr) }; + self.cv.textr(cx, 214.0, cw, &s1); + self.cv.text(cx, 225.0, "CLIP"); + let s1 = if byp { "-----dB".to_string() } else { format!("{:04.1}dB", self.rd_clip) }; + self.cv.textr(cx, 225.0, cw, &s1); + self.setc(self.rd_pk > 1.0); + self.cv.text(cx, 236.0, "TRU.PK"); + let s1 = if self.rd_pk > 0.00001 { format!("{:+05.1}dB", 8.6858896 * self.rd_pk.ln()) } else { "-----dB".into() }; + self.cv.textr(cx, 236.0, cw, &s1); + self.setc(false); + self.cv.text(cx, 247.0, "RMS"); + let s1 = if self.rd_rms > 0.000000001 { format!("{:+05.1}dB", 4.3429448 * self.rd_rms.ln()) } else { "-----dB".into() }; + self.cv.textr(cx, 247.0, cw, &s1); + + self.set_dk(if byp { 0.5 } else { 1.0 }); + if self.btn(cx, 262.0, cw, 16.0, if look { "L.AHEAD ON" } else { "L.AHEAD OFF" }, look as u8) { + self.click_set(12, if look { 0.0 } else { 1.0 }); + } + self.cell(8, cx, 284.0, cw, 38.0, "CEILING"); + if !editing { + self.cell(9, cx, 326.0, cw, 38.0, "THRESHOLD"); + self.cell(11, cx, 368.0, cw, 38.0, "CLIP"); + self.cell(10, cx, 410.0, cw, 38.0, "RELEASE"); + self.cell_o(22, cx, 452.0, cw, 38.0, "OUT GAIN"); + } + } + + self.resize_grip(); + self.menu_draw(); + self.poll_dialog(); + self.run_pending(); + if editing { + self.unmask_in(); + let osk = self.app.osk_open(); + if osk { + self.mask_in(); // picker stays visible underneath but inert + } + self.theme_picker(Rect::new(10.0, 52.0, 320.0, 129.0)); + if osk { + self.unmask_in(); + self.theme_osk(Rect::new(10.0, 52.0, 320.0, 129.0)); + } + } + } +} diff --git a/rust/satlim-plugin/src/gui/ui/scope.rs b/rust/satlim-plugin/src/gui/ui/scope.rs new file mode 100644 index 0000000..06590c2 --- /dev/null +++ b/rust/satlim-plugin/src/gui/ui/scope.rs @@ -0,0 +1,299 @@ +//! Waveform scope ("transient meter"): half or full wave peak display of the output in the UI colour, with what the +//! clipper and limiter removed stacked on top in the accent colour. + +use super::*; + +const SRC: [&str; 3] = ["OUT+GR", "OUT", "GR"]; +const WAVE: [&str; 2] = ["HALF", "FULL"]; +/// time window steps (seconds) and their labels +const WIN_S: [f32; 10] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0]; +const WIN_L: [&str; 10] = ["250ms", "0.5s", "0.75s", "1s", "1.5s", "2s", "3s", "4s", "6s", "8s"]; +/// ceiling steps: +10 dB (this plug-in is meant to clip heavily, so there is room to watch what the clipper does above 0 dBFS) +/// down to -14 dB; the default step is +2 dB +const CEIL_N: usize = 25; + +fn ceil_db(i: usize) -> i32 { + 10 - i as i32 +} + +/// (output peak, peak the limiter was handed, peak before the clipper) of absolute column `j` on a grid of `k` buckets per column, +/// read from a ring whose newest bucket index is `head - 1`. Pure in (ring contents, j, k): once a column is complete it never +/// changes. +fn scope_col(ring: &satcomp_dsp::ScopeRing, head: usize, j: i64, k: f64) -> (f32, f32, f32) { + let len = satcomp_dsp::ScopeRing::LEN as i64; + let b0 = j as f64 * k; + let i0 = b0.floor() as i64; + let i1 = ((b0 + k).floor() as i64).max(i0 + 1); + let (mut o, mut m, mut p) = (0.0f32, 0.0f32, 0.0f32); + for i in i0..i1 { + if i < 0 || head as i64 - i >= len { + continue; + } + let (a, b, c) = ring.get3(i as usize); + o = o.max(a); + m = m.max(b); + p = p.max(c); + } + let m = m.max(o); + (o, m, p.max(m)) +} + +fn fmt_db(db: i32) -> String { + if db > 0 { format!("+{db}dB") } else { format!("{db}dB") } +} + +// Packed settings (params.scope, default (5 << 4) | (8 << 8) = 2 s window, +2 dB ceiling): bit 0 on, bits 1-2 source, +// bit 3 full wave, bits 4-7 window step, bits 8-12 ceiling step (ceil_db). + +impl<'a> Gui<'a> { + fn sc_get(&self, shift: u32, bits: i32) -> usize { + ((self.scope_cfg >> shift) & bits) as usize + } + + fn sc_set(&mut self, shift: u32, bits: i32, v: usize) { + self.scope_cfg = (self.scope_cfg & !(bits << shift)) | ((v as i32 & bits) << shift); + self.env.params.scope.store(self.scope_cfg, Ordering::Relaxed); + } + + pub(super) fn draw_scope(&mut self, x: f32, y: f32, w: f32, h: f32) { + let (src, full) = (self.sc_get(1, 3).min(2), self.sc_get(3, 1) == 1); + let (win, ceil) = (self.sc_get(4, 15).min(WIN_S.len() - 1), self.sc_get(8, 31).min(CEIL_N - 1)); + // viewport drag (relative): x steps through the window, y moves the ceiling (down = lower ceiling = zoomed in) + if self.hit(x, y, w, h) && self.press && self.act == 0 { + self.act = 144; + self.vt1 = 0; + self.vt2 = 0; + self.scope_drag = (self.mx, self.my, win, ceil); + self.press = false; + } + let dragging = self.act == 144; + if dragging && self.down { + let (sx, sy, w0, c0) = self.scope_drag; + let nw = (w0 as f32 + (self.mx - sx) / w * (WIN_S.len() - 1) as f32).round().clamp(0.0, (WIN_S.len() - 1) as f32); + let nc = (c0 as f32 + (self.my - sy) / h * (CEIL_N - 1) as f32).round().clamp(0.0, (CEIL_N - 1) as f32); + self.sc_set(4, 15, nw as usize); + self.sc_set(8, 31, nc as usize); + } + let (win, ceil) = (self.sc_get(4, 15).min(WIN_S.len() - 1), self.sc_get(8, 31).min(CEIL_N - 1)); + let zoom = 10f32.powf(-ceil_db(ceil) as f32 / 20.0); // 1 / ceiling amplitude + self.setc(false); + self.cv.boxr(x, y, w, h); + let ring = self.env.shared.scope.clone(); + let head = ring.head(); + let ncol = (w - 2.0) as usize; + let k = WIN_S[win] as f64 / satcomp_dsp::ScopeRing::BUCKET_S / ncol as f64; // buckets per column (fractional) + let len = satcomp_dsp::ScopeRing::LEN as i64; + // Steady scrolling: the audio thread delivers buckets in host-block chunks, and a column grouped relative to the newest + // bucket changes every frame. So (1) the read position eases toward the head instead of jumping with each chunk, and + // (2) columns sit on a fixed grid in absolute bucket time and only complete ones are drawn: a column's content never + // changes once it exists, the picture just advances. + let target = head as f64 - 4.0; + let dt = (self.now - self.scope_t).clamp(0.0, 0.25); + self.scope_t = self.now; + if self.scope_pos <= 0.0 || (target - self.scope_pos).abs() > 4000.0 { + self.scope_pos = target; + } else { + self.scope_pos += (target - self.scope_pos) * (1.0 - (-dt * 10.0).exp()); + } + let last = (self.scope_pos / k).floor() as i64 - 1; // newest complete column + let mut cols = vec![(0.0f32, 0.0f32, 0.0f32); ncol]; + for (c, col) in cols.iter_mut().enumerate() { + *col = scope_col(&ring, head, last - (ncol - 1 - c) as i64, k); + } + let span = if full { ((h - 2.0) * 0.5).floor() } else { h - 2.0 }; + let hpx = |v: f32| ((v * zoom).min(1.0) * span).floor(); + let base = if full { y + (h * 0.5).floor() } else { y + h - 1.0 }; + let solid = self.env.params.fft_solid.load(Ordering::Relaxed); + // Heights of the layers per column, bottom to top: output (UI colour), then what the limiter removed (solid accent), then + // what the clipper removed (hatched accent: every other column), stacked up to the pre-clip peak. They add up, so it does + // not matter which of the two is larger. SRC GR shows the two removals alone from the baseline. + let layers = |&(o, m, p): &(f32, f32, f32)| -> (f32, f32, f32) { + if src == 0 { + (hpx(o), hpx(m), hpx(p)) + } else { + let l1 = hpx(m - o); + (0.0, l1, l1 + hpx(p - m)) + } + }; + if solid { + if src < 2 { + self.setc(false); + for (c, &(o, _, _)) in cols.iter().enumerate() { + let ho = hpx(o); + if ho > 0.0 { + let cx = x + 1.0 + c as f32; + if full { + self.cv.fill(cx, base - ho, 1.0, 2.0 * ho + 1.0); + } else { + self.cv.fill(cx, base - ho, 1.0, ho + 1.0); + } + } + } + } + if src != 1 { + self.setc(true); + for (c, col) in cols.iter().enumerate() { + let cx = x + 1.0 + c as f32; + let (l0, l1, c1) = layers(col); + let mut seg = |lo: f32, hi: f32| { + if hi > lo { + if full { + self.cv.fill(cx, base - hi, 1.0, hi - lo); + self.cv.fill(cx, base + lo + 1.0, 1.0, hi - lo); + } else { + self.cv.fill(cx, base - hi, 1.0, hi - lo); + } + } + }; + seg(l0, l1); + if c % 2 == 0 { + seg(l1, c1); + } + } + } + } else { + // outline: a 1 px stroke along each layer's top, joined to the previous column so steep edges stay connected: the + // output in the UI colour, the limiter's removal as an accent stroke, the clipper's as a dotted accent stroke + let stroke = |s: &mut Self, accent: bool, tops: &[Option], mirror: bool| { + s.setc(accent); + let mut prev: Option = None; + for (c, t) in tops.iter().enumerate() { + let cx = x + 1.0 + c as f32; + if let Some(t) = *t { + let p = prev.unwrap_or(t); + let (lo, hi) = (t.min(p), t.max(p)); + s.cv.fill(cx, base - hi, 1.0, hi - lo + 1.0); + if mirror { + s.cv.fill(cx, base + lo, 1.0, hi - lo + 1.0); + } + } + prev = *t; + } + }; + if src < 2 { + let tops: Vec> = cols.iter().map(|&(o, _, _)| Some(hpx(o))).collect(); + stroke(self, false, &tops, full); + } + if src != 1 { + let lim: Vec> = cols.iter().map(|col| { let (l0, l1, _) = layers(col); if l1 > l0 { Some(l1) } else { None } }).collect(); + stroke(self, true, &lim, full); + let clip: Vec> = cols.iter().enumerate().map(|(c, col)| { let (_, l1, c1) = layers(col); if c1 > l1 && c % 2 == 0 { Some(c1) } else { None } }).collect(); + stroke(self, true, &clip, full); + } + } + self.setc(false); + if full { + self.cv.fill(x + 1.0, base, 1.0, 1.0); // centre tick + } + if zoom < 0.999 { + // ceiling above 0 dBFS: a faint UI-colour line marks 0 dBFS (the ceiling of a normal signal); anything above it + // is an overshoot + let off = (zoom * span).floor(); + let keep = self.dk; + self.set_dk(keep * 0.35); + self.setc(false); + self.cv.fill(x + 1.0, base - off, w - 2.0, 1.0); + if full { + self.cv.fill(x + 1.0, base + off, w - 2.0, 1.0); + } + self.set_dk(keep); + self.setc(false); + } + if dragging { + let t = format!("WIN {} CEIL {}", WIN_L[win], fmt_db(ceil_db(ceil))); + let tw = self.cv.text_w(&t); + self.cv.setbg(); + self.cv.fill(x + 4.0, y + 4.0, tw + 8.0, 13.0); + self.setc(false); + self.cv.boxr(x + 4.0, y + 4.0, tw + 8.0, 13.0); + self.cv.set_font(1); + self.cv.text(x + 8.0, y + 8.0, &t); + } + } + + /// Settings under the scope: source and wave type cycle on click; window and ceiling are drag sliders (stepped). + pub(super) fn scope_row(&mut self, x: f32, y: f32, w_all: f32) { + let h = 17.0; + let ceil_w = w_all - 74.0 - 64.0 - 62.0 + 3.0; + let mut cx = x; + // SRC and WAVE: click / wheel cycles + for (lbl, names, shift, bits, w) in [("SRC", &SRC[..], 1u32, 3i32, 74.0f32), ("WAVE", &WAVE[..], 3, 1, 64.0)] { + let n = names.len(); + let cur = self.sc_get(shift, bits).min(n - 1); + if self.hit(cx, y, w, h) { + if self.press && self.act == 0 { + self.sc_set(shift, bits, (cur + 1) % n); + self.press = false; + } else if self.wheel != 0 { + let nx = (cur as i32 + if self.wheel > 0 { 1 } else { -1 }).clamp(0, n as i32 - 1) as usize; + self.sc_set(shift, bits, nx); + } + } + self.setc(false); + self.cv.boxr(cx, y, w, h); + self.cv.set_font(1); + self.cv.text(cx + 4.0, y + 5.0, lbl); + self.cv.textr(cx, y + 5.0, w - 4.0, names[cur]); + cx += w - 1.0; + } + // WIN and CEIL: horizontal drag sliders over their cell, stepped + for (k, lbl, shift, bits, n, w) in [(0usize, "WIN", 4u32, 15i32, WIN_S.len(), 62.0f32), (1, "CEIL", 8, 31, CEIL_N, ceil_w)] { + let act = 142 + k as i32; + let cur = self.sc_get(shift, bits).min(n - 1); + if self.hit(cx, y, w, h) { + if self.press && self.act == 0 { + self.act = act; + self.vt1 = 0; + self.vt2 = 0; + self.press = false; + } else if self.wheel != 0 { + let nx = (cur as i32 + if self.wheel > 0 { -1 } else { 1 }).clamp(0, n as i32 - 1) as usize; + self.sc_set(shift, bits, nx); + } + } + if self.act == act && self.down { + let f = ((self.mx - cx - 2.0) / (w - 4.0)).clamp(0.0, 1.0); + self.sc_set(shift, bits, (f * (n - 1) as f32 + 0.5).floor() as usize); + } + let cur = self.sc_get(shift, bits).min(n - 1); + self.setc(self.act == act); + self.cv.boxr(cx, y, w, h); + self.cv.set_font(1); + self.cv.text(cx + 4.0, y + 5.0, lbl); + let val = if k == 0 { WIN_L[cur].to_string() } else { fmt_db(ceil_db(cur)) }; + self.cv.textr(cx, y + 5.0, w - 4.0, &val); + let t = cur as f32 / (n - 1) as f32; + self.cv.fill(cx + 2.0, y + h - 3.0, ((t * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(false); + cx += w - 1.0; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_complete_column_does_not_change_as_new_buckets_arrive() { + let ring = satcomp_dsp::ScopeRing::new(); + let val = |i: usize| 0.2 + 0.3 * ((i as f32 * 0.37).sin().abs()); + for i in 0..2000 { + ring.push(val(i), val(i) * 1.5); + } + // k = 3.7 buckets per column (a fractional window), the same columns read at three different heads + let k = 3.7; + let head0 = ring.head(); + let before: Vec<_> = (400..420).map(|j| scope_col(&ring, head0, j, k)).collect(); + for i in 2000..2013 { + ring.push(val(i), val(i) * 1.5); + } + let after: Vec<_> = (400..420).map(|j| scope_col(&ring, ring.head(), j, k)).collect(); + assert_eq!(before, after); + // and a column reads the maximum of the buckets it spans + let (o, _, _) = scope_col(&ring, ring.head(), 500, k); + // column 500 spans buckets [1850, floor(1853.7)) = 1850..1853 + let want = (1850..1853).map(val).fold(0.0f32, f32::max); + assert!((o - want).abs() < 1e-6, "{o} vs {want}"); + } +} diff --git a/rust/satlim-plugin/src/lib.rs b/rust/satlim-plugin/src/lib.rs new file mode 100644 index 0000000..6bae143 --- /dev/null +++ b/rust/satlim-plugin/src/lib.rs @@ -0,0 +1,255 @@ +//! SatLim: the SatComp saturator into an oversampled clipper and a true-peak brickwall limiter. nih-plug shell around +//! `satlim_dsp::LimEngine`. + +mod gui; +mod params; +#[allow(dead_code)] // used by the editor +mod presets; + +use nih_plug::prelude::*; +use params::SatLimParams; +use satcomp_dsp::shapers::Curve; +use satcomp_dsp::ScopeRing; +use satlim_dsp::LimEngine; +use std::num::NonZeroU32; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Instant; + +/// State shared between the audio thread and the editor (all lock-free). +pub struct Shared { + /// per 2 ms bucket: output peak and the same with what the clipper + limiter removed added back + pub scope: Arc, + pub epoch: Instant, + pub sample_rate: AtomicF32, + // audio -> UI. Peaks accumulate with fetch_max and are consumed with swap(0). + pub opk: [AtomicF32; 2], + /// output true peak (also while the lookahead is off), linear + pub tpk: AtomicF32, + pub clip: AtomicBool, + /// limiter gain reduction, dB positive + pub gr_pk: AtomicF32, + /// what the clipper took off, dB positive, accumulated like `gr_pk` + pub clip_gr_pk: AtomicF32, + /// post-saturator peak (after SAT GAIN), linear + pub sat_pk: AtomicF32, + /// decaying peak of the saturator input (live dot on the plot) + pub sat_vz: AtomicF32, + /// smoothed output mean-square (RMS readout) + pub fms: AtomicF32, + /// loudness change across the saturator (before SAT GAIN), dB + pub sat_db: AtomicF32, + /// sat level match: measuring (audio -> UI), progress seconds, finished result (set once, UI writes SAT GAIN) + pub sat_meas: AtomicBool, + pub sat_mt: AtomicF32, + pub sat_result: AtomicF32, + pub sat_result_new: AtomicBool, + // UI -> audio + pub delta_on: AtomicBool, + pub sat_req: AtomicBool, +} + +impl Shared { + pub fn new() -> Self { + Self { + scope: Arc::new(ScopeRing::new()), + epoch: Instant::now(), + sample_rate: AtomicF32::new(48000.0), + opk: [AtomicF32::new(0.0), AtomicF32::new(0.0)], + tpk: AtomicF32::new(0.0), + clip: AtomicBool::new(false), + gr_pk: AtomicF32::new(0.0), + clip_gr_pk: AtomicF32::new(0.0), + sat_pk: AtomicF32::new(0.0), + sat_vz: AtomicF32::new(0.0), + fms: AtomicF32::new(1e-9), + sat_db: AtomicF32::new(0.0), + sat_meas: AtomicBool::new(false), + sat_mt: AtomicF32::new(0.0), + sat_result: AtomicF32::new(0.0), + sat_result_new: AtomicBool::new(false), + delta_on: AtomicBool::new(false), + sat_req: AtomicBool::new(false), + } + } +} + +impl Default for Shared { + fn default() -> Self { + Self::new() + } +} + +pub struct SatLim { + params: Arc, + shared: Arc, + engine: LimEngine, + last_latency: u32, + last_curve: Curve, + last_asym: [f64; satcomp_dsp::shapers::SHAPER_COUNT], +} + +impl SatLim { + fn new_engine(&self, sr: f64) -> LimEngine { + let mut e = LimEngine::new(sr); + e.scope = self.shared.scope.clone(); + e + } +} + +impl Default for SatLim { + fn default() -> Self { + let shared = Arc::new(Shared::new()); + let mut engine = LimEngine::new(48000.0); + engine.scope = shared.scope.clone(); + Self { + params: Arc::new(SatLimParams::default()), + shared, + engine, + last_latency: u32::MAX, + last_curve: Curve::linear(), + last_asym: [100.0; satcomp_dsp::shapers::SHAPER_COUNT], + } + } +} + +impl Plugin for SatLim { + const NAME: &'static str = "SatLim"; + const VENDOR: &'static str = "thomchantra"; + 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() + }]; + + type SysExMessage = (); + type BackgroundTask = (); + + fn params(&self) -> Arc { + self.params.clone() + } + + fn editor(&mut self, _async_executor: AsyncExecutor) -> Option> { + gui::create(self.params.clone(), self.shared.clone()) + } + + fn initialize(&mut self, _layout: &AudioIOLayout, buffer_config: &BufferConfig, context: &mut impl InitContext) -> bool { + let sr = buffer_config.sample_rate as f64; + self.shared.sample_rate.store(sr as f32, Ordering::Relaxed); + let mut engine = self.new_engine(sr); + engine.set_params(&self.params.to_dsp()); + self.engine = engine; + self.last_latency = self.engine.latency(); + context.set_latency_samples(self.last_latency); + true + } + + fn reset(&mut self) { + let sr = self.engine.sample_rate(); + let mut engine = self.new_engine(sr); + engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve, &mut self.last_asym)); + self.engine = engine; + } + + fn process(&mut self, buffer: &mut Buffer, _aux: &mut AuxiliaryBuffers, context: &mut impl ProcessContext) -> ProcessStatus { + let sh = &self.shared; + self.engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve, &mut self.last_asym)); + let lat = self.engine.latency(); + if lat != self.last_latency { + self.last_latency = lat; + context.set_latency_samples(lat); + } + self.engine.delta_on = sh.delta_on.load(Ordering::Relaxed); + if sh.sat_req.swap(false, Ordering::Relaxed) { + self.engine.request_sat_match(); + } + if let [l, r] = buffer.as_slice() { + self.engine.process(l, r); + } + let e = &mut self.engine; + sh.opk[0].fetch_max(e.opk[0] as f32, Ordering::Relaxed); + sh.opk[1].fetch_max(e.opk[1] as f32, Ordering::Relaxed); + e.opk = [0.0; 2]; + sh.tpk.fetch_max(e.tpk as f32, Ordering::Relaxed); + e.tpk = 0.0; + if e.clip_f { + sh.clip.store(true, Ordering::Relaxed); + e.clip_f = false; + } + sh.gr_pk.fetch_max(e.gr_pk as f32, Ordering::Relaxed); + e.gr_pk = 0.0; + sh.clip_gr_pk.fetch_max(e.clip_gr_pk as f32, Ordering::Relaxed); + e.clip_gr_pk = 0.0; + sh.sat_pk.fetch_max(e.sat_out as f32, Ordering::Relaxed); + e.sat_out = 0.0; + sh.sat_vz.store(e.sat_vz as f32, Ordering::Relaxed); + sh.fms.store(e.fms as f32, Ordering::Relaxed); + sh.sat_db.store(e.sat_db as f32, Ordering::Relaxed); + sh.sat_meas.store(e.sat_matching(), Ordering::Relaxed); + sh.sat_mt.store(e.sat_match_progress() as f32, Ordering::Relaxed); + if let Some(v) = e.take_sat_result() { + sh.sat_result.store(v as f32, Ordering::Relaxed); + sh.sat_result_new.store(true, Ordering::Release); + } + ProcessStatus::Normal + } +} + +impl Vst3Plugin for SatLim { + // 16 bytes, must stay stable forever once released (plug-in identity). + const VST3_CLASS_ID: [u8; 16] = *b"thomchantraSatLm"; + const VST3_SUBCATEGORIES: &'static [Vst3SubCategory] = &[Vst3SubCategory::Fx, Vst3SubCategory::Dynamics, Vst3SubCategory::Distortion]; +} + +impl ClapPlugin for SatLim { + const CLAP_ID: &'static str = "com.thomchantra.satlim"; + const CLAP_DESCRIPTION: Option<&'static str> = Some("Saturator into a clipper and a true-peak limiter"); + const CLAP_MANUAL_URL: Option<&'static str> = None; + const CLAP_SUPPORT_URL: Option<&'static str> = None; + const CLAP_FEATURES: &'static [ClapFeature] = &[ClapFeature::AudioEffect, ClapFeature::Limiter, ClapFeature::Distortion, ClapFeature::Stereo]; +} + +nih_export_vst3!(SatLim); +nih_export_clap!(SatLim); + +#[cfg(test)] +mod tests { + use super::*; + use satlim_dsp::LimParams; + + #[test] + fn generated_defaults_match_engine_defaults() { + let p = SatLimParams::default(); + // plug-in parameters are f32, the engine's are f64: compare the way the plug-in stores them + let want = LimParams { ceiling: -0.3f32 as f64, ..LimParams::default() }; + assert_eq!(p.to_dsp(), want); + } + + #[test] + fn every_table_slot_resolves_and_is_unique() { + let p = SatLimParams::default(); + let mut seen = std::collections::HashSet::new(); + for &(n, id, mn, mx, df) in params::TABLE { + assert!(n < params::SLOTS, "{id}"); + assert!(seen.insert(n), "slot {n} used twice"); + assert!(p.ptr(n).is_some(), "{id}"); + assert!(mn < mx && df >= mn && df <= mx, "{id} range"); + } + } + + #[test] + fn ids_are_unique_and_identity_is_thomchantra() { + let mut ids = std::collections::HashSet::new(); + for &(_, id, ..) in params::TABLE { + assert!(ids.insert(id), "{id}"); + } + assert_eq!(::VST3_CLASS_ID.len(), 16); + assert!(::CLAP_ID.starts_with("com.thomchantra.")); + // distinct from the other plug-ins' identities + assert_ne!(&::VST3_CLASS_ID, b"thomchantraSatXC"); + } +} diff --git a/rust/satlim-plugin/src/params.rs b/rust/satlim-plugin/src/params.rs new file mode 100644 index 0000000..7025250 --- /dev/null +++ b/rust/satlim-plugin/src/params.rs @@ -0,0 +1,201 @@ +// GENERATED by tools/gen_lparams.py. Do not edit by hand. + +use nih_plug::prelude::*; +use nih_plug_egui::EguiState; +use satcomp_dsp::shapers::{asym_from, Curve, SHAPER_COUNT}; +use satlim_dsp::LimParams; +use std::sync::atomic::{AtomicBool, AtomicI32}; +use std::sync::Arc; + +/// Highest UI slot number + 1. +pub const SLOTS: usize = 28; + +/// (slot number, id, min, max, default) for every parameter. +pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[ + (1, "shape", 0.0, 14.0, 0.0), + (2, "drive", 0.0, 100.0, 0.0), + (3, "bias", -100.0, 100.0, 0.0), + (4, "sat_hp", 20.0, 2000.0, 20.0), + (5, "sat_lp", 200.0, 20000.0, 20000.0), + (6, "tone", 1000.0, 20000.0, 20000.0), + (7, "os", 0.0, 3.0, 0.0), + (25, "sat_mix", 0.0, 100.0, 100.0), + (27, "sat_gain", -24.0, 12.0, 0.0), + (12, "lookahead", 0.0, 1.0, 1.0), + (8, "ceiling", -24.0, 0.0, -0.3), + (9, "threshold", -30.0, 0.0, 0.0), + (10, "release", 15.0, 80.0, 80.0), + (11, "clip", 0.0, 100.0, 0.0), + (22, "out_gain", -24.0, 12.0, 0.0), + (26, "bypass", 0.0, 1.0, 0.0), +]; + +#[derive(Params)] +pub struct SatLimParams { + #[persist = "editor-state"] + pub editor_state: Arc, + /// Colour scheme index in the palette table (-1 = not set yet); UI-only, saved with the project. + #[persist = "palette-v2"] + pub palette_v2: Arc, + /// Light mode (the inverted palette of the scheme); UI-only, saved with the project. + #[persist = "light-mode"] + pub light: Arc, + /// Scope fill: true = solid UI-colour bars, false = outline stroke along the peaks; UI-only. + #[persist = "fft-solid"] + pub fft_solid: Arc, + /// UI font index (see `satcomp_ui::canvas::FONT_NAMES`); UI-only, saved with the project. + #[persist = "ui-font"] + pub font: Arc, + /// Active user colour theme (`name|` + 18 hex digits) so a project keeps its look on a machine without the themes file. + #[persist = "custom-theme"] + pub custom_theme: Arc>, + /// Packed scope view settings (see gui/ui/scope.rs); UI-only, saved with the project. + #[persist = "scope-v3"] + pub scope: Arc, + /// Name of the last loaded/saved preset (display only). + #[persist = "preset-name"] + pub preset_name: Arc>, + /// User-drawn waveshaper curve (points on [-1,1]^2, shaper 14 "Custom"); saved with the project and presets. + #[persist = "custom-curve"] + pub custom_curve: Arc>>, + /// ASYM per waveshaper (0..100 %, index = shaper); saved with the project and presets (absent = all 100 %). + #[persist = "asym"] + pub asym: Arc>>, + #[id = "shape"] + pub shape: IntParam, + #[id = "drive"] + pub drive: FloatParam, + #[id = "bias"] + pub bias: FloatParam, + #[id = "sat_hp"] + pub sat_hp: FloatParam, + #[id = "sat_lp"] + pub sat_lp: FloatParam, + #[id = "tone"] + pub tone: FloatParam, + #[id = "os"] + pub os: IntParam, + #[id = "sat_mix"] + pub sat_mix: FloatParam, + #[id = "sat_gain"] + pub sat_gain: FloatParam, + #[id = "lookahead"] + pub lookahead: BoolParam, + #[id = "ceiling"] + pub ceiling: FloatParam, + #[id = "threshold"] + pub threshold: FloatParam, + #[id = "release"] + pub release: FloatParam, + #[id = "clip"] + pub clip: FloatParam, + #[id = "out_gain"] + pub out_gain: FloatParam, + #[id = "bypass"] + pub bypass: BoolParam, +} + +impl Default for SatLimParams { + /// A new instance starts from the shared defaults file (the host then restores a saved project's own look over this). + fn default() -> Self { + Self::from_defaults(satcomp_ui::appearance::load_defaults_for("satlim")) + } +} + +impl SatLimParams { + pub fn from_defaults(d: Option) -> Self { + Self { + editor_state: { + let (w, h) = d.as_ref().map(|d| d.size((340.0, 504.0))).unwrap_or((340, 504)); + EguiState::from_size(w, h) + }, + palette_v2: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.pal_index()).unwrap_or(-1))), + light: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.light).unwrap_or(false))), + font: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.face_index()).unwrap_or(0))), + fft_solid: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.fill_solid).unwrap_or(true))), + scope: Arc::new(AtomicI32::new((5 << 4) | (8 << 8))), + custom_theme: Arc::new(parking_lot::Mutex::new(d.as_ref().map(|d| d.theme.clone()).unwrap_or_default())), + preset_name: Arc::new(parking_lot::Mutex::new(String::new())), + custom_curve: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])), + asym: Arc::new(parking_lot::Mutex::new(Vec::new())), + shape: IntParam::new("Shape", 0, IntRange::Linear { min: 0, max: 14 }), + drive: FloatParam::new("Drive", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + bias: FloatParam::new("Bias", 0.0, FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + sat_hp: FloatParam::new("Sat HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + sat_lp: FloatParam::new("Sat LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + tone: FloatParam::new("Tone", 20000.0, FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + os: IntParam::new("Oversampling", 0, IntRange::Linear { min: 0, max: 3 }), + sat_mix: FloatParam::new("Sat Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + sat_gain: FloatParam::new("Sat Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + lookahead: BoolParam::new("Lookahead", true), + ceiling: FloatParam::new("Ceiling", -0.3, FloatRange::Linear { min: -24.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + threshold: FloatParam::new("Threshold", 0.0, FloatRange::Linear { min: -30.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + release: FloatParam::new("Release", 80.0, FloatRange::Linear { min: 15.0, max: 80.0 }).with_unit(" ms").with_step_size(1.0), + clip: FloatParam::new("Clip", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + out_gain: FloatParam::new("Out Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + bypass: BoolParam::new("Bypass", false), + } + } +} + +impl SatLimParams { + /// Sanitised copy of the persisted custom curve (the UI holds this lock only for a point edit). + pub fn curve_snapshot(&self) -> Curve { + Curve::from_points(&self.custom_curve.lock()) + } + + /// ASYM per shaper, sanitised (short / missing = 100 %). + pub fn asym_snapshot(&self) -> [f64; SHAPER_COUNT] { + asym_from(&self.asym.lock()) + } + + /// Snapshot for the DSP engine (UI side: may wait briefly for the curve lock). + pub fn to_dsp(&self) -> LimParams { + self.to_dsp_with(self.curve_snapshot(), self.asym_snapshot()) + } + + /// Audio-thread snapshot: never blocks on the curve lock. While the UI holds it the previous curve is reused. + pub fn to_dsp_rt(&self, last: &mut Curve, last_asym: &mut [f64; SHAPER_COUNT]) -> LimParams { + if let Some(g) = self.custom_curve.try_lock() { + *last = Curve::from_points(&g); + } + if let Some(g) = self.asym.try_lock() { + *last_asym = asym_from(&g); + } + self.to_dsp_with(*last, *last_asym) + } + + fn to_dsp_with(&self, curve: Curve, asym: [f64; SHAPER_COUNT]) -> LimParams { + LimParams { + shape: self.shape.value(), curve, asym, drive: self.drive.value() as f64, bias: self.bias.value() as f64, + sat_hp: self.sat_hp.value() as f64, sat_lp: self.sat_lp.value() as f64, tone: self.tone.value() as f64, + sat_mix: self.sat_mix.value() as f64, sat_gain: self.sat_gain.value() as f64, os: self.os.value(), + lookahead: self.lookahead.value(), ceiling: self.ceiling.value() as f64, threshold: self.threshold.value() as f64, + release: self.release.value() as f64, clip: self.clip.value() as f64, out_gain: self.out_gain.value() as f64, + bypass: self.bypass.value(), + } + } + + /// Parameter by slot number (UI addressing). + pub fn ptr(&self, n: usize) -> Option { + Some(match n { + 1 => self.shape.as_ptr(), + 2 => self.drive.as_ptr(), + 3 => self.bias.as_ptr(), + 4 => self.sat_hp.as_ptr(), + 5 => self.sat_lp.as_ptr(), + 6 => self.tone.as_ptr(), + 7 => self.os.as_ptr(), + 25 => self.sat_mix.as_ptr(), + 27 => self.sat_gain.as_ptr(), + 12 => self.lookahead.as_ptr(), + 8 => self.ceiling.as_ptr(), + 9 => self.threshold.as_ptr(), + 10 => self.release.as_ptr(), + 11 => self.clip.as_ptr(), + 22 => self.out_gain.as_ptr(), + 26 => self.bypass.as_ptr(), + _ => return None, + }) + } +} diff --git a/rust/satlim-plugin/src/presets.rs b/rust/satlim-plugin/src/presets.rs new file mode 100644 index 0000000..1fb8067 --- /dev/null +++ b/rust/satlim-plugin/src/presets.rs @@ -0,0 +1,202 @@ +//! Presets: JSON files of parameter values keyed by parameter id. +//! Factory bank = every `presets/*.json` embedded at build time (+ built-in INIT). +//! User presets = `*.satlim` files; the dropdown lists the user folder, "Load preset..." opens any file. + +use crate::params::TABLE; +use include_dir::{include_dir, Dir}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +static FACTORY_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/presets"); + +pub const EXT: &str = "satlim"; +/// Never stored in a preset: Bypass is a performance switch. +pub const EXCLUDED: [&str; 1] = ["bypass"]; + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct Preset { + pub format: String, + pub version: u32, + pub name: String, + pub params: BTreeMap, + /// Custom waveshaper curve points (absent in older presets = linear). Backward compatible: version stays 1. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curve: Vec<(f32, f32)>, + /// ASYM (0..100 %) per waveshaper (absent / empty = all 100 %). Backward compatible: version stays 1. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asym: Vec, +} + +impl Preset { + pub fn new(name: &str, params: BTreeMap) -> Self { + Self { format: "satlim-preset".into(), version: 1, name: name.into(), params, curve: Vec::new(), asym: Vec::new() } + } + + /// All defaults. + pub fn init() -> Self { + let params = TABLE.iter().filter(|e| !EXCLUDED.contains(&e.1)).map(|e| (e.1.to_string(), e.4)).collect(); + Self::new("INIT", params) + } + + pub fn from_json(s: &str) -> Option { + let p: Preset = serde_json::from_str(s).ok()?; + (p.format == "satlim-preset").then_some(p) + } + + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).unwrap_or_default() + } +} + +pub fn factory() -> Vec { + let mut v = vec![Preset::init()]; + let mut files: Vec<_> = FACTORY_DIR + .files() + .filter(|f| f.path().extension().map(|e| e == "json").unwrap_or(false)) + .collect(); + files.sort_by_key(|f| f.path().to_path_buf()); + for f in files { + if let Some(mut p) = f.contents_utf8().and_then(Preset::from_json) { + if p.name.is_empty() { + p.name = f.path().file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + } + v.push(p); + } + } + v +} + +/// ~/Library/Application Support/SatLim/Presets (macOS), %APPDATA%\SatLim\Presets (Windows), ~/.config/SatLim/Presets +pub fn user_dir() -> Option { + #[cfg(target_os = "macos")] + let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support")); + #[cfg(windows)] + let base = std::env::var_os("APPDATA").map(PathBuf::from); + #[cfg(not(any(target_os = "macos", windows)))] + let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")); + base.map(|b| b.join("SatLim").join("Presets")) +} + +/// (display name, path) of the user presets, sorted case-insensitively. +pub fn scan_user() -> Vec<(String, PathBuf)> { + let mut v = Vec::new(); + // tests are hermetic: the machine's own user presets must not change what the editor lists (the UI golden steps through them) + if cfg!(test) { + return v; + } + if let Some(d) = user_dir() { + if let Ok(rd) = std::fs::read_dir(d) { + for e in rd.flatten() { + let p = e.path(); + if p.extension().map(|x| x == EXT).unwrap_or(false) { + if let Some(stem) = p.file_stem() { + v.push((stem.to_string_lossy().into_owned(), p)); + } + } + } + } + } + v.sort_by_key(|a| a.0.to_lowercase()); + v +} + +pub fn load_file(path: &Path) -> Option { + Preset::from_json(&std::fs::read_to_string(path).ok()?) +} + +pub fn save_file(path: &Path, p: &Preset) -> std::io::Result<()> { + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + std::fs::write(path, p.to_json()) +} + +#[cfg(any(target_os = "macos", windows))] +pub fn open_dialog() -> Option { + let mut d = rfd::FileDialog::new().add_filter("SatLim preset", &[EXT, "json"]).set_title("Load preset"); + if let Some(u) = user_dir().filter(|u| u.exists()) { + d = d.set_directory(u); + } + d.pick_file() +} + +#[cfg(any(target_os = "macos", windows))] +pub fn save_dialog(default_name: &str) -> Option { + let mut d = rfd::FileDialog::new() + .add_filter("SatLim preset", &[EXT]) + .set_title("Save preset") + .set_file_name(format!("{default_name}.{EXT}")); + if let Some(u) = user_dir() { + let _ = std::fs::create_dir_all(&u); + d = d.set_directory(u); + } + d.save_file().map(|p| if p.extension().is_none() { p.with_extension(EXT) } else { p }) +} + +#[cfg(not(any(target_os = "macos", windows)))] +pub fn open_dialog() -> Option { + None +} +#[cfg(not(any(target_os = "macos", windows)))] +pub fn save_dialog(_default_name: &str) -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn init_roundtrips_and_excludes_the_performance_switch() { + let p = Preset::init(); + assert!(!p.params.contains_key("bypass")); + assert_eq!(p.params["drive"], 0.0); + assert_eq!(p.params["lookahead"], 1.0); + assert_eq!(p.params["release"], 80.0); + let q = Preset::from_json(&p.to_json()).unwrap(); + assert_eq!(q.params, p.params); + assert!(Preset::from_json("{\"format\":\"nope\"}").is_none()); + assert!(Preset::from_json("{\"format\":\"satcomp-preset\",\"version\":1,\"name\":\"x\",\"params\":{}}").is_none()); + } + + #[test] + fn asym_and_curve_roundtrip_and_old_presets_load_without_them() { + let mut p = Preset::init(); + assert!(!p.to_json().contains("asym") && !p.to_json().contains("curve")); + p.asym = vec![100.0, 35.0]; + p.curve = vec![(-1.0, -1.0), (0.0, 0.3), (1.0, 1.0)]; + let q = Preset::from_json(&p.to_json()).unwrap(); + assert_eq!((q.asym.clone(), q.curve.clone()), (p.asym, p.curve)); + let old = r#"{"format":"satlim-preset","version":1,"name":"x","params":{}}"#; + let o = Preset::from_json(old).unwrap(); + assert!(o.asym.is_empty() && o.curve.is_empty()); + } + + #[test] + fn the_factory_bank_has_the_six_presets_and_every_value_is_in_range() { + let f = factory(); + for want in ["Baked", "Drums_Crunch", "Faulty Gate", "Master_Clean", "Master_Loud", "Peak Limiter"] { + assert!(f.iter().any(|p| p.name == want), "missing factory preset {want}"); + } + for p in &f { + for (k, v) in &p.params { + let e = TABLE.iter().find(|e| e.1 == k).unwrap(); + assert!(*v >= e.2 - 1e-3 && *v <= e.3 + 1e-3, "{}: {k} = {v} outside {}..{}", p.name, e.2, e.3); + } + } + let fg = f.iter().find(|p| p.name == "Faulty Gate").unwrap(); + assert_eq!(fg.curve.len(), 4, "Faulty Gate carries its custom curve"); + } + + #[test] + fn factory_starts_with_init_and_every_preset_uses_known_ids() { + let f = factory(); + assert_eq!(f[0].name, "INIT"); + for p in &f { + for k in p.params.keys() { + assert!(TABLE.iter().any(|e| e.1 == k), "{}: unknown id {k}", p.name); + } + } + } +} diff --git a/rust/satlim-plugin/src/standalone.rs b/rust/satlim-plugin/src/standalone.rs new file mode 100644 index 0000000..704f48b --- /dev/null +++ b/rust/satlim-plugin/src/standalone.rs @@ -0,0 +1,3 @@ +fn main() { + nih_plug::wrapper::standalone::nih_export_standalone::(); +} diff --git a/rust/satxcomp-dsp/Cargo.toml b/rust/satxcomp-dsp/Cargo.toml new file mode 100644 index 0000000..31d7355 --- /dev/null +++ b/rust/satxcomp-dsp/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "satxcomp-dsp" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +satcomp-dsp = { path = "../satcomp-dsp" } + +[dev-dependencies] +satcomp-dsp = { path = "../satcomp-dsp", features = ["tune"] } diff --git a/rust/satxcomp-dsp/examples/render.rs b/rust/satxcomp-dsp/examples/render.rs new file mode 100644 index 0000000..2ede780 --- /dev/null +++ b/rust/satxcomp-dsp/examples/render.rs @@ -0,0 +1,147 @@ +//! Offline renderer for limiter / engine comparisons: `render PRESET.kv IN.wav OUT.wav [lim=0|1] [out_gain=dB]`. +//! PRESET.kv is `id value` per line (a SatXComp preset flattened by a script). WAVs are 32-bit float stereo. + +use satxcomp_dsp::{XEngine, XParams}; +use std::fs; + +fn read_wav(path: &str) -> (u32, Vec, Vec) { + let b = fs::read(path).unwrap(); + let sr = u32::from_le_bytes(b[24..28].try_into().unwrap()); + let mut i = 12; + while i + 8 <= b.len() { + let sz = u32::from_le_bytes(b[i + 4..i + 8].try_into().unwrap()) as usize; + if &b[i..i + 4] == b"data" { + let d = &b[i + 8..i + 8 + sz]; + let f: Vec = d.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect(); + return (sr, f.iter().step_by(2).cloned().collect(), f.iter().skip(1).step_by(2).cloned().collect()); + } + i += 8 + sz + (sz & 1); + } + panic!("no data chunk"); +} + +fn write_wav(path: &str, sr: u32, l: &[f32], r: &[f32]) { + let n = l.len() * 8; + let mut o = Vec::with_capacity(44 + n); + o.extend(b"RIFF"); + o.extend(((36 + n) as u32).to_le_bytes()); + o.extend(b"WAVEfmt "); + o.extend(16u32.to_le_bytes()); + o.extend(3u16.to_le_bytes()); + o.extend(2u16.to_le_bytes()); + o.extend(sr.to_le_bytes()); + o.extend((sr * 8).to_le_bytes()); + o.extend(8u16.to_le_bytes()); + o.extend(32u16.to_le_bytes()); + o.extend(b"data"); + o.extend((n as u32).to_le_bytes()); + for i in 0..l.len() { + o.extend(l[i].to_le_bytes()); + o.extend(r[i].to_le_bytes()); + } + fs::write(path, o).unwrap(); +} + +fn apply(p: &mut XParams, id: &str, v: f64) { + let band = |p: &mut XParams, b: usize, f: &str| { + let q = &mut p.bands[b]; + match f { + "on" => q.on = v > 0.5, + "solo" => q.solo = v > 0.5, + "delta" => q.delta = v > 0.5, + "shape" => q.shape = v.round() as i32, + "drive" => q.drive = v, + "bias" => q.bias = v, + "tone" => q.tone = v, + "hp" => q.hp = v, + "lp" => q.lp = v, + "sat_mix" => q.sat_mix = v, + "sat_gain" => q.sat_gain = v, + "thresh" => q.thresh = v, + "ratio" => q.ratio = v, + "attack" => q.attack = v, + "release" => q.release = v, + "speed" => q.speed = v, + "knee" => q.knee = v, + "knee_shape" => q.knee_shape = v, + "detector" => q.detector = v, + "ff_fb" => q.ff_fb = v, + "gr_dist" => q.gr_dist = v, + "comp_mix" => q.comp_mix = v, + "comp_gain" => q.comp_gain = v, + _ => eprintln!("unknown band field {f}"), + } + }; + for (b, pre) in ["lo_", "mid_", "mh_", "hi_"].iter().enumerate() { + if let Some(f) = id.strip_prefix(pre) { + return band(p, b, f); + } + } + if let Some(rest) = id.strip_prefix("eq").and_then(|r| r.chars().next().filter(|c| c.is_ascii_digit()).map(|_| &id[2..])) { + let i = (rest.as_bytes()[0] - b'1') as usize; + let q = &mut p.eq.bands[i]; + match &rest[2..] { + "on" => q.on = v > 0.5, + "type" => q.ty = v.round() as i32, + "freq" => q.freq = v, + "q" => q.q = v, + "gain" => q.gain = v, + f => eprintln!("unknown eq field {f}"), + } + return; + } + match id { + "x1" => p.x1 = v, + "x2" => p.x2 = v, + "x3" => p.x3 = v, + "x1_slope" => p.x1_slope = v as i32, + "x2_slope" => p.x2_slope = v as i32, + "x3_slope" => p.x3_slope = v as i32, + "os" => p.os = v as i32, + "lookahead" => p.lookahead_ms = v, + "mix" => p.mix = v, + "out_gain" => p.out_gain = v, + "gain_match" => p.gain_match = v > 0.5, + "bypass" => p.bypass = v > 0.5, + "lim_on" => p.lim_on = v > 0.5, + "sc_on" => p.sc_on = v > 0.5, + "sc_gain" => p.sc_gain = v, + "sc_hp" => p.sc_hp = v, + "sc_lp" => p.sc_lp = v, + "sc_mix" => p.key_mix = v, + "eq_tilt" => p.eq.tilt = v, + "eq_pivot" => p.eq.pivot = v, + "eq_mix" => p.eq.mix = v, + "eq_gain" => p.eq.gain = v, + "eq_bypass" => p.eq.bypass = v > 0.5, + _ => eprintln!("unknown id {id}"), + } +} + +fn main() { + let a: Vec = std::env::args().collect(); + let mut p = XParams::default(); + for line in fs::read_to_string(&a[1]).unwrap().lines() { + let mut it = line.split_whitespace(); + if let (Some(k), Some(v)) = (it.next(), it.next()) { + apply(&mut p, k, v.parse().unwrap()); + } + } + for o in &a[4..] { + let (k, v) = o.split_once('=').unwrap(); + apply(&mut p, if k == "lim" { "lim_on" } else { k }, v.parse().unwrap()); + } + let (sr, mut l, mut r) = read_wav(&a[2]); + let mut e = XEngine::new(sr as f64); + e.set_params(&p); + let lat = e.latency() as usize; + let n = l.len(); + l.extend(std::iter::repeat(0.0).take(lat)); + r.extend(std::iter::repeat(0.0).take(lat)); + for (cl, cr) in l.chunks_mut(512).zip(r.chunks_mut(512)) { + e.process(cl, cr); + } + // drop the latency so the render lines up with the input + write_wav(&a[3], sr, &l[lat..lat + n], &r[lat..lat + n]); + eprintln!("rendered {n} samples, latency {lat}"); +} diff --git a/rust/satxcomp-dsp/src/confine.rs b/rust/satxcomp-dsp/src/confine.rs new file mode 100644 index 0000000..7a26c9f --- /dev/null +++ b/rust/satxcomp-dsp/src/confine.rs @@ -0,0 +1,118 @@ +//! Band-limits what a band's saturator added. +//! +//! The saturator's harmonics spill above and below the band it works on. Filtering the saturator's *added* content (shaped +//! minus clean) with the band's own crossover edges and slopes keeps them inside the band, while the clean signal goes +//! around the filter untouched, so the bands still sum flat and the crossover needs no second copy. The lowest band has no +//! low edge and the highest no high edge. + +use crate::xover::{fill, Kind, MAX_SEC}; +use satcomp_dsp::biquad::{bq, Coef, IDENTITY}; + +const N: usize = 2 * MAX_SEC; + +/// One edge: crossover frequency (Hz) and slope step (0..3 = 12 / 24 / 48 / 96 dB/oct). +pub type Edge = Option<(f64, usize)>; + +pub struct Confine { + cur: [Coef; N], + tgt: [Coef; N], + delta: [Coef; N], + st: [[[f64; 2]; 2]; N], + ramping: bool, +} + +impl Default for Confine { + fn default() -> Self { + Self::new() + } +} + +impl Confine { + pub fn new() -> Self { + Self { cur: [IDENTITY; N], tgt: [IDENTITY; N], delta: [[0.0; 5]; N], st: [[[0.0; 2]; 2]; N], ramping: false } + } + + /// `lo` = the band's low edge (high-pass), `hi` = its high edge (low-pass). Glides unless `snap`. + pub fn set(&mut self, lo: Edge, hi: Edge, sr: f64, snap: bool) { + match hi { + Some((f, s)) => fill(&mut self.tgt[..MAX_SEC], Kind::Lp, f, s, 2, sr), + None => self.tgt[..MAX_SEC].iter_mut().for_each(|c| *c = IDENTITY), + } + match lo { + Some((f, s)) => fill(&mut self.tgt[MAX_SEC..], Kind::Hp, f, s, 2, sr), + None => self.tgt[MAX_SEC..].iter_mut().for_each(|c| *c = IDENTITY), + } + if snap { + self.cur = self.tgt; + self.delta = [[0.0; 5]; N]; + self.ramping = false; + } + } + + /// Per host block: ramp the coefficients towards the targets over `n` samples. + pub fn begin_block(&mut self, n: usize) { + let rn = 1.0 / n.max(1) as f64; + let mut moving = false; + for f in 0..N { + let mut d = 0.0; + for i in 0..5 { + self.delta[f][i] = (self.tgt[f][i] - self.cur[f][i]) * rn; + d += (self.tgt[f][i] - self.cur[f][i]).abs(); + } + if d < 1e-12 { + self.cur[f] = self.tgt[f]; + self.delta[f] = [0.0; 5]; + } else { + moving = true; + } + } + self.ramping = moving; + } + + #[inline] + pub fn tick(&mut self, x: [f64; 2]) -> [f64; 2] { + if self.ramping { + for f in 0..N { + for i in 0..5 { + self.cur[f][i] += self.delta[f][i]; + } + } + } + let mut y = x; + for c in 0..2 { + for f in 0..N { + y[c] = bq(&mut self.st[f][c], &self.cur[f], y[c]); + } + } + y + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_edges_is_a_pass_through_and_edges_cut_outside_the_band() { + let sr = 48000.0; + let mag = |c: &mut Confine, f: f64| { + let mut peak = 0.0f64; + for i in 0..48000 { + let v = (2.0 * std::f64::consts::PI * f * i as f64 / sr).sin(); + let y = c.tick([v, v]); + if i > 24000 { + peak = peak.max(y[0].abs()); + } + } + peak + }; + let mut c = Confine::new(); + c.set(None, None, sr, true); + assert!((mag(&mut c, 1000.0) - 1.0).abs() < 1e-9); + let mut c = Confine::new(); + c.set(Some((300.0, 2)), Some((3000.0, 2)), sr, true); + let (mid, below, above) = (mag(&mut c, 1000.0), mag(&mut c, 40.0), mag(&mut c, 15000.0)); + assert!(mid > 0.95, "{mid}"); + assert!(below < 0.001 && above < 0.001, "{below} {above}"); + } +} diff --git a/rust/satxcomp-dsp/src/engine.rs b/rust/satxcomp-dsp/src/engine.rs new file mode 100644 index 0000000..39c1045 --- /dev/null +++ b/rust/satxcomp-dsp/src/engine.rs @@ -0,0 +1,1040 @@ +//! SatXComp signal path: LR4 4-way split -> per band [saturator -> compressor -> comp mix/gain] -> sum (solo / delta) -> +//! 5-band EQ (+ tilt, mix, gain) -> dry/wet mix -> out gain -> equal-loudness bypass. +//! Meters and match logic follow `satcomp_dsp::Engine`. + +use crate::params::{eq_kind, EqParams, XParams}; +use crate::strip::Strip; +use crate::xover::{Crossover4, NB}; +use satcomp_dsp::biquad::eq_coef; +use satcomp_dsp::delay::StereoDelay; +use satcomp_dsp::eq::{EqBank, EqSection}; +use satcomp_dsp::keyinput::KeyInput; +use satcomp_dsp::level::{ms_step, one_pole, Matcher, DB_AMP, DB_POW, LN10_20}; +use satcomp_dsp::Limiter; +use satcomp_dsp::{ScopeRing, TapRing, DENORM}; +use std::sync::Arc; + +const EQ_FILTERS: usize = 7; // 5 bands + tilt low shelf + tilt high shelf + +/// Sets the bank targets for the 5 bands and the tilt pair. Returns whether any filter does something. +fn eq_setup(bank: &mut EqBank, p: &EqParams, sr: f64) -> bool { + let mut any = false; + for b in 0..5 { + let bp = &p.bands[b]; + let coef = eq_coef(eq_kind(b, bp.ty), bp.freq.clamp(20.0, 20000.0), bp.gain.clamp(-18.0, 18.0), bp.q.clamp(0.1, 10.0), sr); + bank.target(b, Some(coef), bp.on); + any |= bp.on; + } + let t = p.tilt.clamp(-12.0, 12.0); + let pv = if p.pivot < 19.5 { 600.0 } else { p.pivot.min(20000.0) }; + let on = t != 0.0; + bank.target(5, if on { Some(eq_coef(2, pv, -t * 0.5, 0.4, sr)) } else { None }, on); + bank.target(6, if on { Some(eq_coef(3, pv, t * 0.5, 0.4, sr)) } else { None }, on); + any || on +} + +pub struct XEngine { + sr: f64, + sr_prev: f64, + p: XParams, + dirty: bool, + pub smoothing: bool, + snap: bool, + first_set: bool, + + xo: Crossover4, + /// the external key: conditioned globally, then split by its own copy of the crossover into one slice per band + key: KeyInput, + key_xo: Crossover4, + /// the host gave a sidechain bus this block + pub sc_avail: bool, + /// monitor the conditioned key instead of the output (UI toggle) + pub sc_solo: bool, + sc_s: f64, + pub strips: [Strip; NB], + eq: EqSection, + eq_mix: f64, + eq_mix_t: f64, + dw: StereoDelay<4096>, + lim: Limiter, + /// conditioned key delayed by the limiter latency (sidechain solo lines up with the limited path) + mon_s: StereoDelay<256>, + la_s: usize, + any_solo: bool, + d_s: [f64; NB], + solo_s: [f64; NB], + sm_c: f64, + + og: f64, + og_t: f64, + og_c: f64, + mix: f64, + mix_t: f64, + byp_s: f64, + byp_c: f64, + rmsg_c: f64, + fms_c: f64, + /// monitor what all compressors removed (UI toggle, not a stored parameter) + pub delta_on: bool, + gd_s: f64, + + pub ims: f64, + pub oms: f64, + pub pms: f64, + /// mean squares into / out of the EQ stage (its dry/wet mix and gain included) + eis: f64, + eos: f64, + /// level change across the EQ stage, dB (for the EQ IN>OUT readout) + pub eq_diff: f64, + pub diff_db: f64, + pub diff_disp: f64, + gate_open: bool, + match_on: bool, + prev_match_on: bool, + out_m: Matcher, + /// per band: the SAT GAIN level match (3 s measurement of the saturator's loudness change, then the gain that cancels it) + sat_m: [Matcher; NB], + sat_req: [bool; NB], + sat_result: [Option; NB], + /// per band: live loudness change across the saturator, dB (SAT GAIN not included) + pub sat_db: [f64; NB], + pub match_trim: f64, + match_req: bool, + + /// spectrum taps (mono): output signal, and the saturated signal before the compressors ("dry") + pub tap_out: Arc, + pub tap_dry: Arc, + pub tap_on: bool, + pub scope: Arc, + sc_o: f64, + sc_p: f64, + sc_n: u32, + sc_len: u32, + + pub opk: [f64; 2], + pub clip_f: bool, + /// per band: gain reduction (dB) of the current block / peak since the owner last cleared it + pub gr_blk: [f64; NB], + pub gr_pk: [f64; NB], + /// per band gain lift of the upward compressor (dB, >= 0), block value and the peak accumulated like `gr_pk` + pub gl_blk: [f64; NB], + pub gl_pk: [f64; NB], + /// per band: level change across the strip (output vs the band's input, dB; saturator gain and compression included) + pub band_diff: [f64; NB], + bi_ms: [f64; NB], + bo_ms: [f64; NB], + /// decaying peak of each band's saturator input (for the live marker on the transfer plot) + pub sat_vz: [f64; NB], + /// per band peak of the saturator output, accumulated until the plug-in wrapper takes it (like `gr_pk`) + pub sat_out: [f64; NB], + pub fms: f64, + /// Peak limiter gain reduction (dB, positive) since the shell last took it. + pub lim_gr_pk: f64, +} + +impl XEngine { + pub fn new(sr: f64) -> Self { + let mut e = Self { + sr, + sr_prev: 0.0, + p: XParams::default(), + dirty: true, + smoothing: true, + snap: true, + first_set: true, + xo: Crossover4::new(), + key: KeyInput::new(), + key_xo: Crossover4::new(), + sc_avail: false, + sc_solo: false, + sc_s: 0.0, + strips: [Strip::new(), Strip::new(), Strip::new(), Strip::new()], + eq: EqSection::default(), + eq_mix: 1.0, + eq_mix_t: 1.0, + dw: StereoDelay::new(), + lim: Limiter::new(sr), + mon_s: StereoDelay::new(), + la_s: 0, + any_solo: false, + d_s: [0.0; NB], + solo_s: [1.0; NB], + sm_c: 0.0, + og: 1.0, + og_t: 1.0, + og_c: 0.0, + mix: 1.0, + mix_t: 1.0, + byp_s: 0.0, + byp_c: 0.0, + rmsg_c: 0.0, + fms_c: 0.0, + delta_on: false, + gd_s: 0.0, + ims: 1e-9, + oms: 1e-9, + pms: 1e-9, + eis: 1e-9, + eos: 1e-9, + eq_diff: 0.0, + diff_db: 0.0, + diff_disp: 0.0, + gate_open: false, + match_on: false, + prev_match_on: false, + out_m: Matcher::default(), + sat_m: [Matcher::default(); NB], + sat_req: [false; NB], + sat_result: [None; NB], + sat_db: [0.0; NB], + match_trim: 0.0, + match_req: false, + tap_out: Arc::new(TapRing::new()), + tap_dry: Arc::new(TapRing::new()), + tap_on: false, + scope: Arc::new(ScopeRing::new()), + sc_o: 0.0, + sc_p: 0.0, + sc_n: 0, + sc_len: 96, + opk: [0.0; 2], + clip_f: false, + gr_blk: [0.0; NB], + gr_pk: [0.0; NB], + gl_blk: [0.0; NB], + gl_pk: [0.0; NB], + band_diff: [0.0; NB], + bi_ms: [1e-9; NB], + bo_ms: [1e-9; NB], + sat_vz: [0.0; NB], + sat_out: [0.0; NB], + fms: 1e-9, + lim_gr_pk: 0.0, + }; + e.derive(); + e + } + + pub fn set_sample_rate(&mut self, sr: f64) { + self.sr = sr; + self.dirty = true; + } + + pub fn set_params(&mut self, p: &XParams) { + if self.first_set { + // a fresh engine starts at the host's settings instead of gliding from defaults (host rebuilds on every enable) + self.first_set = false; + self.p = *p; + self.lim.snap_on(p.lim_on); + self.snap = true; + let sm = std::mem::replace(&mut self.smoothing, false); + self.derive(); + self.smoothing = sm; + return; + } + if *p != self.p { + self.p = *p; + self.derive(); + } + } + + /// PDC latency to report (saturator oversampling + lookahead; all bands are aligned). + pub fn latency(&self) -> u32 { + (self.strips[0].latency() + self.lim.latency()) as u32 + } + + /// Measure band `b`'s saturator loudness change for 3 s, then report the SAT GAIN that cancels it (a second call cancels). + pub fn request_sat_match(&mut self, b: usize) { + if b < NB { + self.sat_req[b] = true; + } + } + + pub fn sat_matching(&self, b: usize) -> bool { + self.sat_m[b].active + } + + /// Seconds measured so far (0..3) for band `b`. + pub fn sat_match_progress(&self, b: usize) -> f64 { + self.sat_m[b].t + } + + /// The finished match of band `b`, once (the shell writes it to that band's SAT GAIN parameter). + pub fn take_sat_result(&mut self, b: usize) -> Option { + self.sat_result[b].take() + } + + pub fn request_match(&mut self) { + self.match_req = true; + } + pub fn out_matching(&self) -> bool { + self.out_m.active + } + pub fn out_match_progress(&self) -> f64 { + self.out_m.t + } + pub fn gate_open(&self) -> bool { + self.gate_open + } + pub fn sample_rate(&self) -> f64 { + self.sr + } + + fn derive(&mut self) { + let p = self.p; + let sr = self.sr; + self.sr_prev = sr; + self.dirty = false; + self.lim.set_sample_rate(sr); + self.sc_len = ((sr * ScopeRing::BUCKET_S).round() as u32).max(1); + let snap = self.snap; + self.la_s = ((p.lookahead_ms * 0.001 * sr + 0.5).floor().max(0.0) as usize).min(1900); + let xf = [p.x1, p.x2, p.x3]; + let xs = [p.x1_slope, p.x2_slope, p.x3_slope].map(|v| v.clamp(0, 3) as usize); + self.xo.set(xf, xs, sr, snap); + self.key_xo.set(xf, xs, sr, snap); + self.key.derive(p.sc_gain, p.sc_hp, p.sc_lp, sr); + // each band's saturator is band-limited by the band's own crossover edges + let xf = Crossover4::order(xf); + for b in 0..NB { + let lo = if b == 0 { None } else { Some((xf[b - 1], xs[b - 1])) }; + let hi = if b == NB - 1 { None } else { Some((xf[b], xs[b])) }; + self.strips[b].derive(&p.bands[b], p.os, self.la_s, p.key_mix, (lo, hi), sr, snap, self.smoothing); + } + self.any_solo = p.bands.iter().any(|b| b.solo); + let any = eq_setup(&mut self.eq.bank, &p.eq, sr); + self.eq.derive_gain(any, p.eq.gain, !p.eq.bypass, sr, snap); + self.eq_mix_t = p.eq.mix * 0.01; + self.mix_t = p.mix * 0.01; + self.match_on = p.gain_match; + if self.match_on && !self.prev_match_on { + self.out_m.start(); + } + if !self.match_on { + self.out_m.stop(); + } + self.prev_match_on = self.match_on; + self.rmsg_c = one_pole(sr, 0.5); + self.og_c = one_pole(sr, 0.02); + self.byp_c = one_pole(sr, 0.01); + self.fms_c = one_pole(sr, 0.3); + self.sm_c = one_pole(sr, 0.02); + if snap { + self.snap = false; + self.eq_mix = self.eq_mix_t; + self.mix = self.mix_t; + } + } + + pub fn begin_block(&mut self, n: usize) { + if self.match_req { + self.out_m.start(); + self.match_req = false; + } + if self.dirty || self.sr != self.sr_prev { + self.derive(); + } + self.xo.begin_block(n); + self.key_xo.begin_block(n); + for s in self.strips.iter_mut() { + s.begin_block(n); + } + self.eq.begin_block(n); + + let dt = n as f64 / self.sr; + self.lim_gr_pk = self.lim_gr_pk.max(-self.lim.gmin.max(1e-6).ln() * DB_AMP); + self.lim.gmin = 1.0; + self.gate_open = self.ims > 0.000001; + if self.gate_open { + self.diff_db = DB_POW * (self.oms.max(1e-12) / self.ims.max(1e-12)).ln(); + self.diff_disp = DB_POW * (self.pms.max(1e-12) / self.ims.max(1e-12)).ln(); + } + if self.eis > 0.000001 { + self.eq_diff = DB_POW * (self.eos.max(1e-12) / self.eis.max(1e-12)).ln(); + } + if self.out_m.active && self.gate_open { + if let Some(avg) = self.out_m.step(self.diff_db, dt) { + self.match_trim = avg.clamp(-12.0, 12.0); + } + } + let trim = if self.match_on { self.match_trim } else { 0.0 }; + self.og_t = ((self.p.out_gain + trim) * LN10_20).exp(); + for b in 0..NB { + self.band_diff[b] = if self.bi_ms[b] > 1e-8 { DB_POW * (self.bo_ms[b].max(1e-12) / self.bi_ms[b]).ln() } else { 0.0 }; + self.gr_blk[b] = self.strips[b].gr_blk; + self.gr_pk[b] = self.gr_pk[b].max(self.gr_blk[b]); + self.gl_blk[b] = self.strips[b].gl_blk; + self.gl_pk[b] = self.gl_pk[b].max(self.gl_blk[b]); + self.strips[b].gl_blk = 0.0; + self.strips[b].gr_blk = 0.0; + } + for b in 0..NB { + let change = self.strips[b].sat_change_db(); + if let Some(db) = change { + self.sat_db[b] = db; + } + if std::mem::take(&mut self.sat_req[b]) { + let was = self.sat_m[b].active; + self.sat_m[b].start(); + if was { + self.sat_m[b].stop(); // a second click cancels + } + } + if self.sat_m[b].active { + if let Some(db) = change { + if let Some(avg) = self.sat_m[b].step(db, dt) { + let v = (avg.clamp(-24.0, 12.0) * 10.0 + 0.5).floor() * 0.1; + self.strips[b].sat.set_out_db(v); + self.sat_result[b] = Some(v); + } + } + } + } + let vz_d = (-(n as f64) / (self.sr * 0.15)).exp(); + for b in 0..NB { + self.sat_vz[b] = self.strips[b].sat.blk.max(self.sat_vz[b] * vz_d); + self.strips[b].sat.blk = 0.0; + self.sat_out[b] = self.sat_out[b].max(self.strips[b].sat_pk); + self.strips[b].sat_pk = 0.0; + } + } + + pub fn process(&mut self, left: &mut [f32], right: &mut [f32]) { + self.process_sc(left, right, None); + } + + /// As `process`, with the host's sidechain bus (`None` = no bus: the compressors key off their own bands). + pub fn process_sc(&mut self, left: &mut [f32], right: &mut [f32], sc: Option<(&[f32], &[f32])>) { + let mut n = left.len().min(right.len()); + if let Some((a, b)) = sc { + n = n.min(a.len()).min(b.len()); + } + self.sc_avail = sc.is_some(); + self.begin_block(n); + for i in 0..n { + let (kl, kr) = match sc { + Some((a, b)) => (a[i] as f64, b[i] as f64), + None => (0.0, 0.0), + }; + let (l, r) = self.tick_sc(left[i] as f64, right[i] as f64, kl, kr); + left[i] = l as f32; + right[i] = r as f32; + } + } + + #[inline] + pub fn tick(&mut self, in_l: f64, in_r: f64) -> (f64, f64) { + self.tick_sc(in_l, in_r, 0.0, 0.0) + } + + /// One sample with a sidechain sample pair (ignored unless the sidechain is on and the host gave a bus). + #[inline] + pub fn tick_sc(&mut self, in_l: f64, in_r: f64, sc_l: f64, sc_r: f64) -> (f64, f64) { + let inp = [in_l, in_r]; + ms_step(&mut self.ims, in_l, in_r, self.rmsg_c); + if self.smoothing { + self.eq_mix += (self.eq_mix_t - self.eq_mix) * self.sm_c; + self.mix += (self.mix_t - self.mix) * self.sm_c; + } else { + self.eq_mix = self.eq_mix_t; + self.mix = self.mix_t; + } + self.dw.advance(); + self.dw.put(inp); + let dt = self.dw.tap(self.strips[0].latency()); + // the untouched input a limiter latency later: lines up with the limited path for the bypass blend + let ll = self.lim.latency(); + let db = self.dw.tap(self.strips[0].latency() + ll); + + // ---- split, process each band, sum with solo / delta weighting + let bands = self.xo.tick(inp); + let sgn = self.xo.signs(); + // key: gain > HP > LP, delayed to line up with the saturator outputs, then split into bands by its own crossover + let sc_act = self.p.sc_on && self.sc_avail; + let scv = self.key.tick(if sc_act { Some([sc_l, sc_r]) } else { None }, self.strips[0].sat.latency()); + let kb = if sc_act { Some(self.key_xo.tick(scv)) } else { None }; + let mut sum = [0.0f64; 2]; + let mut pre = [0.0f64; 2]; + let mut gmax = 0.0f64; + let gdelta = if self.delta_on { 1.0 } else { 0.0 }; + self.gd_s += (gdelta - self.gd_s) * self.byp_c; + for b in 0..NB { + let o = self.strips[b].tick(bands[b], self.smoothing, kb.map(|k| k[b])); + ms_step(&mut self.bi_ms[b], bands[b][0], bands[b][1], self.rmsg_c); + ms_step(&mut self.bo_ms[b], o.y[0], o.y[1], self.rmsg_c); + if self.p.bands[b].on { + gmax = gmax.max(o.g); + } + let bp = &self.p.bands[b]; + let dtarget: f64 = if bp.delta { 1.0 } else { 0.0 }; + let d = self.d_s[b] + (dtarget.max(gdelta) - self.d_s[b]) * self.byp_c; + self.d_s[b] = d; + let stgt = if self.any_solo { if bp.solo { 1.0 } else { 0.0 } } else { 1.0 }; + let sg = self.solo_s[b] + (stgt - self.solo_s[b]) * self.byp_c; + self.solo_s[b] = sg; + for c in 0..2 { + sum[c] += (o.y[c] + (o.removed[c] - o.y[c]) * d) * sg * sgn[b]; + pre[c] += o.pre[c] * sgn[b]; + } + } + + // ---- EQ (post-sum) with its own dry/wet + let ew = self.eq.tick(sum); + let wet = [sum[0] + (ew[0] - sum[0]) * self.eq_mix, sum[1] + (ew[1] - sum[1]) * self.eq_mix]; + ms_step(&mut self.eis, sum[0], sum[1], self.rmsg_c); + ms_step(&mut self.eos, wet[0], wet[1], self.rmsg_c); + + // ---- OUT + let mut o = [0.0f64; 2]; + for c in 0..2 { + o[c] = dt[c] + (wet[c] - dt[c]) * self.mix; + } + ms_step(&mut self.oms, o[0], o[1], self.rmsg_c); + self.og += (self.og_t - self.og) * self.og_c; + let pp = [o[0] * self.og, o[1] * self.og]; + ms_step(&mut self.pms, pp[0], pp[1], self.rmsg_c); + self.byp_s += ((if self.p.bypass { 1.0 } else { 0.0 }) - self.byp_s) * self.byp_c; + // output limiter (processed path only: bypass and the key monitor are the untouched input / a monitor) + let lo = self.lim.tick(pp, self.p.lim_on); + let mut out = [lo[0] + (db[0] - lo[0]) * self.byp_s, lo[1] + (db[1] - lo[1]) * self.byp_s]; + // solo: hear the conditioned key as the detectors get it + self.sc_s += ((if self.sc_solo && sc_act { 1.0 } else { 0.0 }) - self.sc_s) * self.byp_c; + self.mon_s.advance(); + self.mon_s.put(scv); + if self.sc_s > 0.0001 { + let sv = self.mon_s.tap(ll); + for c in 0..2 { + out[c] += (sv[c] - out[c]) * self.sc_s; + } + } + + if self.tap_on { + self.tap_out.push(((out[0] + out[1]) * 0.5) as f32); + self.tap_dry.push(((pre[0] + pre[1]) * 0.5) as f32); + } + self.opk[0] = self.opk[0].max(out[0].abs()); + self.opk[1] = self.opk[1].max(out[1].abs()); + if out[0].abs() > 0.9999 || out[1].abs() > 0.9999 { + self.clip_f = true; + } + // scope bucket: output peak, and the same with the loudest band's gain reduction added back + let ao = out[0].abs().max(out[1].abs()); + self.sc_o = self.sc_o.max(ao); + self.sc_p = self.sc_p.max(ao * (gmax * LN10_20).exp()); + self.sc_n += 1; + if self.sc_n >= self.sc_len { + self.scope.push(self.sc_o as f32, self.sc_p as f32); + self.sc_o = 0.0; + self.sc_p = 0.0; + self.sc_n = 0; + } + self.fms += ((out[0] * out[0] + out[1] * out[1]) * 0.5 + DENORM - self.fms) * self.fms_c; + (out[0], out[1]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f64::consts::PI; + + const SR: f64 = 48000.0; + /// the limiter's constant delay at 48 kHz (always reported) + const LIM_LAT: u32 = 32 + 72; + + fn noise(n: usize, seed: u64) -> Vec { + let mut s = seed; + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (((s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0) * 0.3 + }) + .collect() + } + + /// a plug-in state where nothing alters the signal (no saturation, no compression, EQ flat) + fn neutral() -> XParams { + let mut p = XParams::default(); + for b in p.bands.iter_mut() { + b.drive = 0.0; + b.ratio = 1.0; + b.thresh = 0.0; + } + p.lim_on = false; + p + } + + fn run(e: &mut XEngine, x: &[f64]) -> Vec { + let (mut l, mut r): (Vec, Vec) = (x.iter().map(|v| *v as f32).collect(), x.iter().map(|v| *v as f32).collect()); + for (cl, cr) in l.chunks_mut(256).zip(r.chunks_mut(256)) { + e.process(cl, cr); + } + l.iter().map(|v| *v as f64).collect() + } + + fn rms(x: &[f64]) -> f64 { + (x.iter().map(|v| v * v).sum::() / x.len() as f64).sqrt() + } + + #[test] + fn neutral_engine_is_flat_in_level() { + let x = noise(48000, 1); + let mut e = XEngine::new(SR); + e.set_params(&neutral()); + let y = run(&mut e, &x); + let (a, b) = (rms(&x[4000..]), rms(&y[4000..])); + assert!((20.0 * (b / a).log10()).abs() < 0.1, "{a} vs {b}"); + } + + #[test] + fn neutral_engine_stays_flat_at_every_crossover_slope() { + let x = noise(48000, 5); + for (s1, s2, s3) in [(0, 0, 0), (0, 3, 1), (2, 1, 0), (3, 3, 3)] { + let mut p = neutral(); + p.x1_slope = s1; + p.x2_slope = s2; + p.x3_slope = s3; + let mut e = XEngine::new(SR); + e.set_params(&p); + let y = run(&mut e, &x); + let g = 20.0 * (rms(&y[6000..]) / rms(&x[6000..])).log10(); + assert!(g.abs() < 0.1, "slopes {s1}/{s2}/{s3}: {g} dB"); + } + } + + #[test] + fn switching_crossover_slope_does_not_click() { + // a steady tone through the whole engine; the slopes change mid-stream and the output must stay as smooth as the tone itself + let amp = 0.5; + let w = 2.0 * PI * 330.0 / SR; + let tone: Vec = (0..48000).map(|i| amp * (w * i as f64).sin()).collect(); + for (from, to) in [((1, 1, 1), (2, 1, 1)), ((1, 1, 1), (0, 1, 0)), ((0, 0, 0), (3, 3, 3)), ((3, 3, 3), (1, 1, 1))] { + let mut p = neutral(); + p.x1 = 200.0; + p.x2 = 1200.0; + p.x3 = 5000.0; + p.x1_slope = from.0; + p.x2_slope = from.1; + p.x3_slope = from.2; + let mut e = XEngine::new(SR); + e.set_params(&p); + let mut y = run(&mut e, &tone[..24000]); + p.x1_slope = to.0; + p.x2_slope = to.1; + p.x3_slope = to.2; + e.set_params(&p); + y.extend(run(&mut e, &tone[24000..])); + let worst = y.windows(2).skip(8000).map(|d| (d[1] - d[0]).abs()).fold(0.0, f64::max); + // a pure sine of this amplitude moves at most amp * w per sample + assert!(worst < amp * w * 1.5, "slope {from:?} -> {to:?} clicked: step {worst:.4} (tone {:.4})", amp * w); + } + } + + #[test] + fn a_band_only_affects_its_own_range() { + // compress only the high-mid band hard: a low tone is untouched, a tone inside the band is reduced + let tone = |f: f64| (0..48000).map(|i| 0.5 * (2.0 * PI * f * i as f64 / SR).sin()).collect::>(); + let mut p = neutral(); + p.bands[2].thresh = -30.0; + p.bands[2].ratio = 20.0; + let (lo, mid) = (tone(60.0), tone(1800.0)); + let (mut e1, mut e2) = (XEngine::new(SR), XEngine::new(SR)); + e1.set_params(&p); + e2.set_params(&p); + let (ylo, ymid) = (run(&mut e1, &lo), run(&mut e2, &mid)); + let dlo = 20.0 * (rms(&ylo[8000..]) / rms(&lo[8000..])).log10(); + let dmid = 20.0 * (rms(&ymid[8000..]) / rms(&mid[8000..])).log10(); + assert!(dlo.abs() < 0.3, "low changed {dlo}"); + assert!(dmid < -8.0, "mid not compressed {dmid}"); + } + + #[test] + fn solo_isolates_a_band_and_off_band_passes_through() { + let x = noise(48000, 2); + let mut p = neutral(); + p.bands[0].solo = true; + let mut e = XEngine::new(SR); + e.set_params(&p); + let y = run(&mut e, &x); + assert!(rms(&y[6000..]) < rms(&x[6000..]) * 0.6, "solo low should remove most of a white noise"); + let mut p = neutral(); + p.bands[1].on = false; + let mut e = XEngine::new(SR); + e.set_params(&p); + let y2 = run(&mut e, &x); + assert!((20.0 * (rms(&y2[6000..]) / rms(&x[6000..])).log10()).abs() < 0.1); + } + + #[test] + fn eq_band_boosts_and_latency_is_reported() { + let tone: Vec = (0..48000).map(|i| 0.2 * (2.0 * PI * 5000.0 * i as f64 / SR).sin()).collect(); + let mut p = neutral(); + p.eq.bands[3].on = true; + p.eq.bands[3].freq = 5000.0; + p.eq.bands[3].gain = 6.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + let y = run(&mut e, &tone); + let g = 20.0 * (rms(&y[8000..]) / rms(&tone[8000..])).log10(); + assert!((g - 6.0).abs() < 0.3, "{g}"); + p.os = 2; + p.lookahead_ms = 2.0; + e.set_params(&p); + assert_eq!(e.latency(), 28 + (2.0f64 * 0.001 * SR + 0.5).floor() as u32 + LIM_LAT); + } + + #[test] + fn limiter_latency_is_reported_on_or_off_and_the_limiter_holds_the_ceiling() { + let mut e = XEngine::new(SR); + let mut p = neutral(); + e.set_params(&p); + assert_eq!(e.latency(), LIM_LAT); + p.lim_on = true; + e.set_params(&p); + assert_eq!(e.latency(), LIM_LAT); + // +18 dB of SAT GAIN on a hot tone: the output stays at the -0.2 dBTP ceiling and the reduction is reported + for b in p.bands.iter_mut() { + b.sat_gain = 12.0; + } + e.set_params(&p); + let t: Vec = (0..48000).map(|i| 0.8 * (2.0 * PI * 1000.0 * i as f64 / SR).sin()).collect(); + let y = run(&mut e, &t); + let pk = y[24000..].iter().fold(0.0f64, |m, v| m.max(v.abs())); + assert!(pk <= 0.9777 && pk > 0.9, "peak {pk}"); + assert!(e.lim_gr_pk > 5.0, "gr {}", e.lim_gr_pk); + p.lim_on = false; + e.set_params(&p); + let y = run(&mut e, &t); + assert!(y[24000..].iter().fold(0.0f64, |m, v| m.max(v.abs())) > 2.0, "off must not limit"); + } + + #[test] + fn scope_buckets_show_output_and_the_reduction_added_back() { + let mut p = neutral(); + for b in p.bands.iter_mut() { + b.thresh = -20.0; + b.ratio = 8.0; + } + let mut e = XEngine::new(SR); + e.set_params(&p); + let t: Vec = (0..48000).map(|i| 0.8 * (2.0 * PI * 200.0 * i as f64 / SR).sin()).collect(); + run(&mut e, &t); + let n = e.scope.head(); + assert!((n as f64 - 48000.0 / (SR * ScopeRing::BUCKET_S)).abs() < 3.0, "buckets {n}"); + let (o, pre) = e.scope.get(n - 20); + assert!(o > 0.05 && pre > o * 1.5, "out {o}, with reduction {pre}"); + } + + #[test] + fn sat_gain_changes_the_level_after_the_first_block() { + let x = noise(48000, 4); + let mut e = XEngine::new(SR); + e.set_params(&neutral()); + let y0 = run(&mut e, &x); + let mut p = neutral(); + for b in p.bands.iter_mut() { + b.sat_gain = 6.0; + } + e.set_params(&p); + let y1 = run(&mut e, &x); + let g = 20.0 * (rms(&y1[8000..]) / rms(&y0[8000..])).log10(); + assert!((g - 6.0).abs() < 0.5, "sat gain +6 dB moved the level by {g}"); + } + + fn tone_db(f: f64, p: &XParams, warm: Option<&XParams>) -> f64 { + let t: Vec = (0..48000).map(|i| 0.2 * (2.0 * PI * f * i as f64 / SR).sin()).collect(); + let mut e = XEngine::new(SR); + if let Some(w) = warm { + e.set_params(w); + run(&mut e, &t); + } + e.set_params(p); + let y = run(&mut e, &t); + 20.0 * (rms(&y[8000..]) / rms(&t[8000..])).log10() + } + + #[test] + fn eq_gain_mix_and_pivot_act() { + // EQ GAIN on its own (no bands on) + let mut p = neutral(); + p.eq.gain = 6.0; + let g = tone_db(1000.0, &p, None); + assert!((g - 6.0).abs() < 0.3, "eq gain {g}"); + // ... also when changed after the engine has been running + let g = tone_db(1000.0, &p, Some(&neutral())); + assert!((g - 6.0).abs() < 0.3, "eq gain after warm-up {g}"); + // EQ MIX 0 takes the whole EQ out + let mut p = neutral(); + p.eq.bands[3].on = true; + p.eq.bands[3].freq = 5000.0; + p.eq.bands[3].gain = 9.0; + let full = tone_db(5000.0, &p, None); + p.eq.mix = 0.0; + let off = tone_db(5000.0, &p, None); + assert!(full > 8.0 && off.abs() < 0.3, "eq mix: full {full}, mix 0 {off}"); + // pivot moves where the tilt crosses 0 dB + let mut p = neutral(); + p.eq.tilt = 6.0; + p.eq.pivot = 200.0; + let a = tone_db(200.0, &p, None); + p.eq.pivot = 4000.0; + let b = tone_db(200.0, &p, None); + assert!((a - b).abs() > 2.0, "pivot has no effect: {a} vs {b}"); + } + + #[test] + fn eq_diff_reads_the_level_change_across_the_eq_stage_only() { + let tone: Vec = (0..96000).map(|i| 0.2 * (2.0 * PI * 5000.0 * i as f64 / SR).sin()).collect(); + let mut p = neutral(); + p.eq.bands[3].on = true; + p.eq.bands[3].freq = 5000.0; + p.eq.bands[3].gain = 6.0; + p.out_gain = -9.0; // output gain is outside the EQ stage and must not show up + let mut e = XEngine::new(SR); + e.set_params(&p); + run(&mut e, &tone); + assert!((e.eq_diff - 6.0).abs() < 0.5, "eq diff {}", e.eq_diff); + p.eq.mix = 0.0; + e.set_params(&p); + run(&mut e, &tone); + assert!(e.eq_diff.abs() < 0.5, "eq mix 0 should read 0 dB, got {}", e.eq_diff); + } + + #[test] + fn a_band_in_upward_mode_lifts_quiet_material_and_reports_the_lift_not_a_reduction() { + // a -50 dB low tone with the threshold at -30 dB, ratio 2: lifted by about 10 dB, only in the band that is switched to UP + let tone = sine(48000 * 2, 80.0, 0.00316); + let mut p = neutral(); + p.bands[0].thresh = -30.0; + p.bands[0].ratio = 2.0; + p.bands[0].knee = 0.0; + p.bands[0].up = 1; + p.bands[0].up_range = 12.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + let out = run(&mut e, &tone); + let (i, o) = (rms(&tone[48000..]), rms(&out[48000..])); + let gain = 20.0 * (o / i).log10(); + assert!(gain > 6.0 && gain < 12.5, "band lifted by {gain} dB"); + assert!(e.gl_pk[0] > 6.0, "lift reported: {}", e.gl_pk[0]); + assert_eq!(e.gr_pk[0], 0.0, "no reduction in upward mode"); + assert!(e.gl_pk[1] == 0.0 && e.gl_pk[2] == 0.0 && e.gl_pk[3] == 0.0, "other bands untouched: {:?}", e.gl_pk); + } + + #[test] + fn the_sat_match_of_a_band_cancels_that_bands_saturator_change() { + // drive the low band hard on a low tone: the saturator is louder, the match turns SAT GAIN down; other bands untouched + let tone = sine(48000 * 5, 80.0, 0.3); + let mut p = neutral(); + p.bands[0].drive = 70.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + e.request_sat_match(0); + let (mut l, mut r): (Vec, Vec) = (tone.iter().map(|&v| v as f32).collect(), tone.iter().map(|&v| v as f32).collect()); + let mut got = None; + for (cl, cr) in l.chunks_mut(256).zip(r.chunks_mut(256)) { + e.process(cl, cr); + if let Some(v) = e.take_sat_result(0) { + got = Some(v); + } + } + let v = got.expect("the measurement finishes within 5 s"); + assert!(v < -0.5 && v > -24.0, "drive 70 on a tone is louder, the match turns it down: {v}"); + assert!((v + e.sat_db[0]).abs() < 1.0, "match {v} vs measured change {}", e.sat_db[0]); + assert!(e.take_sat_result(0).is_none() && !e.sat_matching(0)); + for b in 1..NB { + assert!(e.take_sat_result(b).is_none(), "band {b} was not asked"); + } + } + + #[test] + fn sat_out_is_the_post_saturator_peak_per_band() { + let tone: Vec = (0..48000).map(|i| 0.5 * (2.0 * PI * 50.0 * i as f64 / SR).sin()).collect(); + let mut e = XEngine::new(SR); + e.set_params(&neutral()); + run(&mut e, &tone); + assert!((e.sat_out[0] - 0.5).abs() < 0.1, "low band peak: {}", e.sat_out[0]); + assert!(e.sat_out[1] < 0.1 && e.sat_out[2] < 0.05 && e.sat_out[3] < 0.05, "other bands only see leakage: {:?}", e.sat_out); + // hot sat gain pushes the post-sat peak over full scale (what the clip indicator watches) + let mut p = neutral(); + p.bands[0].sat_gain = 12.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + run(&mut e, &tone); + assert!(e.sat_out[0] > 1.5, "+12 dB sat gain on a 0.5 peak: {}", e.sat_out[0]); + } + + #[test] + fn sat_vz_follows_each_bands_saturator_input() { + let tone: Vec = (0..48000).map(|i| 0.4 * (2.0 * PI * 50.0 * i as f64 / SR).sin()).collect(); + let mut e = XEngine::new(SR); + let mut p = XParams::default(); + for b in p.bands.iter_mut() { + b.drive = 25.0; // the saturator only measures while it is active + } + e.set_params(&p); + run(&mut e, &tone); + assert!((e.sat_vz[0] - 0.4).abs() < 0.08, "low band sees the 50 Hz tone: {}", e.sat_vz[0]); + assert!(e.sat_vz[1] < 0.02 && e.sat_vz[2] < 0.02 && e.sat_vz[3] < 0.02, "other bands stay quiet: {:?}", e.sat_vz); + } + + fn sine(n: usize, f: f64, amp: f64) -> Vec { + (0..n).map(|i| amp * (2.0 * PI * f * i as f64 / SR).sin()).collect() + } + + fn run_sc(e: &mut XEngine, x: &[f64], key: Option<&[f64]>) -> Vec { + let mut l: Vec = x.iter().map(|v| *v as f32).collect(); + let mut r = l.clone(); + let kf: Option> = key.map(|k| k.iter().map(|v| *v as f32).collect()); + for (i, (cl, cr)) in l.chunks_mut(256).zip(r.chunks_mut(256)).enumerate() { + match &kf { + Some(k) => { + let ks = &k[i * 256..(i * 256 + cl.len()).min(k.len())]; + e.process_sc(cl, cr, Some((ks, ks))); + } + None => e.process_sc(cl, cr, None), + } + } + l.iter().map(|v| *v as f64).collect() + } + + /// every band compresses hard at a low threshold, keyed (not by its own signal) with KEY MIX 100 % + fn sc_params() -> XParams { + let mut p = neutral(); + for b in p.bands.iter_mut() { + b.thresh = -30.0; + b.ratio = 20.0; + b.attack = 0.5; + b.knee = 0.0; + } + p.sc_on = true; + p.key_mix = 100.0; + p + } + + fn gain_db(y: &[f64], x: &[f64]) -> f64 { + 20.0 * (rms(&y[12000..]) / rms(&x[12000..])).log10() + } + + #[test] + fn a_low_key_only_ducks_the_low_band() { + let key = sine(48000, 60.0, 0.9); + // low main (60 Hz) is ducked by the low key ... + let low = sine(48000, 60.0, 0.1); + let mut e = XEngine::new(SR); + e.set_params(&sc_params()); + let g_low = gain_db(&run_sc(&mut e, &low, Some(&key)), &low); + // ... a high main (5 kHz) is not: its band's slice of the key is silent, and the key replaces the band's own detector + let high = sine(48000, 5000.0, 0.1); + let mut e = XEngine::new(SR); + e.set_params(&sc_params()); + let g_high = gain_db(&run_sc(&mut e, &high, Some(&key)), &high); + assert!(g_low < -6.0, "low band should be ducked by the low key: {g_low} dB"); + assert!(g_high > -1.0, "high band must ignore a low key: {g_high} dB"); + } + + #[test] + fn key_is_ignored_when_off_or_when_the_host_has_no_bus() { + let main = sine(48000, 60.0, 0.1); + let key = sine(48000, 60.0, 0.9); + let mut p = sc_params(); + p.sc_on = false; + let mut e = XEngine::new(SR); + e.set_params(&p); + // sidechain off: the key does nothing, so the quiet main keeps its own (key-free) detection: key_mix is moot + let g_off = gain_db(&run_sc(&mut e, &main, Some(&key)), &main); + let mut e = XEngine::new(SR); + e.set_params(&p); + let g_off_nokey = gain_db(&run_sc(&mut e, &main, None), &main); + assert!((g_off - g_off_nokey).abs() < 0.2, "key must not matter while the sidechain is off: {g_off} vs {g_off_nokey}"); + // sidechain on but no bus: same as off + let mut e = XEngine::new(SR); + e.set_params(&sc_params()); + let g_nobus = gain_db(&run_sc(&mut e, &main, None), &main); + assert!((g_nobus - g_off_nokey).abs() < 0.2, "no bus = no key: {g_nobus} vs {g_off_nokey}"); + } + + #[test] + fn key_hp_ignores_a_low_key_and_gain_scales_it() { + let main = sine(48000, 60.0, 0.1); + let key = sine(48000, 60.0, 0.9); + let mut p = sc_params(); + p.sc_hp = 2000.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + let g = gain_db(&run_sc(&mut e, &main, Some(&key)), &main); + assert!(g > -1.0, "a 60 Hz key behind a 2 kHz high-pass must not duck: {g} dB"); + // key gain scales the ducking: the same key 40 dB lower ducks far less than at 0 dB + let g0 = { + let mut e = XEngine::new(SR); + e.set_params(&sc_params()); + gain_db(&run_sc(&mut e, &main, Some(&key)), &main) + }; + let mut p = sc_params(); + p.sc_gain = -40.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + let g40 = gain_db(&run_sc(&mut e, &main, Some(&key)), &main); + assert!(g0 < -6.0 && g40 > g0 + 5.0, "gain -40 dB should duck much less: {g0} dB vs {g40} dB"); + } + + #[test] + fn sidechain_solo_outputs_the_conditioned_key() { + let mut p = sc_params(); + p.sc_gain = -6.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + e.sc_solo = true; + let key = sine(48000, 1000.0, 0.5); + let y = run_sc(&mut e, &sine(48000, 440.0, 0.1), Some(&key)); + let want = rms(&key[24000..]) * 0.5012; // -6 dB + assert!((rms(&y[24000..]) - want).abs() < want * 0.1, "solo should be the key at -6 dB: {} vs {want}", rms(&y[24000..])); + } + + #[test] + fn saturation_and_all_modes_run_clean() { + let x = noise(24000, 3); + for os in 0..3 { + let mut p = XParams::default(); + p.os = os; + p.lookahead_ms = 3.0; + for b in p.bands.iter_mut() { + b.drive = 80.0; + b.shape = 5; + b.thresh = -24.0; + b.release = 2000.0; + } + p.eq.bands[2].on = true; + p.eq.tilt = 3.0; + let mut e = XEngine::new(SR); + e.set_params(&p); + let y = run(&mut e, &x); + assert!(y.iter().all(|v| v.is_finite() && v.abs() < 8.0)); + } + } + + #[test] + fn a_bands_harmonics_stay_inside_its_edges() { + // 50 Hz through the hard-driven low band (edge 150 Hz, 24 dB/oct): the 5th and 7th harmonic (250 / 350 Hz) the + // shaper creates are far below the fundamental, and the rest of the bands add nothing there + let tone: Vec = (0..96000).map(|i| 0.5 * (2.0 * PI * 50.0 * i as f64 / SR).sin()).collect(); + let bin = |y: &[f64], f: f64| { + let (mut re, mut im) = (0.0, 0.0); + for (n, v) in y.iter().enumerate() { + let w = 2.0 * PI * f * n as f64 / SR; + re += v * w.cos(); + im += v * w.sin(); + } + (re * re + im * im).sqrt() / y.len() as f64 * 2.0 + }; + let mut p = neutral(); + p.bands[0].drive = 100.0; + p.bands[0].shape = 3; + let mut e = XEngine::new(SR); + e.set_params(&p); + let y = run(&mut e, &tone); + let y = &y[48000..]; + let (f1, h5, h7) = (bin(y, 50.0), bin(y, 250.0), bin(y, 350.0)); + assert!(h5 < f1 * 0.035 && h7 < f1 * 0.01, "fund {f1} h5 {h5} h7 {h7}"); + } +} diff --git a/rust/satxcomp-dsp/src/lib.rs b/rust/satxcomp-dsp/src/lib.rs new file mode 100644 index 0000000..bfdb597 --- /dev/null +++ b/rust/satxcomp-dsp/src/lib.rs @@ -0,0 +1,11 @@ +//! DSP for SatXComp, the 4-band multiband version of SatComp, built from the shared `satcomp-dsp` blocks. + +pub mod confine; +pub mod engine; +pub mod params; +pub mod strip; +pub mod xover; + +pub use engine::XEngine; +pub use xover::NB; +pub use params::{eq_kind, BandParams, EqBandParams, EqParams, XParams, EQ_DEFAULT_FREQ, EQ_DEFAULT_ON, EQ_DEFAULT_TYPE, EQ_KINDS}; diff --git a/rust/satxcomp-dsp/src/params.rs b/rust/satxcomp-dsp/src/params.rs new file mode 100644 index 0000000..ac00af0 --- /dev/null +++ b/rust/satxcomp-dsp/src/params.rs @@ -0,0 +1,179 @@ +//! SatXComp parameter set (plain f64 values; the plug-in shell maps its nih-plug parameters onto this). + +use satcomp_dsp::shapers::Curve; + +pub use satcomp_dsp::shapers::SHAPER_COUNT; + +/// One band's saturator + compressor + output stage. +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct BandParams { + /// band module on (off = the band passes through untouched, still part of the crossover sum) + pub on: bool, + /// monitor only this band (several soloed bands are heard together) + pub solo: bool, + /// monitor what this band's compressor removed + pub delta: bool, + // SAT + pub shape: i32, + pub curve: Curve, + /// ASYM per shaper (0..100 %: how much of the shaper's even part is kept, see `SatParams::asym`); the active one is `asym[shape]` + pub asym: [f64; SHAPER_COUNT], + pub drive: f64, + pub bias: f64, + pub tone: f64, + /// saturator input high-pass / low-pass, Hz (20 / 20000 = off) + pub hp: f64, + pub lp: f64, + pub sat_mix: f64, + pub sat_gain: f64, + // COMP + pub thresh: f64, + pub ratio: f64, + pub attack: f64, + pub release: f64, + pub speed: f64, + pub knee: f64, + pub knee_shape: f64, + pub detector: f64, + pub ff_fb: f64, + pub gr_dist: f64, + /// 0..100 %: compressed vs the un-compressed saturated signal (parallel compression) + pub comp_mix: f64, + /// dB after the compressor + pub comp_gain: f64, + /// compressor mode: 0 = downward (reduce above the threshold), 1 = upward (lift below it), 2 = both + pub up: i32, + /// dB: the most the upward mode lifts + pub up_range: f64, +} + +impl Default for BandParams { + fn default() -> Self { + Self { + on: true, + solo: false, + delta: false, + shape: 0, + curve: Curve::linear(), + asym: [100.0; SHAPER_COUNT], + drive: 0.0, + bias: 0.0, + tone: 20000.0, + hp: 20.0, + lp: 20000.0, + sat_mix: 100.0, + sat_gain: 0.0, + thresh: 0.0, + ratio: 4.0, + attack: 10.0, + release: 150.0, + speed: 50.0, + knee: 6.0, + knee_shape: 0.0, + detector: 30.0, + ff_fb: 0.0, + gr_dist: 0.0, + comp_mix: 100.0, + comp_gain: 0.0, + up: 0, + up_range: 12.0, + } + } +} + +/// Filter kinds each EQ band can take, by stored type index (0 HPF, 1 LPF, 2 low shelf, 3 high shelf, 4 bell, 5 all-pass, +/// 6 band-pass, 7 notch): bands 1-2 start from a high-pass, band 3 is shelf/shelf, bands 4-5 end in a low-pass. +pub const EQ_KINDS: [[u8; 6]; 5] = [[0, 2, 4, 5, 6, 7], [0, 2, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7], [1, 3, 4, 5, 6, 7], [1, 3, 4, 5, 6, 7]]; +pub const EQ_DEFAULT_TYPE: [i32; 5] = [1, 2, 2, 2, 1]; +pub const EQ_DEFAULT_FREQ: [f64; 5] = [80.0, 200.0, 1000.0, 5000.0, 10000.0]; +pub const EQ_DEFAULT_ON: [bool; 5] = [true, true, false, false, true]; + +pub fn eq_kind(band: usize, ty: i32) -> u8 { + EQ_KINDS[band.min(4)][(ty.max(0) as usize).min(5)] +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct EqBandParams { + pub on: bool, + /// index into `EQ_KINDS[band]` + pub ty: i32, + pub freq: f64, + pub q: f64, + pub gain: f64, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct EqParams { + pub bands: [EqBandParams; 5], + pub tilt: f64, + pub pivot: f64, + /// 0..100 % dry/wet of the whole EQ + pub mix: f64, + pub gain: f64, + pub bypass: bool, +} + +impl Default for EqParams { + fn default() -> Self { + let b = |i: usize| EqBandParams { on: EQ_DEFAULT_ON[i], ty: EQ_DEFAULT_TYPE[i], freq: EQ_DEFAULT_FREQ[i], q: 0.71, gain: 0.0 }; + Self { bands: [b(0), b(1), b(2), b(3), b(4)], tilt: 0.0, pivot: 600.0, mix: 100.0, gain: 0.0, bypass: false } + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct XParams { + /// crossover frequencies, Hz (each is kept above the one below) + pub x1: f64, + pub x2: f64, + pub x3: f64, + /// crossover slopes: 0 = 12, 1 = 24, 2 = 48, 3 = 96 dB/oct + pub x1_slope: i32, + pub x2_slope: i32, + pub x3_slope: i32, + /// saturator oversampling: 0 off, 1 x2, 2 x4 + pub os: i32, + pub lookahead_ms: f64, + /// external key for the compressors (the sidechain bus); gain / HP / LP condition it before it is split into bands + pub sc_on: bool, + pub sc_gain: f64, + pub sc_hp: f64, + pub sc_lp: f64, + /// 0..100 %: how much of every band's detector level comes from the key instead of the band's own signal + pub key_mix: f64, + pub bands: [BandParams; crate::xover::NB], + pub eq: EqParams, + /// 0..100 % dry/wet of the whole plug-in + pub mix: f64, + pub out_gain: f64, + pub gain_match: bool, + pub bypass: bool, + /// true-peak output limiter (-0.2 dBTP) after OUT GAIN; its lookahead latency is always reported + pub lim_on: bool, +} + +impl Default for XParams { + fn default() -> Self { + Self { + x1: 150.0, + x2: 800.0, + x3: 3500.0, + x1_slope: 1, + x2_slope: 1, + x3_slope: 1, + os: 0, + lookahead_ms: 0.0, + sc_on: false, + sc_gain: 0.0, + sc_hp: 20.0, + sc_lp: 20000.0, + key_mix: 100.0, + bands: [BandParams::default(); crate::xover::NB], + eq: EqParams::default(), + mix: 100.0, + out_gain: 0.0, + gain_match: false, + bypass: false, + lim_on: true, + } + } +} diff --git a/rust/satxcomp-dsp/src/strip.rs b/rust/satxcomp-dsp/src/strip.rs new file mode 100644 index 0000000..cf2ffce --- /dev/null +++ b/rust/satxcomp-dsp/src/strip.rs @@ -0,0 +1,181 @@ +//! One band's channel strip: saturator -> lookahead -> compressor -> parallel mix and gain, with a latency-aligned bypass. + +use crate::confine::{Confine, Edge}; +use crate::params::BandParams; +use satcomp_dsp::delay::StereoDelay; +use satcomp_dsp::level::{ms_step, one_pole, LN10_20}; +use satcomp_dsp::{Compressor, SatParams, Saturator}; +use satcomp_dsp::CompParams; + +pub struct StripOut { + /// the band's output (module on/off crossfade applied), aligned to the plug-in latency + pub y: [f64; 2], + /// what the compressor removed (delta monitor) + pub removed: [f64; 2], + /// the saturated signal before the compressor (for the "dry" spectrum) + pub pre: [f64; 2], + /// gain reduction of the louder channel, dB (positive) + pub g: f64, +} + +pub struct Strip { + pub sat: Saturator, + pub comp: Compressor, + confine: Confine, + lk: StereoDelay<4096>, + dry: StereoDelay<4096>, + la_s: usize, + cmix: f64, + cmix_t: f64, + cg: f64, + cg_t: f64, + on_s: f64, + on_t: f64, + sm_c: f64, + on_c: f64, + /// gain reduction of the loudest channel in the current block, dB (the owner resets it) + pub gr_blk: f64, + /// gain lift of the loudest channel in the current block, dB (upward mode; the owner resets it) + pub gl_blk: f64, + /// peak of the saturator output (before the compressor) since the owner last reset it + pub sat_pk: f64, + /// slow mean squares of the band's input and of the saturator's result before SAT GAIN (after the band confine): the + /// loudness change the SAT GAIN level match cancels + ims: f64, + sms: f64, + ms_c: f64, +} + +impl Default for Strip { + fn default() -> Self { + Self::new() + } +} + +impl Strip { + pub fn new() -> Self { + Self { + sat: Saturator::new(), + comp: Compressor::new(), + confine: Confine::new(), + lk: StereoDelay::new(), + dry: StereoDelay::new(), + la_s: 0, + cmix: 1.0, + cmix_t: 1.0, + cg: 1.0, + cg_t: 1.0, + on_s: 1.0, + on_t: 1.0, + sm_c: 0.0, + on_c: 0.0, + gr_blk: 0.0, + gl_blk: 0.0, + sat_pk: 0.0, + ims: 1e-9, + sms: 1e-9, + ms_c: 0.0, + } + } + + /// Loudness change of the band across its saturator in dB (SAT GAIN not included); `None` while the band is silent. + pub fn sat_change_db(&self) -> Option { + (self.ims > 0.000001).then(|| 4.3429448 * (self.sms.max(1e-12) / self.ims.max(1e-12)).ln()) + } + + pub fn sat_params(p: &BandParams, os: i32) -> SatParams { + SatParams { shape: p.shape, curve: p.curve, drive: p.drive, bias: p.bias, hp: p.hp, lp: p.lp, tone: p.tone, os, mix: p.sat_mix, out_db: p.sat_gain, asym: Some(p.asym[(p.shape.max(0) as usize).min(p.asym.len() - 1)]), steep: true } + } + + pub fn comp_params(p: &BandParams, key_mix: f64) -> CompParams { + CompParams { + thresh: p.thresh, + ratio: p.ratio, + attack: p.attack, + release: p.release, + speed: p.speed, + knee: p.knee, + knee_shape: p.knee_shape, + detector: p.detector, + det_hp: 0.0, + ff_fb: p.ff_fb, + gr_dist: p.gr_dist, + key_mix, + up: p.up >= 1, + down: p.up != 1, + up_range: p.up_range, + } + } + + pub fn latency(&self) -> usize { + self.sat.latency() + self.la_s + } + + pub fn derive(&mut self, p: &BandParams, os: i32, la_s: usize, key_mix: f64, edges: (Edge, Edge), sr: f64, snap: bool, smoothing: bool) { + self.confine.set(edges.0, edges.1, sr, snap); + self.sat.derive(&Self::sat_params(p, os), sr, snap, smoothing); + // Saturator::derive only latches SAT OUT on a snap; the target has to follow the parameter every time + self.sat.set_out_db(p.sat_gain); + self.comp.derive(&Self::comp_params(p, key_mix), sr); + self.la_s = la_s; + self.cmix_t = p.comp_mix * 0.01; + self.cg_t = (p.comp_gain * LN10_20).exp(); + self.on_t = if p.on { 1.0 } else { 0.0 }; + self.sm_c = one_pole(sr, 0.02); + self.on_c = one_pole(sr, 0.01); + self.ms_c = one_pole(sr, 0.5); + if snap { + self.cmix = self.cmix_t; + self.cg = self.cg_t; + self.on_s = self.on_t; + } + } + + pub fn begin_block(&mut self, n: usize) { + self.sat.begin_block(); + self.confine.begin_block(n); + } + + #[inline] + /// `key` = this band's slice of the external key while the sidechain is active (replaces the band's own detector signal + /// according to KEY MIX), aligned with the saturator output. + pub fn tick(&mut self, inp: [f64; 2], smoothing: bool, key: Option<[f64; 2]>) -> StripOut { + self.dry.advance(); + self.dry.put(inp); + let dd = self.dry.tap(self.latency()); + // the saturator's added content stays inside the band (see `confine`); the clean signal bypasses the filter + let (raw, clean) = self.sat.tick_split(inp, smoothing); + let add = self.confine.tick([raw[0] - clean[0], raw[1] - clean[1]]); + let g = self.sat.gain_step(); + let shaped = [clean[0] + add[0], clean[1] + add[1]]; + ms_step(&mut self.ims, inp[0], inp[1], self.ms_c); + ms_step(&mut self.sms, shaped[0], shaped[1], self.ms_c); + let cc = [shaped[0] * g, shaped[1] * g]; + self.sat_pk = self.sat_pk.max(cc[0].abs().max(cc[1].abs())); + self.lk.advance(); + self.lk.put(cc); + let cd = if self.la_s > 0 { self.lk.tap(self.la_s) } else { cc }; + let co = self.comp.tick(cc, cd, key); + if smoothing { + self.cmix += (self.cmix_t - self.cmix) * self.sm_c; + self.cg += (self.cg_t - self.cg) * self.sm_c; + } else { + self.cmix = self.cmix_t; + self.cg = self.cg_t; + } + self.on_s += (self.on_t - self.on_s) * self.on_c; + let mut y = [0.0f64; 2]; + let mut removed = [0.0f64; 2]; + let mut pre = [0.0f64; 2]; + for c in 0..2 { + let w = co.y[c] * self.cg; + let proc = cd[c] + (w - cd[c]) * self.cmix; + y[c] = dd[c] + (proc - dd[c]) * self.on_s; + removed[c] = (cd[c] - co.y[c]) * self.on_s; + pre[c] = dd[c] + (cd[c] - dd[c]) * self.on_s; + } + self.gr_blk = self.gr_blk.max(co.g[0].max(co.g[1])); + self.gl_blk = self.gl_blk.max(co.lift[0].max(co.lift[1])); + StripOut { y, removed, pre, g: co.g[0].max(co.g[1]) } + } +} diff --git a/rust/satxcomp-dsp/src/xover.rs b/rust/satxcomp-dsp/src/xover.rs new file mode 100644 index 0000000..8cdaf9e --- /dev/null +++ b/rust/satxcomp-dsp/src/xover.rs @@ -0,0 +1,436 @@ +//! 4-way Linkwitz-Riley crossover: low / low-mid / high-mid / high that sum back to a flat magnitude (all-pass) response. +//! +//! Split 1 at `f1` (LP = low, HP = rest), split 2 at `f2` on the rest (LP = low-mid, HP = rest), split 3 at `f3` on that rest +//! (LP = high-mid, HP = high). Lower bands take all-passes at the splits they do not pass through, so all four bands have +//! the same phase response and sum flat. +//! Each split has its own slope: 12 / 24 / 48 / 96 dB/oct = Butterworth order m = 1 / 2 / 4 / 8 squared (Linkwitz-Riley). +//! LR2 (12 dB/oct) only sums flat with its high side inverted, so the engine sums the bands with `signs()`; the bands +//! themselves keep their natural polarity (so asymmetric saturation behaves the same at every slope). +//! Coefficients glide linearly over each host block when a frequency or slope moves (no zipper noise while dragging). + +use satcomp_dsp::biquad::{allpass, bq, hp, lp, Coef, IDENTITY}; +use std::f64::consts::PI; + +/// Number of bands (and `NB - 1` crossover splits). +pub const NB: usize = 4; +const NS: usize = NB - 1; + +/// Butterworth section Qs per order (order 1 is a first-order section, handled separately). +const Q2: [f64; 1] = [0.707_106_781_186_547_5]; +const Q4: [f64; 2] = [0.541_196_100_146_197, 1.306_562_964_876_376_4]; +const Q8: [f64; 4] = [0.509_795_579_104_159_3, 0.601_344_886_935_045_2, 0.899_976_223_136_415_6, 2.562_915_447_741_505]; + +/// Number of slope steps and their names (dB/oct). +pub const SLOPES: usize = 4; +pub const SLOPE_DB: [u32; SLOPES] = [12, 24, 48, 96]; +pub(crate) const MAX_SEC: usize = 8; // LR8x2: 4 biquads, squared +const AP_SEC: usize = 4; +/// filter slots: per split an LP chain then an HP chain, then the all-pass chains +/// (low band at splits 2 and 3, low-mid band at split 3) +const fn lp_at(s: usize) -> usize { + 2 * s * MAX_SEC +} +const fn hp_at(s: usize) -> usize { + (2 * s + 1) * MAX_SEC +} +const AP0: usize = 2 * NS * MAX_SEC; +/// all-pass chains: [low @ split 2, low @ split 3, low-mid @ split 3] +const N_AP: usize = 3; +const N: usize = AP0 + N_AP * AP_SEC; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Kind { + Lp, + Hp, + Ap, +} + +fn first_order(kind: Kind, f: f64, sr: f64) -> Coef { + let k = (PI * f.min(sr * 0.45) / sr).tan(); + let a1 = (k - 1.0) / (k + 1.0); + match kind { + Kind::Lp => [k / (k + 1.0), k / (k + 1.0), 0.0, a1, 0.0], + Kind::Hp => [1.0 / (k + 1.0), -1.0 / (k + 1.0), 0.0, a1, 0.0], + Kind::Ap => [a1, 1.0, 0.0, a1, 0.0], + } +} + +fn section(kind: Kind, f: f64, q: f64, sr: f64) -> Coef { + match kind { + Kind::Lp => lp(f, q, sr), + Kind::Hp => hp(f, q, sr), + Kind::Ap => allpass(f, q, sr), + } +} + +/// Fills `out` (unused sections become identity) with the Butterworth order `1 << slope` sections of `kind`, `repeat` times over. +pub(crate) fn fill(out: &mut [Coef], kind: Kind, f: f64, slope: usize, repeat: usize, sr: f64) { + for c in out.iter_mut() { + *c = IDENTITY; + } + let qs: &[f64] = match slope { + 0 => &[], + 1 => &Q2, + 2 => &Q4, + _ => &Q8, + }; + let mut i = 0; + for _ in 0..repeat { + if slope == 0 { + out[i] = first_order(kind, f, sr); + i += 1; + } else { + for &q in qs { + out[i] = section(kind, f, q, sr); + i += 1; + } + } + } +} + +struct Core { + slopes: [usize; NS], + cur: [Coef; N], + tgt: [Coef; N], + delta: [Coef; N], + st: [[[f64; 2]; 2]; N], + ramping: bool, + sign_cur: [f64; NB], + sign_tgt: [f64; NB], + sign_delta: [f64; NB], +} + +impl Core { + fn new() -> Self { + Self { + slopes: [1; NS], + cur: [IDENTITY; N], + tgt: [IDENTITY; N], + delta: [[0.0; 5]; N], + st: [[[0.0; 2]; 2]; N], + ramping: false, + sign_cur: [1.0; NB], + sign_tgt: [1.0; NB], + sign_delta: [0.0; NB], + } + } + + /// New crossover frequencies and slopes (0..3 = 12 / 24 / 48 / 96 dB/oct); `snap` jumps to them (first parameter set), + /// otherwise they glide over the next block. + fn set(&mut self, f: [f64; NS], s: [usize; NS], sr: f64, snap: bool) { + self.slopes = s; + for k in 0..NS { + fill(&mut self.tgt[lp_at(k)..lp_at(k) + MAX_SEC], Kind::Lp, f[k], s[k], 2, sr); + fill(&mut self.tgt[hp_at(k)..hp_at(k) + MAX_SEC], Kind::Hp, f[k], s[k], 2, sr); + } + // all-passes: low band at splits 2 and 3, low-mid band at split 3 + for (i, k) in [1usize, 2, 2].into_iter().enumerate() { + fill(&mut self.tgt[AP0 + i * AP_SEC..AP0 + (i + 1) * AP_SEC], Kind::Ap, f[k], s[k], 1, sr); + } + let g = |k: usize| if s[k] == 0 { -1.0 } else { 1.0 }; + self.sign_tgt = [1.0, g(0), g(0) * g(1), g(0) * g(1) * g(2)]; + if snap { + self.cur = self.tgt; + self.delta = [[0.0; 5]; N]; + self.sign_cur = self.sign_tgt; + self.sign_delta = [0.0; NB]; + self.ramping = false; + } + } + + /// Per host block: ramp towards the targets over `n` samples. + fn begin_block(&mut self, n: usize) { + let rn = 1.0 / n.max(1) as f64; + let mut moving = false; + for f in 0..N { + let mut d = 0.0; + for i in 0..5 { + self.delta[f][i] = (self.tgt[f][i] - self.cur[f][i]) * rn; + d += (self.tgt[f][i] - self.cur[f][i]).abs(); + } + if d < 1e-12 { + self.cur[f] = self.tgt[f]; + self.delta[f] = [0.0; 5]; + } else { + moving = true; + } + } + for b in 0..NB { + let d = self.sign_tgt[b] - self.sign_cur[b]; + if d.abs() < 1e-12 { + self.sign_cur[b] = self.sign_tgt[b]; + self.sign_delta[b] = 0.0; + } else { + self.sign_delta[b] = d * rn; + moving = true; + } + } + self.ramping = moving; + } + + #[inline] + fn run(&mut self, f: usize, c: usize, x: f64) -> f64 { + bq(&mut self.st[f][c], &self.cur[f], x) + } + + #[inline] + fn chain(&mut self, base: usize, len: usize, c: usize, mut x: f64) -> f64 { + for f in base..base + len { + x = self.run(f, c, x); + } + x + } + + /// One stereo sample -> natural-polarity bands (low .. high), each [l, r] (sum them with the engine's `signs()`). + #[inline] + fn tick(&mut self, x: [f64; 2]) -> [[f64; 2]; NB] { + if self.ramping { + for f in 0..N { + for i in 0..5 { + self.cur[f][i] += self.delta[f][i]; + } + } + for b in 0..NB { + self.sign_cur[b] += self.sign_delta[b]; + } + } + let mut out = [[0.0f64; 2]; NB]; + for c in 0..2 { + let low = self.chain(lp_at(0), MAX_SEC, c, x[c]); + let rest1 = self.chain(hp_at(0), MAX_SEC, c, x[c]); + let ml = self.chain(lp_at(1), MAX_SEC, c, rest1); + let rest2 = self.chain(hp_at(1), MAX_SEC, c, rest1); + let mh = self.chain(lp_at(2), MAX_SEC, c, rest2); + let high = self.chain(hp_at(2), MAX_SEC, c, rest2); + let low = self.chain(AP0, AP_SEC, c, low); + out[0][c] = self.chain(AP0 + AP_SEC, AP_SEC, c, low); + out[1][c] = self.chain(AP0 + 2 * AP_SEC, AP_SEC, c, ml); + out[2][c] = mh; + out[3][c] = high; + } + out + } +} + +/// Samples of input history replayed through a freshly built crossover so it starts warm. +const HIST: usize = 4096; +/// Length of the crossfade when a slope changes (about 10 ms at 48 kHz). +const FADE: usize = 512; + +/// The 4-way crossover. A frequency change glides the filter coefficients; a slope change builds the new crossover next to +/// the old one (warmed up on recent input) and crossfades, because the two have different filter structures. +pub struct Crossover4 { + core: Core, + old: Option, + fade: usize, + hist: Box<[[f64; 2]; HIST]>, + hpos: usize, + sign_mix: [f64; NB], +} + +impl Default for Crossover4 { + fn default() -> Self { + Self::new() + } +} + +impl Crossover4 { + pub fn new() -> Self { + Self { core: Core::new(), old: None, fade: 0, hist: Box::new([[0.0; 2]; HIST]), hpos: 0, sign_mix: [1.0; NB] } + } + + /// Clamp the frequencies so f1 < f2 < f3, each at least a 5 % gap above the one below. + pub fn order(f: [f64; NS]) -> [f64; NS] { + let f1 = f[0].clamp(20.0, 18000.0); + let f2 = f[1].max(f1 * 1.05).min(19000.0); + let f3 = f[2].max(f2 * 1.05).min(20000.0); + [f1, f2, f3] + } + + /// Per-band polarity the engine multiplies each band with when summing (-1 only for the 12 dB/oct high sides). + #[inline] + pub fn signs(&self) -> [f64; NB] { + self.sign_mix + } + + /// True when nothing is moving: no coefficient glide and no slope crossfade in progress. + pub fn settled(&self) -> bool { + self.old.is_none() && !self.core.ramping + } + + /// New crossover frequencies and slopes (0..3 = 12 / 24 / 48 / 96 dB/oct); `snap` jumps to them (first parameter set). + /// Otherwise frequencies glide over the next block and a slope change crossfades. + pub fn set(&mut self, freqs: [f64; NS], slopes: [usize; NS], sr: f64, snap: bool) { + let f = Self::order(freqs); + let s = slopes.map(|v| v.min(SLOPES - 1)); + if snap { + self.old = None; + self.core.set(f, s, sr, true); + self.sign_mix = self.core.sign_cur; + } else if s != self.core.slopes { + let mut fresh = Core::new(); + fresh.set(f, s, sr, true); + // warm it up on the last HIST input samples, oldest first + for k in 0..HIST { + let _ = fresh.tick(self.hist[(self.hpos + k) % HIST]); + } + self.old = Some(std::mem::replace(&mut self.core, fresh)); + self.fade = 0; + } else { + self.core.set(f, s, sr, false); + } + } + + /// Per host block: ramp towards the targets over `n` samples. + pub fn begin_block(&mut self, n: usize) { + self.core.begin_block(n); + if let Some(o) = self.old.as_mut() { + o.begin_block(n); + } + } + + /// One stereo sample -> natural-polarity bands (low .. high), each [l, r] (sum them with `signs()`). + #[inline] + pub fn tick(&mut self, x: [f64; 2]) -> [[f64; 2]; NB] { + self.hist[self.hpos] = x; + self.hpos = (self.hpos + 1) % HIST; + let new = self.core.tick(x); + let Some(old) = self.old.as_mut() else { + self.sign_mix = self.core.sign_cur; + return new; + }; + let a = (self.fade + 1) as f64 / FADE as f64; + let prev = old.tick(x); + let mut out = [[0.0f64; 2]; NB]; + for b in 0..NB { + for c in 0..2 { + out[b][c] = prev[b][c] + (new[b][c] - prev[b][c]) * a; + } + self.sign_mix[b] = old.sign_cur[b] + (self.core.sign_cur[b] - old.sign_cur[b]) * a; + } + self.fade += 1; + if self.fade >= FADE { + self.old = None; + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SR: f64 = 48000.0; + const F: [f64; NS] = [200.0, 1200.0, 5000.0]; + + fn impulse_response(f: [f64; NS], s: [usize; NS]) -> ([Vec; NB], [f64; NB]) { + let mut x = Crossover4::new(); + x.set(f, s, SR, true); + x.begin_block(1); + let mut r: [Vec; NB] = Default::default(); + for i in 0..16384 { + let o = x.tick([if i == 0 { 1.0 } else { 0.0 }, 0.0]); + for b in 0..NB { + r[b].push(o[b][0]); + } + } + (r, x.signs()) + } + + fn mag(ir: &[f64], f: f64) -> f64 { + let (mut re, mut im) = (0.0, 0.0); + for (n, v) in ir.iter().enumerate() { + let w = 2.0 * std::f64::consts::PI * f * n as f64 / SR; + re += v * w.cos(); + im -= v * w.sin(); + } + (re * re + im * im).sqrt() + } + + #[test] + fn bands_sum_to_a_flat_magnitude_at_every_slope_combination() { + for s1 in 0..SLOPES { + for s2 in 0..SLOPES { + for s3 in 0..SLOPES { + // every combination, thinned: all uniform ones plus a spread of mixed ones + if !((s1 == s2 && s2 == s3) || (s1 + 2 * s2 + 3 * s3) % 5 == 0) { + continue; + } + let (ir, sg) = impulse_response(F, [s1, s2, s3]); + let sum: Vec = (0..ir[0].len()).map(|i| (0..NB).map(|b| ir[b][i] * sg[b]).sum()).collect(); + for f in [30.0, 100.0, 200.0, 600.0, 1200.0, 3000.0, 5000.0, 9000.0, 15000.0] { + let db = 20.0 * mag(&sum, f).log10(); + assert!(db.abs() < 0.05, "slopes {s1}/{s2}/{s3} at {f} Hz: {db} dB"); + } + } + } + } + } + + #[test] + fn only_the_12_db_splits_invert_their_high_side() { + for (s, want) in [ + ([0, 0, 0], [1.0, -1.0, 1.0, -1.0]), + ([1, 1, 1], [1.0, 1.0, 1.0, 1.0]), + ([0, 2, 1], [1.0, -1.0, -1.0, -1.0]), + ([3, 0, 2], [1.0, 1.0, -1.0, -1.0]), + ([1, 1, 0], [1.0, 1.0, 1.0, -1.0]), + ] { + let (_, sg) = impulse_response(F, s); + assert_eq!(sg, want, "slopes {s:?}"); + } + } + + #[test] + fn each_band_is_minus_6db_at_its_crossover_and_slope_sets_the_rejection() { + let mut rej = [0.0f64; SLOPES]; + for s in 0..SLOPES { + let (ir, _) = impulse_response(F, [s; NS]); + let db = |b: usize, f: f64| 20.0 * mag(&ir[b], f).log10(); + for (k, f) in F.iter().enumerate() { + // the inner splits sit close to their neighbours' skirts, so they may stray a little further from -6 dB + let tol = if k == 0 { 0.3 } else { 1.2 }; + assert!((db(k, *f) + 6.02).abs() < tol && (db(k + 1, *f) + 6.02).abs() < tol, "slope {s} split {k}: {} / {}", db(k, *f), db(k + 1, *f)); + } + rej[s] = db(0, 800.0); // two octaves above the low crossover + // roughly the nominal dB/oct over the two octaves (less the 6 dB at the corner) + let want = -(SLOPE_DB[s] as f64) * 2.0; + assert!(rej[s] < want * 0.6 && rej[s] > want * 1.4 - 8.0, "slope {s}: {} dB at 4x, nominal {want}", rej[s]); + } + assert!(rej.windows(2).all(|w| w[1] < w[0] - 6.0), "steeper slopes must reject more: {rej:?}"); + } + + #[test] + fn gliding_frequencies_and_slopes_stay_finite_and_settle() { + let mut x = Crossover4::new(); + x.set([150.0, 900.0, 3500.0], [1; NS], SR, true); + let (mut peak, mut settled) = (0.0f64, 0.0f64); + for blk in 0..400 { + if blk == 50 { + x.set([400.0, 2000.0, 6000.0], [2, 0, 1], SR, false); + } + x.begin_block(64); + for i in 0..64 { + let s = (2.0 * std::f64::consts::PI * 330.0 * (blk * 64 + i) as f64 / SR).sin(); + let o = x.tick([s, s]); + let sg = x.signs(); + let sum: f64 = (0..NB).map(|b| o[b][0] * sg[b]).sum(); + assert!(sum.is_finite()); + if blk < 100 { + peak = peak.max(sum.abs()); // while the crossover moves (a swept tone overshoots a little) + } else if blk >= 380 { + settled = settled.max(sum.abs()); + } + } + } + assert!(peak < 2.0, "{peak}"); + assert!((settled - 1.0).abs() < 0.02, "{settled}"); + assert!(x.settled()); + } + + #[test] + fn order_keeps_each_split_above_the_one_below() { + let [a, b, c] = Crossover4::order([3000.0, 100.0, 50.0]); + assert!(b >= a * 1.05 && c >= b * 1.05); + } +} diff --git a/rust/satxcomp-plugin/Cargo.toml b/rust/satxcomp-plugin/Cargo.toml new file mode 100644 index 0000000..b6ed363 --- /dev/null +++ b/rust/satxcomp-plugin/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "satxcomp" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-or-later" +publish = false + +[lib] +crate-type = ["cdylib", "lib"] + +[dependencies] +nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", features = ["vst3"] } +satcomp-dsp = { path = "../satcomp-dsp" } +satxcomp-dsp = { path = "../satxcomp-dsp" } +satcomp-ui = { path = "../satcomp-ui" } +nih_plug_egui = { path = "../vendor/nih_plug_egui" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +parking_lot = "0.12" +include_dir = "0.7" + +[target.'cfg(any(target_os = "macos", windows))'.dependencies] +rfd = { version = "0.15", default-features = false } + +[features] +# `cargo run -p satxcomp --features standalone --bin satxcomp-standalone` opens the editor in a plain window (dev aid) +standalone = ["nih_plug/standalone"] + +[[bin]] +name = "satxcomp-standalone" +path = "src/standalone.rs" +required-features = ["standalone"] diff --git a/rust/satxcomp-plugin/presets/.gitkeep b/rust/satxcomp-plugin/presets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/rust/satxcomp-plugin/presets/DRUMS_Smiley.json b/rust/satxcomp-plugin/presets/DRUMS_Smiley.json new file mode 100644 index 0000000..254546d --- /dev/null +++ b/rust/satxcomp-plugin/presets/DRUMS_Smiley.json @@ -0,0 +1,144 @@ +{ + "format": "satxcomp-preset", + "version": 1, + "name": "DRUMS_Smiley", + "params": { + "eq1_freq": 50.0, + "eq1_gain": 0.0, + "eq1_on": 1.0, + "eq1_q": 1.39, + "eq1_type": 0.0, + "eq2_freq": 224.0, + "eq2_gain": -5.9, + "eq2_on": 1.0, + "eq2_q": 1.65, + "eq2_type": 2.0, + "eq3_freq": 1000.0, + "eq3_gain": 0.0, + "eq3_on": 0.0, + "eq3_q": 0.71, + "eq3_type": 2.0, + "eq4_freq": 1587.0, + "eq4_gain": 3.0, + "eq4_on": 1.0, + "eq4_q": 0.71, + "eq4_type": 2.0, + "eq5_freq": 9107.0, + "eq5_gain": 2.1, + "eq5_on": 1.0, + "eq5_q": 0.71, + "eq5_type": 1.0, + "eq_bypass": 0.0, + "eq_gain": -1.4, + "eq_mix": 100.0, + "eq_pivot": 600.0, + "eq_tilt": 0.0, + "hi_attack": 10.0, + "hi_bias": 0.0, + "hi_comp_gain": 0.0, + "hi_comp_mix": 100.0, + "hi_delta": 0.0, + "hi_detector": 30.0, + "hi_drive": 0.0, + "hi_ff_fb": 0.0, + "hi_gr_dist": 0.0, + "hi_hp": 20.0, + "hi_knee": 6.0, + "hi_knee_shape": 0.0, + "hi_lp": 20000.0, + "hi_on": 1.0, + "hi_ratio": 4.0, + "hi_release": 150.0, + "hi_sat_gain": 0.0, + "hi_sat_mix": 100.0, + "hi_shape": 0.0, + "hi_solo": 0.0, + "hi_speed": 50.0, + "hi_thresh": 0.0, + "hi_tone": 20000.0, + "lim_on": 1.0, + "lo_attack": 55.01, + "lo_bias": 0.0, + "lo_comp_gain": 4.8, + "lo_comp_mix": 100.0, + "lo_delta": 0.0, + "lo_detector": 30.0, + "lo_drive": 39.5, + "lo_ff_fb": 0.0, + "lo_gr_dist": 0.0, + "lo_hp": 20.0, + "lo_knee": 6.0, + "lo_knee_shape": 0.0, + "lo_lp": 20000.0, + "lo_on": 1.0, + "lo_ratio": 2.0, + "lo_release": 242.0, + "lo_sat_gain": -5.0, + "lo_sat_mix": 100.0, + "lo_shape": 3.0, + "lo_solo": 0.0, + "lo_speed": 50.0, + "lo_thresh": -21.3, + "lo_tone": 20000.0, + "lookahead": 0.0, + "mh_attack": 9.09, + "mh_bias": 0.0, + "mh_comp_gain": 0.0, + "mh_comp_mix": 100.0, + "mh_delta": 0.0, + "mh_detector": 30.0, + "mh_drive": 18.5, + "mh_ff_fb": 0.0, + "mh_gr_dist": 0.0, + "mh_hp": 20.0, + "mh_knee": 6.0, + "mh_knee_shape": 0.0, + "mh_lp": 20000.0, + "mh_on": 1.0, + "mh_ratio": 4.0, + "mh_release": 24.0, + "mh_sat_gain": 0.0, + "mh_sat_mix": 100.0, + "mh_shape": 5.0, + "mh_solo": 0.0, + "mh_speed": 50.0, + "mh_thresh": -24.7, + "mh_tone": 20000.0, + "mid_attack": 10.0, + "mid_bias": 0.0, + "mid_comp_gain": 0.0, + "mid_comp_mix": 100.0, + "mid_delta": 0.0, + "mid_detector": 30.0, + "mid_drive": 0.0, + "mid_ff_fb": 0.0, + "mid_gr_dist": 0.0, + "mid_hp": 20.0, + "mid_knee": 6.0, + "mid_knee_shape": 0.0, + "mid_lp": 20000.0, + "mid_on": 1.0, + "mid_ratio": 4.0, + "mid_release": 150.0, + "mid_sat_gain": 0.0, + "mid_sat_mix": 100.0, + "mid_shape": 0.0, + "mid_solo": 0.0, + "mid_speed": 50.0, + "mid_thresh": 0.0, + "mid_tone": 20000.0, + "mix": 100.0, + "os": 0.0, + "out_gain": 0.0, + "sc_gain": 0.0, + "sc_hp": 20.0, + "sc_lp": 20000.0, + "sc_mix": 100.0, + "x1": 233.0, + "x1_slope": 1.0, + "x2": 800.0, + "x2_slope": 1.0, + "x3": 4085.0, + "x3_slope": 1.0 + } +} diff --git a/rust/satxcomp-plugin/presets/DRUMS_UTubes.json b/rust/satxcomp-plugin/presets/DRUMS_UTubes.json new file mode 100644 index 0000000..877077b --- /dev/null +++ b/rust/satxcomp-plugin/presets/DRUMS_UTubes.json @@ -0,0 +1,144 @@ +{ + "format": "satxcomp-preset", + "version": 1, + "name": "DRUMS_UTubes", + "params": { + "eq1_freq": 80.0, + "eq1_gain": 0.0, + "eq1_on": 1.0, + "eq1_q": 0.71, + "eq1_type": 1.0, + "eq2_freq": 200.0, + "eq2_gain": 0.0, + "eq2_on": 1.0, + "eq2_q": 0.71, + "eq2_type": 2.0, + "eq3_freq": 1000.0, + "eq3_gain": 0.0, + "eq3_on": 0.0, + "eq3_q": 0.71, + "eq3_type": 2.0, + "eq4_freq": 5000.0, + "eq4_gain": 0.0, + "eq4_on": 0.0, + "eq4_q": 0.71, + "eq4_type": 2.0, + "eq5_freq": 10000.0, + "eq5_gain": 0.0, + "eq5_on": 1.0, + "eq5_q": 0.71, + "eq5_type": 1.0, + "eq_bypass": 0.0, + "eq_gain": 0.0, + "eq_mix": 100.0, + "eq_pivot": 600.0, + "eq_tilt": 0.0, + "hi_attack": 2.04, + "hi_bias": 0.0, + "hi_comp_gain": 1.2, + "hi_comp_mix": 100.0, + "hi_delta": 0.0, + "hi_detector": 0.0, + "hi_drive": 12.5, + "hi_ff_fb": 0.0, + "hi_gr_dist": 0.0, + "hi_hp": 20.0, + "hi_knee": 0.0, + "hi_knee_shape": 0.0, + "hi_lp": 20000.0, + "hi_on": 1.0, + "hi_ratio": 4.0, + "hi_release": 38.0, + "hi_sat_gain": 0.0, + "hi_sat_mix": 100.0, + "hi_shape": 0.0, + "hi_solo": 0.0, + "hi_speed": 0.0, + "hi_thresh": -23.8, + "hi_tone": 20000.0, + "lim_on": 1.0, + "lo_attack": 42.09, + "lo_bias": 0.0, + "lo_comp_gain": 4.0, + "lo_comp_mix": 100.0, + "lo_delta": 0.0, + "lo_detector": 30.0, + "lo_drive": 20.5, + "lo_ff_fb": 0.0, + "lo_gr_dist": 0.0, + "lo_hp": 20.0, + "lo_knee": 6.0, + "lo_knee_shape": 0.0, + "lo_lp": 20000.0, + "lo_on": 1.0, + "lo_ratio": 4.0, + "lo_release": 268.0, + "lo_sat_gain": -5.0, + "lo_sat_mix": 100.0, + "lo_shape": 0.0, + "lo_solo": 0.0, + "lo_speed": 50.0, + "lo_thresh": -17.6, + "lo_tone": 20000.0, + "lookahead": 0.0, + "mh_attack": 10.41, + "mh_bias": 0.0, + "mh_comp_gain": 0.0, + "mh_comp_mix": 100.0, + "mh_delta": 0.0, + "mh_detector": 15.0, + "mh_drive": 39.5, + "mh_ff_fb": 0.0, + "mh_gr_dist": 0.0, + "mh_hp": 20.0, + "mh_knee": 6.0, + "mh_knee_shape": 0.0, + "mh_lp": 20000.0, + "mh_on": 1.0, + "mh_ratio": 4.0, + "mh_release": 20.0, + "mh_sat_gain": 0.0, + "mh_sat_mix": 30.0, + "mh_shape": 0.0, + "mh_solo": 0.0, + "mh_speed": 15.0, + "mh_thresh": -26.6, + "mh_tone": 20000.0, + "mid_attack": 10.07, + "mid_bias": 0.0, + "mid_comp_gain": 0.0, + "mid_comp_mix": 100.0, + "mid_delta": 0.0, + "mid_detector": 30.0, + "mid_drive": 21.0, + "mid_ff_fb": 0.0, + "mid_gr_dist": 0.0, + "mid_hp": 20.0, + "mid_knee": 6.0, + "mid_knee_shape": 0.0, + "mid_lp": 20000.0, + "mid_on": 1.0, + "mid_ratio": 4.0, + "mid_release": 150.0, + "mid_sat_gain": 0.0, + "mid_sat_mix": 100.0, + "mid_shape": 0.0, + "mid_solo": 0.0, + "mid_speed": 50.0, + "mid_thresh": -21.8, + "mid_tone": 20000.0, + "mix": 100.0, + "os": 0.0, + "out_gain": 0.0, + "sc_gain": 0.0, + "sc_hp": 20.0, + "sc_lp": 20000.0, + "sc_mix": 100.0, + "x1": 150.0, + "x1_slope": 1.0, + "x2": 800.0, + "x2_slope": 1.0, + "x3": 4998.0, + "x3_slope": 1.0 + } +} diff --git a/rust/satxcomp-plugin/presets/Deep_n_Bright.json b/rust/satxcomp-plugin/presets/Deep_n_Bright.json new file mode 100644 index 0000000..13daa17 --- /dev/null +++ b/rust/satxcomp-plugin/presets/Deep_n_Bright.json @@ -0,0 +1,144 @@ +{ + "format": "satxcomp-preset", + "version": 1, + "name": "Deep n Bright", + "params": { + "eq1_freq": 80.0, + "eq1_gain": 0.0, + "eq1_on": 1.0, + "eq1_q": 0.71, + "eq1_type": 1.0, + "eq2_freq": 200.0, + "eq2_gain": 0.0, + "eq2_on": 1.0, + "eq2_q": 0.71, + "eq2_type": 2.0, + "eq3_freq": 1000.0, + "eq3_gain": 0.0, + "eq3_on": 0.0, + "eq3_q": 0.71, + "eq3_type": 2.0, + "eq4_freq": 5000.0, + "eq4_gain": 0.0, + "eq4_on": 0.0, + "eq4_q": 0.71, + "eq4_type": 2.0, + "eq5_freq": 10000.0, + "eq5_gain": 0.0, + "eq5_on": 1.0, + "eq5_q": 0.71, + "eq5_type": 1.0, + "eq_bypass": 0.0, + "eq_gain": 0.0, + "eq_mix": 100.0, + "eq_pivot": 600.0, + "eq_tilt": 0.0, + "hi_attack": 10.0, + "hi_bias": 0.0, + "hi_comp_gain": 0.0, + "hi_comp_mix": 100.0, + "hi_delta": 0.0, + "hi_detector": 30.0, + "hi_drive": 0.0, + "hi_ff_fb": 0.0, + "hi_gr_dist": 0.0, + "hi_hp": 20.0, + "hi_knee": 6.0, + "hi_knee_shape": 0.0, + "hi_lp": 20000.0, + "hi_on": 1.0, + "hi_ratio": 4.0, + "hi_release": 150.0, + "hi_sat_gain": 0.0, + "hi_sat_mix": 100.0, + "hi_shape": 0.0, + "hi_solo": 0.0, + "hi_speed": 50.0, + "hi_thresh": 0.0, + "hi_tone": 20000.0, + "lim_on": 1.0, + "lo_attack": 49.07, + "lo_bias": 0.0, + "lo_comp_gain": 7.5, + "lo_comp_mix": 100.0, + "lo_delta": 0.0, + "lo_detector": 69.0, + "lo_drive": 26.0, + "lo_ff_fb": 0.0, + "lo_gr_dist": 0.0, + "lo_hp": 20.0, + "lo_knee": 6.0, + "lo_knee_shape": 0.0, + "lo_lp": 20000.0, + "lo_on": 1.0, + "lo_ratio": 4.0, + "lo_release": 175.0, + "lo_sat_gain": 0.0, + "lo_sat_mix": 100.0, + "lo_shape": 1.0, + "lo_solo": 0.0, + "lo_speed": 85.0, + "lo_thresh": -30.8, + "lo_tone": 20000.0, + "lookahead": 0.0, + "mh_attack": 5.05, + "mh_bias": 0.0, + "mh_comp_gain": 5.5, + "mh_comp_mix": 50.0, + "mh_delta": 0.0, + "mh_detector": 30.0, + "mh_drive": 14.5, + "mh_ff_fb": 0.0, + "mh_gr_dist": 0.0, + "mh_hp": 20.0, + "mh_knee": 6.0, + "mh_knee_shape": 0.0, + "mh_lp": 20000.0, + "mh_on": 1.0, + "mh_ratio": 4.0, + "mh_release": 27.0, + "mh_sat_gain": 0.0, + "mh_sat_mix": 65.0, + "mh_shape": 8.0, + "mh_solo": 0.0, + "mh_speed": 50.0, + "mh_thresh": -31.4, + "mh_tone": 20000.0, + "mid_attack": 10.0, + "mid_bias": 0.0, + "mid_comp_gain": 0.0, + "mid_comp_mix": 100.0, + "mid_delta": 0.0, + "mid_detector": 30.0, + "mid_drive": 0.0, + "mid_ff_fb": 0.0, + "mid_gr_dist": 0.0, + "mid_hp": 20.0, + "mid_knee": 6.0, + "mid_knee_shape": 0.0, + "mid_lp": 20000.0, + "mid_on": 1.0, + "mid_ratio": 4.0, + "mid_release": 150.0, + "mid_sat_gain": 0.0, + "mid_sat_mix": 100.0, + "mid_shape": 0.0, + "mid_solo": 0.0, + "mid_speed": 50.0, + "mid_thresh": 0.0, + "mid_tone": 20000.0, + "mix": 100.0, + "os": 0.0, + "out_gain": 0.0, + "sc_gain": 0.0, + "sc_hp": 20.0, + "sc_lp": 20000.0, + "sc_mix": 100.0, + "x1": 284.0, + "x1_slope": 1.0, + "x2": 800.0, + "x2_slope": 1.0, + "x3": 4419.0, + "x3_slope": 1.0 + } +} diff --git a/rust/satxcomp-plugin/presets/Mildly_Cooked.json b/rust/satxcomp-plugin/presets/Mildly_Cooked.json new file mode 100644 index 0000000..5a4f7f4 --- /dev/null +++ b/rust/satxcomp-plugin/presets/Mildly_Cooked.json @@ -0,0 +1,202 @@ +{ + "format": "satxcomp-preset", + "version": 1, + "name": "Mildly Cooked", + "params": { + "eq1_freq": 80.0, + "eq1_gain": 0.0, + "eq1_on": 1.0, + "eq1_q": 0.71, + "eq1_type": 1.0, + "eq2_freq": 200.0, + "eq2_gain": 0.0, + "eq2_on": 1.0, + "eq2_q": 0.71, + "eq2_type": 2.0, + "eq3_freq": 1000.0, + "eq3_gain": 0.0, + "eq3_on": 0.0, + "eq3_q": 0.71, + "eq3_type": 2.0, + "eq4_freq": 5000.0, + "eq4_gain": 0.0, + "eq4_on": 0.0, + "eq4_q": 0.71, + "eq4_type": 2.0, + "eq5_freq": 10000.0, + "eq5_gain": 0.0, + "eq5_on": 1.0, + "eq5_q": 0.71, + "eq5_type": 1.0, + "eq_bypass": 0.0, + "eq_gain": 0.0, + "eq_mix": 100.0, + "eq_pivot": 600.0, + "eq_tilt": 0.0, + "hi_attack": 1.13, + "hi_bias": 0.0, + "hi_comp_gain": 0.0, + "hi_comp_mix": 100.0, + "hi_delta": 0.0, + "hi_detector": 36.0, + "hi_drive": 22.5, + "hi_ff_fb": 0.0, + "hi_gr_dist": 0.0, + "hi_hp": 20.0, + "hi_knee": 6.0, + "hi_knee_shape": 0.0, + "hi_lp": 20000.0, + "hi_on": 1.0, + "hi_ratio": 2.0, + "hi_release": 11.0, + "hi_sat_gain": 0.0, + "hi_sat_mix": 100.0, + "hi_shape": 2.0, + "hi_solo": 0.0, + "hi_speed": 50.0, + "hi_thresh": -21.8, + "hi_tone": 20000.0, + "lim_on": 1.0, + "lo_attack": 45.05, + "lo_bias": 0.0, + "lo_comp_gain": 7.3, + "lo_comp_mix": 100.0, + "lo_delta": 0.0, + "lo_detector": 30.0, + "lo_drive": 28.5, + "lo_ff_fb": 0.0, + "lo_gr_dist": 0.0, + "lo_hp": 20.0, + "lo_knee": 6.0, + "lo_knee_shape": 0.0, + "lo_lp": 20000.0, + "lo_on": 1.0, + "lo_ratio": 4.0, + "lo_release": 272.0, + "lo_sat_gain": 0.0, + "lo_sat_mix": 100.0, + "lo_shape": 5.0, + "lo_solo": 0.0, + "lo_speed": 50.0, + "lo_thresh": -25.6, + "lo_tone": 20000.0, + "lookahead": 0.0, + "mh_attack": 14.71, + "mh_bias": 12.0, + "mh_comp_gain": 4.1, + "mh_comp_mix": 100.0, + "mh_delta": 0.0, + "mh_detector": 30.0, + "mh_drive": 30.5, + "mh_ff_fb": 36.0, + "mh_gr_dist": 0.0, + "mh_hp": 20.0, + "mh_knee": 6.0, + "mh_knee_shape": 0.0, + "mh_lp": 20000.0, + "mh_on": 1.0, + "mh_ratio": 4.0, + "mh_release": 54.0, + "mh_sat_gain": 0.0, + "mh_sat_mix": 50.0, + "mh_shape": 14.0, + "mh_solo": 0.0, + "mh_speed": 0.0, + "mh_thresh": -21.2, + "mh_tone": 20000.0, + "mid_attack": 20.69, + "mid_bias": 0.0, + "mid_comp_gain": 8.3, + "mid_comp_mix": 51.0, + "mid_delta": 0.0, + "mid_detector": 30.0, + "mid_drive": 0.0, + "mid_ff_fb": 0.0, + "mid_gr_dist": 0.0, + "mid_hp": 20.0, + "mid_knee": 6.0, + "mid_knee_shape": 0.0, + "mid_lp": 20000.0, + "mid_on": 1.0, + "mid_ratio": 4.0, + "mid_release": 302.0, + "mid_sat_gain": 0.0, + "mid_sat_mix": 100.0, + "mid_shape": 0.0, + "mid_solo": 0.0, + "mid_speed": 50.0, + "mid_thresh": -40.0, + "mid_tone": 20000.0, + "mix": 100.0, + "os": 0.0, + "out_gain": 0.0, + "sc_gain": 0.0, + "sc_hp": 20.0, + "sc_lp": 20000.0, + "sc_mix": 100.0, + "x1": 200.0, + "x1_slope": 1.0, + "x2": 310.0, + "x2_slope": 1.0, + "x3": 2861.0, + "x3_slope": 1.0 + }, + "curves": [ + [ + [ + -1.0, + -1.0 + ], + [ + 1.0, + 1.0 + ] + ], + [ + [ + -1.0, + -1.0 + ], + [ + 1.0, + 1.0 + ] + ], + [ + [ + -1.0, + -1.0 + ], + [ + -0.8258, + 0.8557 + ], + [ + -0.3183, + -0.0942 + ], + [ + 0.3183, + 0.0942 + ], + [ + 0.8258, + -0.8557 + ], + [ + 1.0, + 1.0 + ] + ], + [ + [ + -1.0, + -1.0 + ], + [ + 1.0, + 1.0 + ] + ] + ] +} diff --git a/rust/satxcomp-plugin/presets/README.md b/rust/satxcomp-plugin/presets/README.md new file mode 100644 index 0000000..6360149 --- /dev/null +++ b/rust/satxcomp-plugin/presets/README.md @@ -0,0 +1,12 @@ +# Factory presets + +Every `*.json` file in this folder is embedded into the plug-in at build time and listed under FACTORY +in the preset dropdown (sorted by file name; `INIT` is always first and built in). + +To make one: dial the sound in, click the save icon in the preset bar, save the file, rename the copy to +`NN name.json`-style if you want an order, drop it here and rebuild. + +Format: `{ "format": "satxcomp-preset", "version": 1, "name": "...", "params": { "": , ... }, +"curves": [[[x, y], ...], [...], [...]] }`. Parameter ids are the ones in `src/params.rs`; missing ids fall back to +the default. `curves` (optional) holds the custom waveshaper curve of the low, mid and high band; absent = linear. +Bypass and Gain Match are never stored (performance switches). The Sidechain switch (`sc_on`) is stored when a preset is saved but only applied when the preset has the key, so a sidechain preset comes back keyed while older presets and INIT leave the switch alone (it depends on the track's routing). diff --git a/rust/satxcomp-plugin/src/gui/mod.rs b/rust/satxcomp-plugin/src/gui/mod.rs new file mode 100644 index 0000000..f8f391d --- /dev/null +++ b/rust/satxcomp-plugin/src/gui/mod.rs @@ -0,0 +1,65 @@ +//! SatXComp editor: egui on the shared satcomp-ui canvas / widget kit, same logical-grid approach as SatComp. + +mod ui; +#[cfg(test)] +mod smoke; + +use crate::params::SatXCompParams; +use crate::Shared; +use nih_plug::prelude::Editor; +use nih_plug_egui::create_egui_editor; +use nih_plug_egui::egui::{self, LayerId}; +use satcomp_ui::canvas::Canvas; +use satcomp_ui::init_ctx; +use std::sync::Arc; +use std::time::Duration; +use ui::{Env, Gui, State}; + +/// Logical grid (units); the window scales it in quarter steps. +pub const W: f32 = 664.0; +pub const H: f32 = 400.0; + +/// One editor frame: map the egui input into logical canvas units, draw the whole UI. +pub(crate) fn run_frame(ctx: &egui::Context, setter: &nih_plug::prelude::ParamSetter, st: &mut State, params: &SatXCompParams, shared: &Shared) { + let screen = ctx.screen_rect(); + let s = ((screen.width() / W).min(screen.height() / H) * 4.0).floor() / 4.0; + let s = s.max(0.5); + let ox = ((screen.width() - W * s) * 0.5).floor(); + let oy = ((screen.height() - H * s) * 0.5).floor(); + let ppp = ctx.pixels_per_point(); + let (pos, down, rdown, scroll, shift, now) = ctx.input(|i| { + (i.pointer.latest_pos(), i.pointer.primary_down(), i.pointer.secondary_down(), i.raw_scroll_delta.y, i.modifiers.shift, i.time) + }); + let (mx, my) = match pos { + Some(p) => ((p.x - ox) / s, (p.y - oy) / s), + None => (-1000.0, -1000.0), + }; + st.set_input(mx, my, down, rdown, scroll, shift, now); + st.ptr_pt = pos.map(|p| (p.x, p.y)).unwrap_or((0.0, 0.0)); + st.win_pt = (screen.width(), screen.height()); + let painter = ctx.layer_painter(LayerId::background()); + let cv = Canvas::new(&painter, ppp, ox, oy, s, st.colors(), st.face); + painter.rect_filled(screen, 0.0, cv.bg_color()); + // Theme editor: the whole window is a static page (default params, constant meter values); the real params and + // shared state are not touched. + let (dp, ds) = (st.dummy_params.clone(), st.dummy_shared.clone()); + let editing = st.app.editing(); + if editing { + st.fill_dummy(); + } + let (pr, sr): (&SatXCompParams, &Shared) = if editing { (&*dp, &*ds) } else { (params, shared) }; + let env = Env { params: pr, setter, shared: sr, dsp: pr.to_dsp() }; + let mut g = Gui { s: st, cv, env }; + g.frame(); + ctx.request_repaint_after(Duration::from_millis(16)); +} + +pub fn create(params: Arc, shared: Arc) -> Option> { + let state = State::new(¶ms); + let editor_state = params.editor_state.clone(); + let look_params = params.clone(); + create_egui_editor(editor_state, state, move |ctx, st| { + init_ctx(ctx); + st.sync_look(&look_params); + }, move |ctx, setter, st| run_frame(ctx, setter, st, ¶ms, &shared)) +} diff --git a/rust/satxcomp-plugin/src/gui/smoke.rs b/rust/satxcomp-plugin/src/gui/smoke.rs new file mode 100644 index 0000000..2a634d6 --- /dev/null +++ b/rust/satxcomp-plugin/src/gui/smoke.rs @@ -0,0 +1,707 @@ +//! Headless smoke test of the editor: drives both pages with a scripted mouse against a recording fake host and checks that +//! it neither panics nor behaves non-deterministically, and that the expected parameter writes happen. +//! (nih-plug keeps its parameter setters crate-private, so values are not echoed back; the host write log is what is checked.) + +use super::ui::State; +use crate::params::SatXCompParams; +use crate::Shared; +use nih_plug::prelude::*; +use nih_plug_egui::egui::{self, Event, Modifiers, PointerButton, Pos2, RawInput, Rect, Vec2}; +use std::sync::Arc; + +#[derive(Default)] +struct FakeHost { + log: parking_lot::Mutex>, +} + +impl GuiContext for FakeHost { + fn plugin_api(&self) -> PluginApi { + PluginApi::Vst3 + } + fn request_resize(&self) -> bool { + true + } + unsafe fn raw_begin_set_parameter(&self, _p: ParamPtr) {} + unsafe fn raw_set_parameter_normalized(&self, p: ParamPtr, n: f32) { + self.log.lock().push(format!("{} {:.3}", p.name(), n)); + } + unsafe fn raw_end_set_parameter(&self, _p: ParamPtr) {} + fn get_state(&self) -> nih_plug::wrapper::state::PluginState { + nih_plug::wrapper::state::PluginState { version: String::new(), params: Default::default(), fields: Default::default() } + } + fn set_state(&self, _s: nih_plug::wrapper::state::PluginState) {} +} + +struct Rig { + ctx: egui::Context, + host: Arc, + params: Arc, + shared: Arc, + st: State, + t: f64, + hash: u64, +} + +impl Rig { + fn new() -> Self { + Self::with_params(|_| {}) + } + + /// A rig whose parameters start from `tweak` (nih-plug's setters are sealed, so state is set before the params are shared). + fn with_params(tweak: impl FnOnce(&mut SatXCompParams)) -> Self { + let ctx = egui::Context::default(); + satcomp_ui::init_ctx(&ctx); + let mut p = SatXCompParams::from_defaults(None); // hermetic: ignore this machine's defaults file + tweak(&mut p); + let params = Arc::new(p); + Self { ctx, host: Arc::new(FakeHost::default()), shared: Arc::new(Shared::new()), st: State::new(¶ms), params, t: 1.0, hash: 0xcbf29ce484222325 } + } + + fn frame(&mut self, events: Vec) { + self.t += 0.03; + // some audio-side telemetry so meters and the spectrum draw + let n = (self.t * 10.0) as f32; + self.shared.opk[0].store(0.5 + 0.3 * n.sin(), std::sync::atomic::Ordering::Relaxed); + self.shared.gr_pk[1].store(4.0 + n.cos().abs() * 3.0, std::sync::atomic::Ordering::Relaxed); + for i in 0..8192usize { + let v = 0.3 * ((i as f32 + n * 13.0) * 0.05).sin(); + self.shared.tap_out.buf[i].store(v.to_bits(), std::sync::atomic::Ordering::Relaxed); + self.shared.tap_dry.buf[i].store((v * 1.4).to_bits(), std::sync::atomic::Ordering::Relaxed); + } + self.shared.tap_out.w.store(8192, std::sync::atomic::Ordering::Relaxed); + self.shared.tap_dry.w.store(8192, std::sync::atomic::Ordering::Relaxed); + let raw = RawInput { time: Some(self.t), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(996.0, 600.0))), events, ..Default::default() }; + let setter = ParamSetter::new(&*self.host); + let (p, sh) = (self.params.clone(), self.shared.clone()); + let st = &mut self.st; + let full = self.ctx.run(raw, |ctx| super::run_frame(ctx, &setter, st, &p, &sh)); + for b in format!("{:?}", full.shapes).bytes() { + self.hash ^= b as u64; + self.hash = self.hash.wrapping_mul(0x100000001b3); + } + } + + /// logical (1.5 px per unit) position + fn at(x: f32, y: f32) -> Pos2 { + Pos2::new(x * 1.5, y * 1.5) + } + + fn click(&mut self, x: f32, y: f32) { + let p = Self::at(x, y); + self.frame(vec![Event::PointerMoved(p)]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]); + self.frame(vec![]); + } + + /// the host closed and reopened the editor: egui's clock restarts from zero while the UI state lives on + fn reopen_editor(&mut self) { + self.t = 0.0; + } + + fn rclick(&mut self, x: f32, y: f32) { + let p = Self::at(x, y); + self.frame(vec![Event::PointerMoved(p)]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }]); + self.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]); + self.frame(vec![]); + } + + fn drag(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) { + let p0 = Self::at(x0, y0); + self.frame(vec![Event::PointerMoved(p0)]); + self.frame(vec![Event::PointerButton { pos: p0, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + for i in 1..=5 { + let f = i as f32 / 5.0; + self.frame(vec![Event::PointerMoved(Self::at(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f))]); + } + let p1 = Self::at(x1, y1); + self.frame(vec![Event::PointerButton { pos: p1, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]); + self.frame(vec![]); + } + + fn log(&self) -> Vec { + self.host.log.lock().clone() + } +} + +fn script() -> (u64, Vec) { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(594.0, 184.0); // oversampling x2 (right column, bottom row) + r.click(634.0, 184.0); // oversampling x4 + r.drag(41.0, 248.0, 41.0, 223.0); // DRIVE row of the selected band + r.click(165.0, 206.0); // band row: select ML (click on the tab, four tabs of 104 px) + r.drag(41.0, 248.0, 41.0, 233.0); // DRIVE of ML + r.drag(100.0, 100.0, 150.0, 100.0); // viewport: grab a crossover line / marker area + r.click(373.0, 206.0); // band row: HI tab + r.click(452.0, 206.0); // DELTA of the band + r.click(500.0, 206.0); // SOLO of the band + r.click(514.0, 16.0); // EQ page (header) + r.drag(60.0, 120.0, 90.0, 80.0); // EQ node + r.click(300.0, 206.0); // EQ band toggle + r.drag(50.0, 283.0, 50.0, 258.0); // an EQ cell + r.click(50.0, 230.0); // type glyph + r.click(514.0, 16.0); // back to the main page + r.click(624.0, 42.0); // BYPASS + (r.hash, r.log()) +} + +#[test] +fn editor_runs_both_pages_and_writes_parameters() { + let (h1, log) = script(); + let (h2, _) = script(); + assert_eq!(h1, h2, "editor output must be deterministic"); + let joined = log.join("\n"); + assert!(joined.contains("Sat Oversampling"), "oversampling click should reach the host:\n{joined}"); + assert!(joined.contains("Lo Drive"), "dragging DRIVE should write the selected band's drive:\n{joined}"); + assert!(joined.contains("ML Drive"), "after selecting ML its drive must be the one written:\n{joined}"); + assert!(joined.contains("Hi Delta") && joined.contains("Hi Solo"), "band DELTA / SOLO act on the selected band:\n{joined}"); + assert!(joined.contains("EQ2 On") || joined.contains("EQ4 On"), "EQ band toggle should reach the host:\n{joined}"); + assert!(joined.contains("EQ1 Type"), "type glyph click should write the EQ type:\n{joined}"); + assert!(joined.contains("Bypass"), "BYPASS click should reach the host"); +} + +/// Regression: EQ-page cells whose parameter slot is 100 or above (EQ3-5 Q/freq/gain, tilt, pivot, mix, EQ gain) used to start +/// a drag that was never processed, and dragging an EQ node or a crossover line shared ids with those slots. +#[test] +fn eq_page_cells_above_slot_100_can_be_dragged() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(514.0, 16.0); // EQ page + // (x, y, drag dy, parameter that must be written): cells start at y 220, 44 apart; EQ mix sits at its maximum + for (x, y, dy, name) in [ + (490.0, 239.0, -25.0, "EQ Pivot"), + (490.0, 283.0, -25.0, "EQ Tilt"), + (490.0, 327.0, 25.0, "EQ Mix"), + (490.0, 371.0, -25.0, "EQ Gain"), + (222.0, 283.0, -25.0, "EQ3 Q"), + (222.0, 327.0, -25.0, "EQ3 Freq"), + (394.0, 371.0, -25.0, "EQ5 Gain"), + ] { + let n0 = r.log().len(); + r.drag(x, y, x, y + dy); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with(name)), "dragging the {name} cell wrote nothing: {new:?}"); + assert!(new.iter().all(|l| l.starts_with(name)), "dragging the {name} cell also wrote other parameters: {new:?}"); + } + // an EQ node drag must only move that node's own freq and gain (EQ2 sits at 200 Hz on the 0 dB line, x ~182, y 113) + let n0 = r.log().len(); + r.drag(182.0, 113.0, 242.0, 83.0); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with("EQ2 Freq")) && new.iter().any(|l| l.starts_with("EQ2 Gain")), "{new:?}"); + assert!(new.iter().all(|l| l.starts_with("EQ2 ")), "an EQ node drag wrote other parameters: {new:?}"); +} + +/// The controls of the 680 x 410 layout all reach the host. +#[test] +fn main_page_controls_of_the_wide_layout_write_parameters() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + // (x, y, drag dy, parameter): the crossover rows are 16 high at y 110 / 132 / 154, L.AHEAD is the small row at the end of the band row + for (x, y, dy, name) in [(560.0, 118.0, -25.0, "X-Over 1"), (560.0, 140.0, -25.0, "X-Over 2"), (560.0, 162.0, -25.0, "X-Over 3"), (584.0, 206.0, -25.0, "Lookahead")] { + let n0 = r.log().len(); + r.drag(x, y, x, y + dy); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with(name)), "dragging {name} wrote nothing: {new:?}"); + assert!(new.iter().all(|l| l.starts_with(name)), "dragging {name} also wrote other parameters: {new:?}"); + } + // slope buttons at the right end of each crossover row: a click opens the 12 / 24 / 48 / 96 list, a pick writes the slope + for (y, name) in [(118.0, "X-Slope 1"), (140.0, "X-Slope 2"), (162.0, "X-Slope 3")] { + let n0 = r.log().len(); + r.click(637.0, y); + assert!(r.log()[n0..].is_empty(), "opening the slope list must not write: {:?}", &r.log()[n0..]); + r.click(595.0, y + 8.0 + 1.0 + 14.0 * 2.0 + 7.0); // third entry = 48 dB/oct + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with(name) && l.contains("0.667")) && new.iter().all(|l| l.starts_with(name)), "picking a {name} entry: {new:?}"); + } + // oversampling lives under the crossover group + let n0 = r.log().len(); + r.click(594.0, 184.0); + assert!(r.log()[n0..].iter().any(|l| l.starts_with("Sat Oversampling"))); + // band cells: THRESH of the selected (low) band, SAT GAIN, and the OUT column + for (x, y, dy, name) in [ + (327.0, 238.0, 25.0, "Lo Thresh"), + (179.0, 371.0, -25.0, "Lo Sat Gain"), + (594.0, 371.0, -25.0, "Out Gain"), + (594.0, 327.0, 25.0, "Mix"), + ] { + let n0 = r.log().len(); + r.drag(x, y, x, y + dy); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with(name)), "dragging {name} wrote nothing: {new:?}"); + assert!(new.iter().all(|l| l.starts_with(name)), "dragging {name} also wrote other parameters: {new:?}"); + } +} + +/// Header: SIDECHAIN toggles the key, the scale button opens the size menu, the preset menu initialises (every stored +/// parameter, nothing excluded), the arrows step through the bank. The save icon is not clicked: it opens a real file dialog. +#[test] +fn header_sidechain_scale_menu_and_preset_menu() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + let n0 = r.log().len(); + r.click(444.0, 16.0); // SIDECHAIN + assert!(r.log()[n0..].iter().any(|l| l.starts_with("Sidechain 1.000")), "SIDECHAIN click: {:?}", &r.log()[n0..]); + // the scale button opens a menu; clicking an entry must not touch parameters and a click elsewhere closes it + let n0 = r.log().len(); + r.click(379.0, 16.0); + r.click(384.0, 24.0 + 1.0 + 14.0 * 2.0 + 7.0); + r.click(379.0, 16.0); + r.click(300.0, 300.0); + assert!(r.log()[n0..].is_empty(), "scale menu must not write parameters: {:?}", &r.log()[n0..]); + // name -> dropdown -> "Initialize preset" (first entry) writes every stored parameter and nothing excluded + let n0 = r.log().len(); + r.click(240.0, 16.0); + r.click(200.0, 24.0 + 1.0 + 7.0); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.len() >= 100, "initialise should write every stored parameter: {} writes", new.len()); + assert!(new.iter().any(|l| l.starts_with("Lo Drive 0.000")) && new.iter().any(|l| l.starts_with("ML Thresh 1.000")), "init values"); + for banned in ["Bypass", "Gain Match", "Sidechain"] { + assert!(!new.iter().any(|l| l.starts_with(banned)), "{banned} must not be part of a preset"); + } + // arrows step through factory + user presets (at least INIT itself): a full write each time + for x in [312.0, 337.0] { + let n0 = r.log().len(); + r.click(x, 16.0); + assert!(r.log().len() - n0 >= 100, "stepping the bank applies a preset"); + } +} + +/// The *NAME* marker: a loaded preset shows as modified once live parameters differ from it. +#[test] +fn preset_modified_marker_follows_the_parameters() { + let mut clean = Rig::new(); + for _ in 0..4 { + clean.frame(vec![]); + } + assert!(!clean.st.modified_marker(), "defaults equal INIT"); + let mut r = Rig::with_params(|p| p.lo_drive = FloatParam::new("Lo Drive", 50.0, FloatRange::Linear { min: 0.0, max: 100.0 })); + for _ in 0..4 { + r.frame(vec![]); + } + assert!(r.st.modified_marker(), "a changed parameter marks the preset as modified"); +} + +/// Sidechain on: the control row appears under the spectrum (SC gain, HP, LP writes; SOLO is a UI flag) and KEY MIX replaces +/// FF>FB in the compressor cells. +#[test] +fn sidechain_row_and_key_mix_cell() { + let mut r = Rig::with_params(|p| p.sc_on = BoolParam::new("Sidechain", true)); + for _ in 0..4 { + r.frame(vec![]); + } + // row y 175..192: SC gain x 10..170, HP 169..304, LP 303..438, SOLO 437..540 + for (x, y, dy, name) in [(90.0, 183.0, -25.0, "SC Gain"), (230.0, 183.0, -25.0, "SC HP"), (370.0, 183.0, 25.0, "SC LP")] { + let n0 = r.log().len(); + r.drag(x, y, x, y + dy); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with(name)) && new.iter().all(|l| l.starts_with(name)), "dragging {name}: {new:?}"); + } + assert!(!r.shared.sc_solo.load(std::sync::atomic::Ordering::Relaxed)); + r.click(490.0, 183.0); + assert!(r.shared.sc_solo.load(std::sync::atomic::Ordering::Relaxed), "SOLO click sets the monitor flag"); + // KEY MIX sits where FF>FB is (third compressor column, second row) and defaults to its maximum + let n0 = r.log().len(); + r.drag(500.0, 282.0, 500.0, 307.0); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with("Key Mix")) && new.iter().all(|l| l.starts_with("Key Mix")), "KEY MIX cell: {new:?}"); + // sidechain off: solo is cleared by the next frame and the row is gone (no SC writes at its old spot) + let mut r = Rig::new(); + r.shared.sc_solo.store(true, std::sync::atomic::Ordering::Relaxed); + r.frame(vec![]); + assert!(!r.shared.sc_solo.load(std::sync::atomic::Ordering::Relaxed), "solo never outlives the sidechain switch"); + r.drag(90.0, 183.0, 90.0, 158.0); + assert!(!r.log().iter().any(|l| l.starts_with("SC Gain")), "no SC row while the sidechain is off: {:?}", r.log()); +} + +/// Reopening the editor restarts egui's clock; the slow GR number and the VU hold / clip timers must keep working afterwards +/// (they froze at 0 when their timestamps were not re-based). +#[test] +fn gr_number_and_meter_timers_survive_an_editor_reopen() { + let mut r = Rig::new(); + for _ in 0..40 { + r.shared.gr_pk[0].store(6.0, std::sync::atomic::Ordering::Relaxed); + r.frame(vec![]); + } + assert!(r.st.gr_text(0) > 5.0, "GR number follows the engine before the reopen: {}", r.st.gr_text(0)); + r.reopen_editor(); + r.frame(vec![]); + r.shared.gr_pk[0].store(0.0, std::sync::atomic::Ordering::Relaxed); + for _ in 0..80 { + r.frame(vec![]); // ~2.4 s on the restarted clock, no more GR + } + assert!(r.st.gr_text(0) < 0.5, "GR number must refresh after a reopen, not stay frozen: {}", r.st.gr_text(0)); +} + +/// About page: opens from the title, the Appearance tab switches scheme / mode and nothing reaches the host as a parameter. +#[test] +fn about_and_appearance_pages_work() { + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(80.0, 15.0); // title -> About + assert_eq!(r.st.app.about, 1); + r.frame(vec![]); + r.click(135.0, 42.0); // APPEARANCE tab + assert_eq!(r.st.app.about, 3); + r.click(80.0, 125.0); // second scheme row + assert_eq!(r.params.palette_v2.load(Relaxed), 1); + r.click(186.0, 68.0); // LIGHT + assert!(r.params.light.load(Relaxed)); + r.click(135.0 + 115.0, 42.0); // CHANGELOG tab + assert_eq!(r.st.app.about, 2); + r.click(482.0, 42.0); // X CLOSE + assert_eq!(r.st.app.about, 0); + assert!(r.log().is_empty(), "the About pages must not write parameters: {:?}", r.log()); +} + +/// Theme editor: NEW THEME shows the dummy page with the editor cells, the picker opens on a swatch, and the real parameters are +/// never touched while it is open. (Saving would write the user's themes file, so the test cancels.) +#[test] +fn theme_editor_opens_edits_and_cancels_without_touching_parameters() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(80.0, 15.0); + r.click(135.0, 42.0); + r.click(380.0, 89.0); // NEW THEME + assert!(r.st.app.editing()); + r.frame(vec![]); + r.click(210.0 + 30.0, 220.0 + 20.0); // DARK BG swatch -> colour picker + r.click(192.0, 104.0); // inside the saturation / value square + r.drag(282.0, 74.0, 282.0, 114.0); // hue strip + r.click(372.0, 161.0); // picker CANCEL + r.click(480.0, 320.0); // editor cancel icon + assert!(!r.st.app.editing()); + assert_eq!(r.st.app.about, 3, "cancel returns to the Appearance tab"); + assert!(r.log().is_empty(), "the editor must not write parameters: {:?}", r.log()); +} + +/// Icon: a double click toggles light / dark, a right click opens the scheme list. +#[test] +fn icon_double_click_toggles_light_and_right_click_lists_schemes() { + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(20.0, 12.0); + r.click(20.0, 12.0); + assert!(r.params.light.load(Relaxed)); + for _ in 0..12 { + r.frame(vec![]); // wait out the single-click window: the double click must not also cycle the scheme + } + assert_eq!(r.params.palette_v2.load(Relaxed), 0); + r.rclick(20.0, 12.0); + r.click(40.0, 12.0 + 22.0 + 2.0 + 14.0 * 3.0); // third schemes row: Furnace is index 1, rows: MODE, rule, Mono, Furnace + assert_eq!(r.params.palette_v2.load(Relaxed), 1); + r.click(20.0, 12.0); // single click: next scheme after the window + for _ in 0..12 { + r.frame(vec![]); + } + assert_eq!(r.params.palette_v2.load(Relaxed), 2); +} + +/// ASYM heads the first stack of the saturator's right column (TONE under it): drag lowers / wheel changes the selected band's value for the current shaper (stored in the project). +#[test] +fn asym_slider_writes_the_selected_shapers_value() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + assert_eq!(r.params.asym_snapshot(0)[0], 100.0); + r.drag(180.0, 228.0, 180.0, 248.0); // drag down = lower + let a = r.params.asym_snapshot(0); + assert!(a[0] < 100.0, "dragging ASYM changed nothing: {:?}", &a[..3]); + assert_eq!(a[1], 100.0, "other shapers keep their own value"); + assert_eq!(r.params.asym_snapshot(1)[0], 100.0, "other bands keep their own value"); + r.click(180.0, 228.0); + r.click(180.0, 228.0); // double-click = reset + assert_eq!(r.params.asym_snapshot(0)[0], 100.0); +} + +/// LIM sits left of the output meter and toggles the limiter parameter (on by default). +#[test] +fn lim_button_toggles_the_limiter() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + assert!(r.params.lim_on.value(), "limiter defaults to on"); + let n0 = r.log().len(); + r.click(549.0, 16.0); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with("Limiter 0.000")), "LIM click should switch the limiter off: {new:?}"); +} + +/// Waveform scope ("transient meter"): the icon in the viewport corner switches the view, the settings row appears under it, +/// dragging the view changes window / ceiling, the choice is saved with the project, and it writes no parameters. +#[test] +fn scope_icon_switches_the_view_and_drag_changes_window_and_ceiling() { + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + assert_eq!(r.params.scope.load(Relaxed) & 1, 0); + r.click(514.0, 43.0); // icon, top right of the viewport + assert_eq!(r.params.scope.load(Relaxed) & 1, 1, "icon turns the scope on and stores it"); + let before = r.params.scope.load(Relaxed); + r.drag(200.0, 80.0, 300.0, 110.0); // view drag: window and ceiling steps + assert_ne!(r.params.scope.load(Relaxed), before, "dragging the view changes the settings"); + let n0 = r.log().len(); + r.click(40.0, 183.0); // SRC cell of the settings row (bottom of the viewport) + assert_ne!((r.params.scope.load(Relaxed) >> 1) & 3, (before >> 1) & 3, "SRC cycles on click"); + assert_eq!(r.log().len(), n0, "the scope writes no parameters"); + r.click(514.0, 43.0); + assert_eq!(r.params.scope.load(Relaxed) & 1, 0, "icon turns it off again"); +} + +/// The saturator's controls: BIAS beside DRIVE, ASYM over TONE and HP over LP in the right column, all writing the selected band. +#[test] +fn bias_tone_hp_lp_cells_write_the_selected_band() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + // (x, y, drag dy, parameter): selector 220-239, DRIVE | BIAS 239-258; stacks at x 142-216 from y 220 (halves 19 / 20 high) + for (x, y, dy, name) in [ + (85.0, 248.0, -25.0, "Lo Bias"), + (180.0, 250.0, 25.0, "Lo Tone"), + (180.0, 266.0, -25.0, "Lo HP"), + (180.0, 284.0, 25.0, "Lo LP"), + ] { + let n0 = r.log().len(); + r.drag(x, y, x, y + dy); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with(name)), "dragging {name} wrote nothing: {new:?}"); + assert!(new.iter().all(|l| l.starts_with(name)), "dragging {name} also wrote other parameters: {new:?}"); + } +} + +/// Four bands: every tab selects its own band, the third crossover line can be dragged and moves only X-Over 3. +#[test] +fn four_band_tabs_and_the_third_crossover_line() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + for (i, x) in [60.0, 165.0, 270.0, 373.0].into_iter().enumerate() { + r.click(x, 206.0); + assert_eq!(r.params.sel_band.load(std::sync::atomic::Ordering::Relaxed), i as i32, "tab {i}"); + } + // the dotted crossover line at 3.5 kHz: drag it left, only X-Over 3 may change + let px = satcomp_ui::spectrum::freq_to_x(3500.0, 11.0, 512.0); // viewport x 10, width 514 + let n0 = r.log().len(); + r.drag(px, 60.0, px - 30.0, 60.0); + let new: Vec = r.log()[n0..].to_vec(); + assert!(!new.is_empty() && new.iter().all(|l| l.starts_with("X-Over 3")), "{new:?}"); + let last: f32 = new.last().unwrap().rsplit(' ').next().unwrap().parse().unwrap(); + assert!(last < (3500.0 - 200.0) / 19800.0, "dragging left must lower X-Over 3: {new:?}"); +} + +/// Draw view: the corner pencil opens it with the symmetry tool (odd curve: the left half mirrors the right), the pencil tool +/// draws free, the symmetry tool folds a lopsided curve back onto its odd part, the cross closes the view. +#[test] +fn draw_view_has_a_symmetry_tool_and_a_free_tool() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + let odd = |r: &Rig| { + let c = r.params.curve_snapshot(0); + (0..=10).map(|i| (c.eval(i as f64 * 0.1) + c.eval(-(i as f64) * 0.1)).abs()).fold(0.0, f64::max) + }; + r.click(128.0, 272.0); // corner pencil: opens the draw view (plot at x 10, y 264, 126 square) + assert_eq!(r.params.curve_snapshot(0).n, 2); + r.click(99.0, 288.0); // a point at about (0.5, 0.8) on the right half + let c = r.params.curve_snapshot(0); + assert_eq!(c.n, 4, "a mirrored pair must appear: {:?}", c.pts()); + assert!(odd(&r) < 1e-6, "symmetry tool keeps the curve odd: {}", odd(&r)); + r.click(114.0, 272.0); // pencil tool: free draw + r.click(59.0, 331.0); // a lone point on the left half, at about (-0.25, -0.1) + let n_free = r.params.curve_snapshot(0).n; + assert_eq!(n_free, 5, "free draw adds a single point"); + assert!(odd(&r) > 0.02, "the curve is lopsided now: {}", odd(&r)); + r.click(100.0, 272.0); // symmetry tool: folds onto the odd part + assert!(odd(&r) < 1e-6, "folded back onto its odd part: {}", odd(&r)); + let n_fold = r.params.curve_snapshot(0).n; + r.click(128.0, 272.0); // cross: closes the view + r.click(99.0, 300.0); + assert_eq!(r.params.curve_snapshot(0).n, n_fold, "a closed view must not edit the curve"); +} + +#[test] +fn a_project_restored_after_the_editor_was_built_keeps_its_saved_look() { + use std::sync::atomic::Ordering::Relaxed; + // nih-plug builds the editor first and the host restores the project's parameters afterwards + let mut r = Rig::new(); + assert_eq!((r.st.pal, r.st.light, r.st.face), (0, false, 0)); + r.params.palette_v2.store(5, Relaxed); + r.params.light.store(true, Relaxed); + r.params.font.store(2, Relaxed); + r.st.sync_look(&r.params); // what opening the window does + assert_eq!((r.st.pal, r.st.light, r.st.face), (5, true, 2)); + for _ in 0..3 { + r.frame(vec![]); + } + assert_eq!(r.params.palette_v2.load(Relaxed), 5, "drawing must not overwrite the restored scheme"); +} + +/// A sidechain preset comes back keyed: the switch is saved with a preset and applied only when the preset carries it. +#[test] +fn a_preset_saves_and_restores_the_sidechain_switch_but_old_presets_leave_it_alone() { + // saved from a rig with the switch on + let mut on = Rig::with_params(|p| p.sc_on = BoolParam::new("Sidechain", true)); + for _ in 0..4 { + on.frame(vec![]); + } + on.st.test_want_capture = true; + on.frame(vec![]); + let saved = on.st.test_capture.take().expect("captured"); + assert_eq!(saved.params.get("sc_on"), Some(&1.0), "the switch is stored"); + assert!(!saved.params.contains_key("bypass") && !saved.params.contains_key("gain_match")); + + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + let n0 = r.log().len(); + r.st.test_apply = Some(saved); + r.frame(vec![]); + assert!(r.log()[n0..].iter().any(|l| l.starts_with("Sidechain 1.000")), "loading it switches the key on: {:?}", &r.log()[n0..]); + // an older preset (no sc_on) must not touch the switch, either way + let n1 = r.log().len(); + r.st.test_apply = Some(crate::presets::Preset::init()); + r.frame(vec![]); + assert!(!r.log()[n1..].iter().any(|l| l.starts_with("Sidechain")), "old presets / INIT leave the switch alone"); +} + +/// SOLO and DELTA follow the band tab: selecting another band moves them along instead of leaving the old band soloed. +#[test] +fn solo_and_delta_follow_the_selected_band_tab() { + let mut r = Rig::with_params(|p| { + p.lo_solo = BoolParam::new("Lo Solo", true); + p.lo_delta = BoolParam::new("Lo Delta", true); + }); + for _ in 0..4 { + r.frame(vec![]); + } + let n0 = r.log().len(); + r.click(167.0, 206.0); // the ML tab + let new: Vec = r.log()[n0..].to_vec(); + for want in ["Lo Solo 0.000", "ML Solo 1.000", "Lo Delta 0.000", "ML Delta 1.000"] { + assert!(new.iter().any(|l| l.starts_with(want)), "{want} missing: {new:?}"); + } + // nothing on: switching tabs writes no solo / delta + let mut q = Rig::new(); + for _ in 0..4 { + q.frame(vec![]); + } + let n0 = q.log().len(); + q.click(167.0, 206.0); + assert!(!q.log()[n0..].iter().any(|l| l.contains("Solo") || l.contains("Delta")), "{:?}", &q.log()[n0..]); +} + +/// SAT GAIN level match: the SAT readout in a band's plot corner requests a measurement for that band, and the finished +/// result is written to that band's SAT GAIN. +#[test] +fn clicking_the_sat_readout_requests_that_bands_level_match_and_its_result_writes_sat_gain() { + use std::sync::atomic::Ordering::{Relaxed, Release}; + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(100.0, 382.0); // the SAT readout of the selected (LO) band + assert!(r.shared.sat_req[0].swap(false, Relaxed), "no match request for band 0"); + assert!(!r.shared.sat_req[1].load(Relaxed), "only the selected band is measured"); + let n0 = r.log().len(); + r.shared.sat_result[0].store(-3.5, Relaxed); + r.shared.sat_result_new[0].store(true, Release); + r.frame(vec![]); + assert!(r.log()[n0..].iter().any(|l| l.starts_with("Lo Sat Gain 0.569")), "{:?}", &r.log()[n0..]); +} + +/// Upward compression: the COMP DOWN / UP switch sits on top of the second compressor column (with RANGE under it, KNEE and +/// K.SHAPE as a stacked pair below), it writes the band's UP parameter, and the GR meter is drawn centre-tapped in that mode. +#[test] +fn the_comp_up_switch_writes_the_band_and_the_meter_turns_centre_tapped() { + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + let n0 = r.log().len(); + r.click(400.0, 229.0); // DWNWARD -> UPWARD (second column, top row); the mode is 0..2, so UPWARD is 0.500 normalised + assert!(r.log()[n0..].iter().any(|l| l.starts_with("Lo Comp Mode 0.500")), "{:?}", &r.log()[n0..]); + // the rest of the cycle, each from a rig that starts in that mode (the fake host logs writes but does not apply them) + for (from, want) in [(1, "Lo Comp Mode 1.000"), (2, "Lo Comp Mode 0.000")] { + let mut q = Rig::with_params(|p| p.lo_up = IntParam::new("Lo Comp Mode", from, IntRange::Linear { min: 0, max: 2 })); + for _ in 0..4 { + q.frame(vec![]); + } + let n = q.log().len(); + q.click(400.0, 229.0); + assert!(q.log()[n..].iter().any(|l| l.starts_with(want)), "from mode {from}: {:?}", &q.log()[n..]); + } + // KNEE and K.SHAPE still reach their parameters from the stacked pair in the second row + let n0 = r.log().len(); + r.drag(400.0, 273.0, 400.0, 255.0); + r.drag(400.0, 291.0, 400.0, 273.0); + let new: Vec = r.log()[n0..].to_vec(); + assert!(new.iter().any(|l| l.starts_with("Lo Knee ")) && new.iter().any(|l| l.starts_with("Lo Knee Shape ")), "{new:?}"); + + // the same lift on the meter draws differently with UP on than with it off (centre-tapped, gain colour) + let frame_hash = |up: bool| { + let mut q = Rig::with_params(|p| p.lo_up = IntParam::new("Lo Comp Mode", up as i32 * 2, IntRange::Linear { min: 0, max: 2 })); + q.shared.gl_pk[0].store(6.0, Relaxed); + for _ in 0..12 { + q.shared.gl_pk[0].fetch_max(6.0, Relaxed); + q.frame(vec![]); + } + q.hash + }; + assert_ne!(frame_hash(true), frame_hash(false), "the meter should change with the mode"); + assert_eq!(frame_hash(true), frame_hash(true), "and be deterministic"); +} + +/// The About signal flow doubles as switches: clicking its LIM block turns the limiter off and a band block writes that band's ON. +/// (The blocks move with the layout, so the test scans the flow area for the clicks that land.) +#[test] +fn the_about_signal_flow_blocks_are_switches() { + let mut r = Rig::new(); + for _ in 0..4 { + r.frame(vec![]); + } + r.click(80.0, 15.0); // title -> About + r.frame(vec![]); + let (mut lim, mut band) = (false, false); + 'scan: for y in (70..170).step_by(4) { + for x in (150..540).step_by(6) { + let n0 = r.log().len(); + r.click(x as f32, y as f32); + for l in r.log()[n0..].iter() { + lim |= l.starts_with("Limiter"); + band |= l.contains(" On ") || l.ends_with(" On"); + } + if lim && band { + break 'scan; + } + } + } + assert!(lim, "a flow click should switch the limiter: {:?}", r.log()); + assert!(band, "a flow click should switch a band: {:?}", r.log()); + assert_eq!(r.st.app.about, 1, "still on the About page"); +} diff --git a/rust/satxcomp-plugin/src/gui/ui.rs b/rust/satxcomp-plugin/src/gui/ui.rs new file mode 100644 index 0000000..2457c02 --- /dev/null +++ b/rust/satxcomp-plugin/src/gui/ui.rs @@ -0,0 +1,3032 @@ +//! SatXComp pages: header, tab row, spectrum / crossover viewport, the four band tabs with their saturator and compressor +//! cells, and the output column. Widgets (cells, buttons, drag logic) come from `satcomp_ui::kit`. + +use crate::params::{SatXCompParams, SLOTS, TABLE}; +use crate::presets::{self, Preset}; +use crate::Shared; +use nih_plug::prelude::*; +use satcomp_dsp::biquad::{eq_coef, mag_db}; +use satcomp_dsp::shapers::{Curve, ShaperLut, CUSTOM, MAX_PTS, MIN_GAP, SHAPER_NAMES}; +use satcomp_ui::appearance::{self, AppState, AppearanceUi, CellGrid, Rect}; +use satcomp_ui::canvas::{Canvas, PALETTES}; +use satcomp_ui::kit::{Kit, Meta, Widgets}; +use satcomp_ui::spectrum::{freq_to_x, x_to_freq, Spectrum}; +use satxcomp_dsp::{eq_kind, XParams, EQ_KINDS, NB}; +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +/// First UI slot of band `b` (see tools/gen_xparams.py). +pub const fn band_base(b: usize) -> usize { + 10 + 24 * b +} +// offsets inside a band +const ON: usize = 0; +const SOLO: usize = 1; +const DELTA: usize = 2; +const SHAPE: usize = 3; +const DRIVE: usize = 4; +const BIAS: usize = 5; +const TONE: usize = 6; +const SAT_MIX: usize = 7; +const SAT_GAIN: usize = 8; +const THRESH: usize = 9; +const RATIO: usize = 10; +const ATTACK: usize = 11; +const RELEASE: usize = 12; +const SPEED: usize = 13; +const KNEE: usize = 14; +const KNEE_SHAPE: usize = 15; +const DETECTOR: usize = 16; +const FF_FB: usize = 17; +const GR_DIST: usize = 18; +const COMP_MIX: usize = 19; +const COMP_GAIN: usize = 20; +const HP: usize = 21; +const LP: usize = 22; +/// upward compression switch (offset inside the band); its RANGE lives at slot `range_slot(b)` +const UP: usize = 23; +const RANGE_BASE: usize = 160; +const fn range_slot(b: usize) -> usize { + RANGE_BASE + b +} + +/// first UI slot of EQ band `i`: on, type, freq, q, gain +const fn eq_base(i: usize) -> usize { + 120 + 5 * i +} +const EQ_TILT: usize = 145; +const EQ_PIVOT: usize = 146; +const EQ_MIX: usize = 147; +const EQ_GAIN: usize = 148; +const EQ_BYPASS: usize = 149; +/// crossover frequency slots (1, 2, 9) and slope slots, by split +const XOV: [usize; 3] = [1, 2, 9]; +const XOV_SLOPE: [usize; 3] = [106, 107, 108]; +const SC_ON: usize = 110; +const SC_GAIN: usize = 111; +const SC_HP: usize = 112; +const SC_LP: usize = 113; +const SC_MIX: usize = 114; +const LIM_ON: usize = 150; +/// height of the sidechain control row under the spectrum +const SC_ROW_H: f32 = 17.0; +// ---- layout (logical units; the window is W x H = 680 x 480) +/// viewport (spectrum / crossover / EQ curve) +const VX: f32 = 10.0; +const VY: f32 = 34.0; +const VW: f32 = 514.0; +const VH: f32 = 158.0; +/// right-hand column (levels, crossover sliders, output module) +const RX: f32 = 534.0; +const RW: f32 = 120.0; +/// row of band tabs / EQ band toggles under the viewport +const BAND_Y: f32 = VY + VH + 6.0; +/// first row of cells; four rows, CELL_P apart +const CELLS_Y: f32 = BAND_Y + 22.0; +const CELL_H: f32 = 38.0; +const CELL_P: f32 = 44.0; +/// band module cells (saturator / compressor) +const CELL_W: f32 = 74.0; +/// EQ page columns: five bands plus the pivot column, across the viewport width +const EQ_W: f32 = 80.0; +const EQ_P: f32 = 86.0; +const EQ_PW: f32 = VW - 5.0 * EQ_P; +/// window scale steps (x the 664 x 400 base) +const SIZES: [f32; 6] = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5]; +/// `kit.act` values: 1..VIEW_ACT are parameter slots (vertical drag, slots run to 150); VIEW_ACT and up are viewport drags +const VIEW_ACT: i32 = 1000; +const ACT_X1: i32 = VIEW_ACT + 1; +const ACT_X2: i32 = VIEW_ACT + 2; +/// third crossover line (the EQ nodes take VIEW_ACT + 3..7) +const ACT_X3: i32 = VIEW_ACT + 8; +/// EQ node `b` is ACT_NODE + b +const ACT_NODE: i32 = VIEW_ACT + 3; +/// EQ viewport: drag the dashed pivot line / drag empty space sideways for tilt +const ACT_PIVOT: i32 = VIEW_ACT + 10; +const ACT_TILT: i32 = VIEW_ACT + 11; +/// custom-curve point drag in the draw view +const ACT_CURVE: i32 = VIEW_ACT + 20; +/// band handle drag in the spectrum (threshold); band b is ACT_THR + b +const ACT_THR: i32 = VIEW_ACT + 30; +/// ASYM slider drag (one slider, follows the selected band) +const ACT_ASYM: i32 = VIEW_ACT + 40; +/// waveform scope: view drag, then the WIN and CEIL sliders (ACT_SCOPE + 1 / + 2) +const ACT_SCOPE: i32 = VIEW_ACT + 50; +mod scope; +const MENU_ROWS: usize = 18; +const MENU_ROW_H: f32 = 14.0; + +/// popup list (shaper dropdown): plain label rows, one checked +#[derive(Clone, Copy)] +enum MenuKind { + /// shaper list of band `b` + Shape(usize), + Size, + Preset, + /// colour scheme list (the icon's right-click menu) + Palette, + /// crossover slope list of split `k` + Slope(usize), +} + +/// kind: 0 selectable item, 1 header (dim, not selectable), 2 separator +#[derive(Clone)] +struct MItem { + label: String, + kind: u8, + id: i32, +} + +struct Menu { + kind: MenuKind, + x: f32, + y: f32, + items: Vec, + /// id of the checked item + checked: i32, + scroll: usize, +} + +/// Outcome of a file dialog on its worker thread. +pub enum Dlg { + Pending, + Cancelled, + Loaded(Preset), + Saved(String), +} + +const KIND_NAMES: [&str; 8] = ["HPF", "LPF", "LO SHELF", "HI SHELF", "BAND", "ALLPASS", "BANDPASS", "NOTCH"]; + +const BAND_NAMES: [&str; NB] = ["LOW", "ML", "MH", "HI"]; +const BAND_LETTERS: [&str; NB] = ["LO", "ML", "MH", "HI"]; + +pub struct State { + pub kit: Kit, + /// colour themes, theme editor and About-page state (satcomp-ui) + pub app: AppState, + pub dummy_params: Arc, + pub dummy_shared: Arc, + /// time of an icon click waiting out the double-click window (then it cycles the colour scheme) + logo_pend: f64, + pub pal: usize, + pub light: bool, + pub face: usize, + spec_out: Spectrum, + spec_dry: Spectrum, + gr_disp: [f32; NB], + gr_hold: [f32; NB], + gr_hold_t: [f64; NB], + gr_ri: usize, + ovl: f32, + ovr: f32, + hl_l: f32, + hl_r: f32, + hl_l_t: f64, + hl_r_t: f64, + opk_max: f32, + clip_lat: bool, + rd_last: f64, + rd_pk: f32, + /// per band: loudness change across the saturator (readout in the plot corner, refreshed ~8x/s) + rd_sat: [f32; 4], + rd_rms: f32, + rd_diff: f32, + lut: ShaperLut, + eq_page: bool, + eq_sel: usize, + /// custom-curve draw view of the selected band (pencil), and the point being dragged + curve_edit: bool, + /// draw view tool: true = symmetry (odd: the right half is drawn, the left follows as f(-x) = -f(x)), false = free draw + sym_mode: bool, + /// waveform scope settings, packed (see scope.rs); view-drag anchor (mx, my, window step, ceiling step) + scope_cfg: i32, + /// steady scope scrolling: eased read position (bucket index) and the time of the last frame + scope_pos: f64, + scope_t: f64, + scope_drag: (f32, f32, usize, usize), + /// ASYM drag anchor: (mouse y, value 0..1) at the press + asym_drag: (f32, f32), + edit_seen: bool, + cpt: usize, + menu: Option, + /// presets: factory bank, user folder listing, the loaded preset as reference for the modified marker, pending dialog + factory: Vec, + user: Vec<(String, std::path::PathBuf)>, + base: Option<(String, Preset)>, + hold_until: f64, + /// tests: a preset to apply / a capture to take at the start of the next frame (the file dialogs are not testable) + #[cfg(test)] + pub test_apply: Option, + #[cfg(test)] + pub test_want_capture: bool, + #[cfg(test)] + pub test_capture: Option, + /// what the preset bar last showed (the *NAME* marker) + shown_modified: bool, + pending: u8, + dlg: Option>>, + /// gain-reduction readouts refresh slowly (peak over the last interval) so the numbers stay readable + gr_txt: [f32; NB], + /// upward compressor lift per band: display value, hold, hold time and the number window (like the gr_* ones) + gl_disp: [f32; NB], + gl_hold: [f32; NB], + gl_hold_t: [f64; NB], + gl_txt: [f32; NB], + gl_txt_pk: [f32; NB], + gr_txt_pk: [f32; NB], + gr_txt_t: f64, + /// output limiter reduction: decaying peak (flow block) and a 4 Hz text value + lim_disp: f32, + lim_txt: f32, + lim_txt_pk: f32, + /// per band post-saturator meter: decaying level, hold, and the last time it clipped + vu: [f32; NB], + vu_hold: [f32; NB], + vu_hold_t: [f64; NB], + vu_clip_t: [f64; NB], + /// window-size grip drag and the pointer / window in host points (set by run_frame) + resizing: bool, + resize_off: (f32, f32), + pub ptr_pt: (f32, f32), + pub win_pt: (f32, f32), + /// EQ viewport drags: tilt accumulator, last pointer x, pivot grab offset + tacc: f32, + tlast: f32, + gdx: f32, + rd_eq_diff: f32, +} + +impl Deref for State { + type Target = Kit; + fn deref(&self) -> &Kit { + &self.kit + } +} +impl DerefMut for State { + fn deref_mut(&mut self) -> &mut Kit { + &mut self.kit + } +} + +fn version_short() -> String { + if cfg!(test) { + return "TEST".into(); + } + let v = env!("CARGO_PKG_VERSION"); + v.strip_suffix(".0").unwrap_or(v).to_string() +} + +impl State { + pub fn new(params: &SatXCompParams) -> Self { + let mut kit = Kit::new(SLOTS); + for &(n, _, mn, mx, df) in TABLE { + kit.meta[n] = Meta { min: mn, max: mx, def: df, mode: 0, snap: 0, step: 1.0 }; + } + let mut sp = |n: usize, mode: u8, snap: u8, step: f32| { + kit.meta[n].mode = mode; + kit.meta[n].snap = snap; + kit.meta[n].step = step; + }; + for n in XOV { + sp(n, 1, 0, 1.0); + } + sp(4, 0, 0, 0.1); + sp(6, 0, 0, 0.1); + for b in 0..NB { + let o = band_base(b); + sp(o + DRIVE, 0, 0, 0.5); + sp(o + BIAS, 0, 0, 1.0); + sp(o + TONE, 1, 2, 10.0); + sp(o + HP, 1, 1, 1.0); + sp(o + LP, 1, 2, 10.0); + sp(o + SAT_GAIN, 0, 0, 0.1); + sp(o + THRESH, 0, 0, 0.1); + sp(o + RATIO, 1, 2, 0.1); + sp(o + ATTACK, 1, 0, 0.01); + sp(o + RELEASE, 1, 2, 1.0); + sp(o + KNEE, 0, 0, 0.1); + sp(o + COMP_GAIN, 0, 0, 0.1); + sp(range_slot(b), 0, 0, 0.5); + } + for i in 0..5 { + let o = eq_base(i); + sp(o + 2, 1, 0, 1.0); + sp(o + 3, 1, 0, 0.01); + sp(o + 4, 0, 0, 0.1); + } + sp(SC_GAIN, 0, 0, 0.1); + sp(SC_HP, 1, 1, 1.0); + sp(SC_LP, 1, 2, 10.0); + sp(SC_MIX, 0, 0, 1.0); + sp(EQ_TILT, 0, 0, 0.1); + sp(EQ_PIVOT, 1, 0, 1.0); + sp(EQ_GAIN, 0, 0, 0.1); + let pal = params.palette_v2.load(Ordering::Relaxed).max(0) as usize; + let mut app = AppState::new(); + let pal = app.restore_custom(pal, ¶ms.custom_theme.lock()); + params.palette_v2.store(pal as i32, Ordering::Relaxed); + Self { + kit, + app, + dummy_params: Arc::new(SatXCompParams::from_defaults(None)), + dummy_shared: Arc::new(Shared::new()), + logo_pend: -1.0, + pal, + light: params.light.load(Ordering::Relaxed), + face: (params.font.load(Ordering::Relaxed).max(0) as usize).min(satcomp_ui::canvas::FONT_NAMES.len() - 1), + spec_out: Spectrum::new(), + spec_dry: Spectrum::new(), + gr_disp: [0.0; NB], + gr_hold: [0.0; NB], + gr_hold_t: [0.0; NB], + gr_ri: 0, + ovl: 0.0, + ovr: 0.0, + hl_l: 0.0, + hl_r: 0.0, + hl_l_t: 0.0, + hl_r_t: 0.0, + opk_max: 0.0, + clip_lat: false, + rd_last: 0.0, + rd_pk: 0.0, + rd_sat: [0.0; 4], + rd_rms: 0.0, + rd_diff: 0.0, + lut: ShaperLut::new(0), + eq_page: false, + eq_sel: 0, + curve_edit: false, + sym_mode: true, + scope_cfg: params.scope.load(Ordering::Relaxed), + scope_pos: 0.0, + scope_t: 0.0, + scope_drag: (0.0, 0.0, 0, 0), + asym_drag: (0.0, 0.0), + edit_seen: false, + cpt: 0, + menu: None, + factory: presets::factory(), + user: presets::scan_user(), + base: None, + hold_until: 0.0, + #[cfg(test)] + test_apply: None, + #[cfg(test)] + test_want_capture: false, + #[cfg(test)] + test_capture: None, + shown_modified: false, + pending: 0, + dlg: None, + gr_txt: [0.0; NB], + gl_disp: [0.0; NB], + gl_hold: [0.0; NB], + gl_hold_t: [0.0; NB], + gl_txt: [0.0; NB], + gl_txt_pk: [0.0; NB], + gr_txt_pk: [0.0; NB], + gr_txt_t: 0.0, + lim_disp: 0.0, + lim_txt: 0.0, + lim_txt_pk: 0.0, + vu: [0.0; NB], + vu_hold: [0.0; NB], + vu_hold_t: [0.0; NB], + vu_clip_t: [-10.0; NB], + resizing: false, + resize_off: (0.0, 0.0), + ptr_pt: (0.0, 0.0), + win_pt: (super::W, super::H), + tacc: 0.0, + tlast: 0.0, + gdx: 0.0, + rd_eq_diff: 0.0, + } + } + + /// the preset bar's modified marker (tests) + #[cfg(test)] + pub fn modified_marker(&self) -> bool { + self.shown_modified + } + + /// last published GR number of band `b` (tests) + #[cfg(test)] + pub fn gr_text(&self, b: usize) -> f32 { + self.gr_txt[b] + } + + pub fn set_input(&mut self, mx: f32, my: f32, down: bool, rdown: bool, scroll: f32, shift: bool, now: f64) { + if self.kit.set_input(mx, my, down, rdown, scroll, shift, now) { + // the egui clock restarts when the editor window is reopened: re-base every stored timestamp + self.rd_last = now; + self.scope_t = now; + self.hl_l_t = now; + self.hl_r_t = now; + self.gr_hold_t = [now; NB]; + self.gl_hold_t = [now; NB]; + self.gr_txt_t = now; + self.hold_until = now; + self.vu_hold_t = [now; NB]; + self.vu_clip_t = [-10.0; NB]; + self.spec_out.rebase(now); + self.spec_dry.rebase(now); + self.app.rebase(); + self.logo_pend = -1.0; + } + } + + /// nih-plug builds the editor (and so this state) when the plug-in is created, BEFORE the host restores the project's + /// saved parameters. Re-read the saved look every time the window opens, otherwise a project reopens on the defaults. + pub fn sync_look(&mut self, params: &SatXCompParams) { + let pal = params.palette_v2.load(Ordering::Relaxed).max(0) as usize; + self.pal = self.app.restore_custom(pal, ¶ms.custom_theme.lock()); + params.palette_v2.store(self.pal as i32, Ordering::Relaxed); + self.light = params.light.load(Ordering::Relaxed); + self.face = (params.font.load(Ordering::Relaxed).max(0) as usize).min(satcomp_ui::canvas::FONT_NAMES.len() - 1); + self.scope_cfg = params.scope.load(Ordering::Relaxed); + } + + /// Colours the canvas draws with: the editor preview while editing, else the active scheme. + pub fn colors(&self) -> [f32; 9] { + self.app.colors(self.pal, self.light) + } + + /// Constant meter / readout values and a synthetic spectrum for the theme editor's dummy page. + pub fn fill_dummy(&self) { + use std::sync::atomic::Ordering::Relaxed; + let d = &self.dummy_shared; + d.opk[0].store(1.0, Relaxed); + d.opk[1].store(0.5, Relaxed); + d.clip.store(true, Relaxed); + for b in 0..NB { + d.gr_pk[b].store(2.0 + b as f32 * 2.0, Relaxed); + d.sat_vz[b].store(0.3, Relaxed); + d.sat_out_pk[b].store(0.3 + 0.35 * b as f32, Relaxed); + } + d.fms.store(0.05, Relaxed); + d.diff_disp.store(2.0, Relaxed); + d.eq_diff.store(1.0, Relaxed); + // out: a pink-ish stack of sines; dry: the same, louder in the highs (the gap between them shows both accents) + let w0 = d.tap_out.w.load(Relaxed); + for i in 0..satcomp_dsp::TapRing::LEN { + let t = (i + w0) as f32 * 0.001; + let lo = 0.3 * (t * 211.0).sin() + 0.2 * (t * 1733.0).sin(); + let hi = 0.1 * (t * 7919.0).sin() + 0.05 * (t * 13007.0).sin(); + d.tap_out.buf[i].store((lo + hi * 0.5).to_bits(), Relaxed); + d.tap_dry.buf[i].store((lo * 0.8 + hi * 2.0).to_bits(), Relaxed); + } + d.tap_out.w.store(satcomp_dsp::TapRing::LEN * 3, Relaxed); + d.tap_dry.w.store(satcomp_dsp::TapRing::LEN * 3, Relaxed); + } +} + +pub struct Env<'a> { + pub params: &'a SatXCompParams, + pub setter: &'a ParamSetter<'a>, + pub shared: &'a Shared, + pub dsp: XParams, +} + +pub struct Gui<'a> { + pub s: &'a mut State, + pub cv: Canvas<'a>, + pub env: Env<'a>, +} + +impl<'a> Deref for Gui<'a> { + type Target = State; + fn deref(&self) -> &State { + self.s + } +} +impl<'a> DerefMut for Gui<'a> { + fn deref_mut(&mut self) -> &mut State { + self.s + } +} + +impl<'a> Widgets<'a> for Gui<'a> { + fn kit(&mut self) -> &mut Kit { + &mut self.s.kit + } + fn kit_ref(&self) -> &Kit { + &self.s.kit + } + fn cv(&mut self) -> &mut Canvas<'a> { + &mut self.cv + } + fn param_ptr(&self, n: usize) -> Option { + self.env.params.ptr(n) + } + fn host(&self) -> &dyn GuiContext { + self.env.setter.raw_context + } + fn masked(&self) -> bool { + self.s.app.edit.is_some() + } + fn fmt(&self, n: usize, v: f32) -> String { + fmt_slot(n, v) + } +} + +impl<'a> Gui<'a> { + /// Push the active scheme's colours into the canvas. + fn apply_pal(&mut self) { + let a = self.app.scheme_cols(self.pal, self.light); + self.cv.bk = [a[0], a[1], a[2]]; + self.cv.fg = [a[3], a[4], a[5]]; + self.cv.ac = [a[6], a[7], a[8]]; + } +} + +/// About page copy (docs/abouttextcopy.md). Each inner slice is one paragraph, each string one source line. +const ABOUT_TEXT: &[&[&str]] = &[ + &["A 4-band compressor with waveshaping saturator and 5-band EQ", "For surgical baking intentions :3"], + &["Set the crossover ranges with the XOV sliders (12, 24, 48 and 96 dB slopes), then drive each band to taste."], + &["Use sidechain mode for dynamic EQ style ducking, then cook hard with waveshaping distortion.", "[Click] the top-right pencil icon to enter custom draw mode.", "[Click] the lower-right SAT value to auto-match the gain."], + &["Slower attack and release suit low frequencies, faster attack and release suit high ones."], + &["Refine tone with the post-compressor 5-band EQ, or sculpt with notch, bandpass and allpass with dry signal blending."], + &["Spectrum viewport: accent = gain reduction vs dry, inverted accent = gain increase vs dry."], + &["Band handles: the top horizontal bar is the in/out gain difference, the vertical bar above it the gain increase (upward compression), the vertical bar below it the gain reduction."], + &["[Double-click] slider resets the parameter to its default value", "[Click] GR meter cycles its range", "[Click] clip meter resets the readout", "[Left/Right-click] top-left icon cycles the colour theme", "[Double-click] top-left icon switches between dark and light mode"], +]; + +/// Changelog, newest first. Keep each entry to two short sentences or fewer. +const CHANGELOG: &[(&str, &[&str])] = &[("v0.1", &[ + "First release: four bands (LO, ML, MH, HI) with three crossovers (12, 24, 48 or 96 dB), a waveshaper and compressor per band, sidechain with solo, a 5-band post EQ and presets.", + "Compressor mode per band: DWNWARD, UPWARD (lifts what is below the threshold, up to RANGE) or UP/DWN (both). The band handles show the lift as a bar above and the reduction below.", + "Saturator per band: DRIVE, BIAS and ASYM, HP and LP, SAT GAIN with auto-match, custom curves with a symmetry tool, and a post-saturator level meter.", + "A true-peak output limiter (LIM, on by default) catches rogue peaks; its reduction shows in the LIM readout. BYPASS is a plain bypass.", + "The viewport shows gain reduction in the accent colour and gain increase in its inverse. The corner icon opens a waveform scope (transient meter).", + "Colour schemes (27) with light mode, custom themes, fonts and the spectrum fill under About > Preferences."])]; + +impl<'a> AppearanceUi<'a> for Gui<'a> { + fn app(&mut self) -> &mut AppState { + &mut self.s.app + } + fn app_ref(&self) -> &AppState { + &self.s.app + } + fn pal(&self) -> usize { + self.s.pal + } + fn light(&self) -> bool { + self.s.light + } + fn face(&self) -> usize { + self.s.face + } + fn commit_scheme(&mut self, pal: usize, encoded: String) { + self.s.pal = pal; + self.env.params.palette_v2.store(pal as i32, Ordering::Relaxed); + // a user theme is also stored in the project, so it survives a machine without the themes file + *self.env.params.custom_theme.lock() = encoded; + self.apply_pal(); + } + fn commit_light(&mut self, light: bool) { + self.s.light = light; + self.env.params.light.store(light, Ordering::Relaxed); + self.apply_pal(); + } + fn fft_solid(&self) -> Option { + Some(self.env.params.fft_solid.load(Ordering::Relaxed)) + } + fn commit_fft_solid(&mut self, solid: bool) { + self.env.params.fft_solid.store(solid, Ordering::Relaxed); + } + fn plugin_key(&self) -> &'static str { + "satxcomp" + } + fn presets_dir(&self) -> Option { + crate::presets::user_dir() + } + fn scale_now(&self) -> f32 { + self.cur_scale() + } + fn set_scale(&mut self, scale: f32) { + self.request_scale(scale); + } + fn factory_scale(&self) -> f32 { + 1.25 + } + fn commit_face(&mut self, face: usize) { + self.s.face = face; + self.env.params.font.store(face as i32, Ordering::Relaxed); + self.cv.face = face; + } + fn about_paras(&self) -> &'static [&'static [&'static str]] { + ABOUT_TEXT + } + fn changelog(&self) -> &'static [(&'static str, &'static [&'static str])] { + CHANGELOG + } + fn manual_pdf(&self) -> Option<(&'static str, &'static [u8])> { + // the file must exist for the crate's current version (docs/manual/build.py), or the plug-in does not compile + Some(( + concat!("SatXComp-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf"), + include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/manual/SatXComp-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf")), + )) + } + fn draw_flow(&mut self, r: Rect, byp: bool) { + self.draw_flow_at(r, byp); + } + fn flow_h(&self) -> f32 { + 150.0 + } + fn about_scroll_drag_start(&mut self) {} +} + +fn hz(v: f32) -> String { + if v >= 10000.0 { + format!("{:.0}kHz", v * 0.001) + } else if v >= 1000.0 { + format!("{:.1}kHz", v * 0.001) + } else { + format!("{:.0}Hz", v) + } +} + +fn fmt_slot(n: usize, v: f32) -> String { + match n { + SC_GAIN => return format!("{:+.1}dB", v), + SC_HP | SC_LP => return hz(v), + SC_MIX => return format!("{:.0}%", v), + _ => {} + } + if (RANGE_BASE..RANGE_BASE + NB).contains(&n) { + return format!("{:.0}dB", v); + } + if XOV_SLOPE.contains(&n) { + return format!("{}dB", [12, 24, 48, 96][(v + 0.5).floor().clamp(0.0, 3.0) as usize]); + } + if (10..10 + 24 * NB).contains(&n) { + return match (n - 10) % 24 { + DRIVE | SAT_MIX | SPEED | KNEE_SHAPE | DETECTOR | FF_FB | GR_DIST | COMP_MIX => format!("{:.0}%", v), + BIAS => format!("{:+.0}%", v), + TONE | LP => { + if v >= 19900.0 { + "OFF".into() + } else if v >= 1000.0 { + format!("{:.1}k", v * 0.001) + } else { + format!("{:.0}", v) + } + } + HP => { + if v <= 20.5 { + "OFF".into() + } else if v >= 1000.0 { + format!("{:.1}k", v * 0.001) + } else { + format!("{:.0}", v) + } + } + SAT_GAIN | COMP_GAIN => format!("{:+.1}dB", v), + THRESH | KNEE => format!("{:.1}dB", v), + RATIO => { + if v >= 19.9 { + "INF".into() + } else { + format!("{:.1}:1", v) + } + } + ATTACK => { + if v < 1.0 { + format!("{:.2}ms", v) + } else { + format!("{:.1}ms", v) + } + } + RELEASE => { + if v >= 1990.0 { + "AUTO".into() + } else if v >= 1000.0 { + format!("{:.2}s", v * 0.001) + } else { + format!("{:.0}ms", v) + } + } + _ => format!("{:.1}", v), + }; + } + if (120..145).contains(&n) { + return match (n - 120) % 5 { + 2 => hz(v), + 3 => format!("{:.2}", v), + 4 => { + if v.abs() < 0.05 { + "0.0dB".into() + } else { + format!("{:+.1}dB", v) + } + } + _ => format!("{:.0}", v), + }; + } + match n { + EQ_TILT | EQ_GAIN => format!("{:+.1}dB", v), + EQ_PIVOT => hz(v), + EQ_MIX => format!("{:.0}%", v), + 1 | 2 | 9 => hz(v), + 4 => { + if v < 0.05 { + "OFF".into() + } else { + format!("{:.1}ms", v) + } + } + 5 => format!("{:.0}%", v), + 6 => format!("{:+.1}dB", v), + _ => format!("{:.1}", v), + } +} + +impl<'a> Gui<'a> { + fn sel(&self) -> usize { + (self.env.params.sel_band.load(Ordering::Relaxed).max(0) as usize).min(NB - 1) + } + + // ------------------------------------------------------------------ window size + fn cur_scale(&self) -> f32 { + self.env.params.editor_state.size().0 as f32 / super::W + } + + /// Ask the host to resize the editor to `scale` x the base size (aspect locked). + fn request_scale(&mut self, scale: f32) { + let sc = scale.clamp(SIZES[0], SIZES[SIZES.len() - 1]); + if (sc - self.cur_scale()).abs() > 0.001 { + self.env.params.editor_state.set_requested_size(((super::W * sc).round() as u32, (super::H * sc).round() as u32)); + } + } + + fn open_size_menu(&mut self, x: f32, y: f32) { + let items = SIZES.iter().enumerate().map(|(i, v)| MItem { label: format!("{:.0}%", v * 100.0), kind: 0, id: i as i32 }).collect(); + let cur = SIZES.iter().position(|v| (v - self.cur_scale()).abs() < 0.13).unwrap_or(0); + self.menu = Some(Menu { kind: MenuKind::Size, x, y, items, checked: cur as i32, scroll: 0 }); + } + + /// Bottom-right grip: drag = aspect-locked resize in 25% steps, right-click = size menu. + fn resize_grip(&mut self) { + let (gx, gy, gw, gh) = (super::W - 16.0, super::H - 16.0, 16.0, 16.0); + let hv = self.hit(gx, gy, gw, gh); + if hv && self.kit.press && self.kit.act == 0 { + self.resizing = true; + // distance from the pointer to the window's bottom-right corner, in window points + self.resize_off = (self.win_pt.0 - self.ptr_pt.0, self.win_pt.1 - self.ptr_pt.1); + self.kit.press = false; + } + if hv && self.kit.rpress { + self.open_size_menu(gx - 40.0, gy - 90.0); + self.kit.rpress = false; + } + if self.resizing { + if self.kit.down { + // Absolute target (pointer + fixed corner offset), independent of the lagging render scale. Only issue a new + // request once the host window has caught up with the last one, otherwise stale pointer/size pairs make the + // target overshoot and the window loops. + let (cw, _) = self.env.params.editor_state.size(); + if (self.win_pt.0 - cw as f32).abs() < 1.5 { + let w = (self.ptr_pt.0 + self.resize_off.0) / super::W; + let h = (self.ptr_pt.1 + self.resize_off.1) / super::H; + self.request_scale((w.min(h) * 4.0).round() / 4.0); + } + } else { + self.resizing = false; + } + } + self.set_dk(1.0); + self.setc(self.resizing); + for o in [4.0, 8.0, 12.0] { + self.cv.line(super::W - 1.0, super::H - 1.0 - o, super::W - 1.0 - o, super::H - 1.0); + } + self.setc(false); + } + + // ------------------------------------------------------------------ presets + fn preset_name(&self) -> String { + self.env.params.preset_name.lock().clone() + } + + fn set_preset_name(&mut self, n: &str) { + *self.env.params.preset_name.lock() = n.to_string(); + } + + /// Write every stored parameter of `p` (missing ids -> default) and the three curves (missing = linear, so a preset never + /// keeps the previous one's curve). Bypass / Gain Match are left alone, and so is the sidechain switch unless the preset + /// carries it (`presets::value_for`). + fn apply_preset(&mut self, p: &Preset) { + for &(n, id, mn, mx, df) in TABLE { + let Some(v) = presets::value_for(p, id, df) else { continue }; + self.click_set(n, v.clamp(mn, mx)); + } + for b in 0..NB { + let c = Curve::from_points(p.curve(b)); + self.curve_cell(b).lock().clone_from(&c.pts().to_vec()); + let a = crate::params::asym_from(p.asym(b)); + *self.env.params.asym_cell(b).lock() = a.iter().map(|&v| v as f32).collect(); + } + self.set_preset_name(&p.name); + self.base = None; + self.hold_until = self.kit.now + 0.6; + } + + fn curve_cell(&self, b: usize) -> &Arc>> { + match b { + 0 => &self.env.params.curve_lo, + 1 => &self.env.params.curve_mid, + 2 => &self.env.params.curve_mh, + _ => &self.env.params.curve_hi, + } + } + + /// True when the live parameters differ from the loaded preset (drives the *NAME* marker). + fn is_modified(&mut self) -> bool { + if self.kit.now < self.hold_until { + return false; // host parameter writes land a few frames late after a load + } + let cur = self.preset_name(); + let key = if cur.is_empty() { "INIT".to_string() } else { cur }; + if self.base.as_ref().map(|b| b.0 != key).unwrap_or(true) { + let p = if key == "INIT" && self.factory.iter().all(|f| f.name != "INIT") { + Some(Preset::init()) + } else { + self.preset_index().and_then(|i| self.preset_at(i)) + }; + self.base = p.map(|p| (key, p)); + } + let Some((_, b)) = &self.base else { return false }; + for &(n, id, mn, mx, df) in TABLE { + let Some(want) = presets::value_for(b, id, df) else { continue }; + let want = want.clamp(mn, mx); + let have = self.sget(n); + if (want - have).abs() > 2e-4 * want.abs().max(have.abs()) + 1e-4 { + return true; + } + } + (0..NB).any(|c| Curve::from_points(b.curve(c)) != self.env.params.curve_snapshot(c) || crate::params::asym_from(b.asym(c)) != self.env.params.asym_snapshot(c)) + } + + fn capture(&self, name: &str) -> Preset { + let params = TABLE + .iter() + .filter(|e| !presets::EXCLUDED.contains(&e.1)) + .map(|e| (e.1.to_string(), self.sget(e.0))) + .collect(); + let mut p = Preset::new(name, params); + let curves: Vec = (0..NB).map(|b| self.env.params.curve_snapshot(b)).collect(); + if curves.iter().any(|c| *c != Curve::linear()) { + p.curves = curves.iter().map(|c| c.pts().to_vec()).collect(); + } + let asyms: Vec<[f64; satxcomp_dsp::params::SHAPER_COUNT]> = (0..NB).map(|b| self.env.params.asym_snapshot(b)).collect(); + if asyms.iter().any(|a| a.iter().any(|&v| v != 100.0)) { + p.asym = asyms.iter().map(|a| a.iter().map(|&v| v as f32).collect()).collect(); + } + p + } + + fn preset_count(&self) -> usize { + self.factory.len() + self.user.len() + } + + fn preset_at(&self, i: usize) -> Option { + if i < self.factory.len() { + Some(self.factory[i].clone()) + } else { + let (name, path) = self.user.get(i - self.factory.len())?; + presets::load_file(path).map(|mut p| { + p.name = name.clone(); + p + }) + } + } + + fn preset_index(&self) -> Option { + let cur = self.preset_name(); + let cur = if cur.is_empty() { "INIT".to_string() } else { cur }; + self.factory + .iter() + .position(|p| p.name == cur) + .or_else(|| self.user.iter().position(|u| u.0 == cur).map(|i| i + self.factory.len())) + } + + fn step_preset(&mut self, dir: i32) { + self.user = presets::scan_user(); + let n = self.preset_count() as i32; + let next = match self.preset_index() { + Some(i) => (i as i32 + dir).rem_euclid(n), + None => { + if dir > 0 { + 0 + } else { + n - 1 + } + } + }; + if let Some(p) = self.preset_at(next as usize) { + self.apply_preset(&p); + } + } + + fn open_preset_menu(&mut self, x: f32, y: f32) { + self.user = presets::scan_user(); + let mut items = vec![ + MItem { label: "Initialize preset".into(), kind: 0, id: 1 }, + MItem { label: "Load preset...".into(), kind: 0, id: 0 }, + ]; + // factory[0] is the built-in INIT: it is the "Initialize preset" entry above, so not listed twice + if self.factory.len() > 1 { + items.push(MItem { label: String::new(), kind: 2, id: -1 }); + items.push(MItem { label: "FACTORY".into(), kind: 1, id: -1 }); + for (i, p) in self.factory.iter().enumerate().skip(1) { + items.push(MItem { label: p.name.clone(), kind: 0, id: 1000 + i as i32 }); + } + } + if !self.user.is_empty() { + items.push(MItem { label: String::new(), kind: 2, id: -1 }); + items.push(MItem { label: "USER".into(), kind: 1, id: -1 }); + for (i, u) in self.user.iter().enumerate() { + items.push(MItem { label: u.0.clone(), kind: 0, id: 2000 + i as i32 }); + } + } + let checked = match self.preset_index() { + Some(0) => 1, + Some(i) if i < self.factory.len() => 1000 + i as i32, + Some(i) => 2000 + (i - self.factory.len()) as i32, + None => -1, + }; + self.menu = Some(Menu { kind: MenuKind::Preset, x, y, items, checked, scroll: 0 }); + } + + fn preset_action(&mut self, id: i32) { + match id { + 0 => self.pending = 1, + 1 => self.apply_preset(&Preset::init()), + 1000..=1999 => { + if let Some(p) = self.preset_at((id - 1000) as usize) { + self.apply_preset(&p); + } + } + 2000.. => { + if let Some(p) = self.preset_at(self.factory.len() + (id - 2000) as usize) { + self.apply_preset(&p); + } + } + _ => {} + } + } + + /// File dialogs run on a worker thread: a modal NSSavePanel started inside our frame callback re-enters the host window's + /// event handling (resign-key) while the editor state is borrowed, which aborted REAPER. rfd dispatches the panel to the + /// main thread itself; the result is picked up by `poll_dialog`. + fn run_pending(&mut self) { + let what = std::mem::take(&mut self.pending); + if what == 0 || self.dlg.is_some() { + return; + } + let slot = Arc::new(parking_lot::Mutex::new(Dlg::Pending)); + self.dlg = Some(slot.clone()); + match what { + 1 => { + std::thread::spawn(move || { + let r = presets::open_dialog().and_then(|path| { + presets::load_file(&path).map(|mut p| { + if let Some(stem) = path.file_stem() { + p.name = stem.to_string_lossy().into_owned(); + } + p + }) + }); + *slot.lock() = r.map_or(Dlg::Cancelled, Dlg::Loaded); + }); + } + 2 => { + let cur = self.preset_name(); + let def = if cur.is_empty() || cur == "INIT" { "My preset".to_string() } else { cur }; + let snapshot = self.capture(&def); // parameters as of the click + std::thread::spawn(move || { + let r = presets::save_dialog(&def).and_then(|path| { + let name = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or(def); + let mut p = snapshot; + p.name = name.clone(); + presets::save_file(&path, &p).ok().map(|_| name) + }); + *slot.lock() = r.map_or(Dlg::Cancelled, Dlg::Saved); + }); + } + _ => self.dlg = None, + } + } + + /// Apply the outcome of a finished file dialog (called every frame). + fn poll_dialog(&mut self) { + let Some(slot) = self.dlg.clone() else { return }; + let r = std::mem::replace(&mut *slot.lock(), Dlg::Pending); + match r { + Dlg::Pending => return, + Dlg::Loaded(p) => self.apply_preset(&p), + Dlg::Saved(name) => { + self.set_preset_name(&name); + self.base = None; + self.user = presets::scan_user(); + } + Dlg::Cancelled => {} + } + self.dlg = None; + } + + /// Header preset bar (save icon | name | prev next) and the window-scale button. + fn preset_bar(&mut self) { + let (y, h) = (8.0, 16.0); + if self.btn(152.0, y, 26.0, h, "", 0) { + self.pending = 2; + } + self.setc(false); + self.cv.boxr(160.0, y + 3.0, 10.0, 10.0); + self.cv.fill(163.0, y + 3.0, 4.0, 3.0); + self.cv.boxr(162.0, y + 8.0, 6.0, 5.0); + // name -> dropdown + let name = self.preset_name(); + let shown = if name.is_empty() || name == "INIT" { "-- INIT --".to_string() } else { name }; + let hv = self.hit(178.0, y, 122.0, h); + if hv && self.kit.press && self.kit.act == 0 { + self.open_preset_menu(178.0, y + h); + self.kit.press = false; + } + self.setc(false); + self.cv.boxr(178.0, y, 122.0, h); + self.cv.set_font(2); + let modified = self.is_modified(); + self.shown_modified = modified; + let mut t = shown; + while self.cv.text_w(&t) > if modified { 104.0 } else { 116.0 } && t.chars().count() > 3 { + t.pop(); + } + if modified { + t = format!("*{t}*"); + } + self.cv.textc(178.0, y + ((h - 8.0) * 0.5).floor(), 122.0, &t); + // prev / next + for (i, dir) in [(0, -1), (1, 1)] { + let x = 300.0 + i as f32 * 25.0; + if self.btn(x, y, 25.0, h, "", 0) { + self.step_preset(dir); + } + self.setc(false); + let (cx, cy) = (x + 12.5, y + h * 0.5); + if dir < 0 { + self.cv.tri((cx + 2.0, cy - 3.0), (cx + 2.0, cy + 3.0), (cx - 2.0, cy)); + } else { + self.cv.tri((cx - 2.0, cy - 3.0), (cx - 2.0, cy + 3.0), (cx + 2.0, cy)); + } + } + // window scale + let label = format!("{:.0}%", self.cur_scale() * 100.0); + if self.btn(356.0, y, 42.0, h, &label, 0) { + self.open_size_menu(356.0, y + h); + } + } + + fn select_band(&mut self, b: usize) { + let old = self.sel(); + if b != old { + self.curve_edit = false; // the draw view belongs to one band + // SOLO and DELTA follow the selected band: whichever of them is on for the band being left moves to the new one + for off in [SOLO, DELTA] { + if self.sget(band_base(old) + off) > 0.5 { + self.click_set(band_base(old) + off, 0.0); + self.click_set(band_base(b) + off, 1.0); + } + } + } + self.env.params.sel_band.store(b as i32, Ordering::Relaxed); + } + + // ------------------------------------------------------------------ header + /// plug-in icon: click = next colour scheme, double click = light / dark, right click = scheme dropdown + fn logo(&mut self, x: f32, y: f32) { + let hv = self.hit(x - 3.0, y - 3.0, 27.0, 27.0); + if hv && self.kit.press && self.kit.act == 0 { + // single click = next scheme (after the double-click window), double click = light/dark + if self.logo_pend >= 0.0 && self.kit.now - self.logo_pend < 0.3 { + self.logo_pend = -1.0; + self.set_light(!self.light); + } else { + self.logo_pend = self.kit.now; + } + self.kit.press = false; + } + if self.logo_pend >= 0.0 && self.kit.now - self.logo_pend >= 0.3 { + self.logo_pend = -1.0; + let n = self.app.n_schemes(); + self.set_pal((self.pal + 1) % n); + } + if hv && self.kit.rpress { + self.logo_pend = -1.0; + let mut items = vec![MItem { label: format!("MODE: {}", if self.light { "LIGHT" } else { "DARK" }), kind: 0, id: 1000 }]; + items.push(MItem { label: String::new(), kind: 2, id: -1 }); + items.extend((0..self.app.n_schemes()).map(|i| MItem { label: self.app.scheme_name(i), kind: 0, id: i as i32 })); + self.menu = Some(Menu { kind: MenuKind::Palette, x, y: y + 22.0, items, checked: self.pal as i32, scroll: 0 }); + } + self.setc(false); + // hovering inverts the icon (a plate in the UI colour, or back to the outline in light mode): it is clickable + if self.light != hv { + self.cv.fill(x - 3.0, y - 3.0, 27.0, 27.0); + self.cv.setbg(); + } else { + self.cv.boxr(x - 3.0, y - 3.0, 27.0, 27.0); + self.setc(false); + } + self.cv.boxr(x + 6.0, y + 6.0, 9.0, 9.0); + let l = |c: &Canvas, a: f32, b: f32, cc: f32, d: f32| c.line(x + a, y + b, x + cc, y + d); + l(&self.cv, 12.5, 0.5, 20.5, 0.5); + l(&self.cv, 20.5, 0.5, 20.5, 7.5); + l(&self.cv, 8.5, 20.5, 0.5, 20.5); + l(&self.cv, 0.5, 20.5, 0.5, 13.5); + l(&self.cv, 6.5, 14.5, 0.5, 20.5); + l(&self.cv, 14.5, 6.5, 20.5, 0.5); + // second diagonal: the X of SatXComp + l(&self.cv, 6.5, 6.5, 0.5, 0.5); + l(&self.cv, 14.5, 14.5, 20.5, 20.5); + } + + fn out_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { + let rw = 8.0; + let bw = w - rw - 2.0; + let bh = ((h - 3.0) * 0.5).floor(); + let sh = self.env.shared; + let pa = sh.opk[0].swap(0.0, Ordering::Relaxed); + let pb = sh.opk[1].swap(0.0, Ordering::Relaxed); + if sh.clip.swap(false, Ordering::Relaxed) { + self.clip_lat = true; + } + if self.hit(x, y, w, h) && self.kit.press && self.kit.act == 0 { + self.opk_max = 0.0; + self.clip_lat = false; + self.hl_l = 0.0; + self.hl_r = 0.0; + self.kit.press = false; + } + self.ovl = pa.max(self.ovl * 0.85); + self.ovr = pb.max(self.ovr * 0.85); + let now = self.kit.now; + if pa >= self.hl_l { + self.hl_l = pa; + self.hl_l_t = now; + } else if now - self.hl_l_t > 1.0 { + self.hl_l *= 0.9; + } + if pb >= self.hl_r { + self.hl_r = pb; + self.hl_r_t = now; + } else if now - self.hl_r_t > 1.0 { + self.hl_r *= 0.9; + } + self.opk_max = self.opk_max.max(pa.max(pb)); + let lvf = |v: f32| ((8.6858896 * v.max(0.0000001).ln() + 48.0) / 48.0).clamp(0.0, 1.0); + self.setc(false); + self.cv.boxr(x, y, bw, h); + self.cv.fill(x + 1.0, y + 1.0, ((bw - 2.0) * lvf(self.ovl)).floor(), bh); + self.cv.fill(x + 1.0, y + 2.0 + bh, ((bw - 2.0) * lvf(self.ovr)).floor(), bh); + if self.hl_l > 0.0001 { + self.cv.fill(x + 1.0 + ((bw - 3.0) * lvf(self.hl_l)).floor(), y + 1.0, 1.0, bh); + } + if self.hl_r > 0.0001 { + self.cv.fill(x + 1.0 + ((bw - 3.0) * lvf(self.hl_r)).floor(), y + 2.0 + bh, 1.0, bh); + } + if self.clip_lat { + self.setc(true); + self.cv.fill(x + bw + 2.0, y, rw, h); + } else { + self.setc(false); + self.cv.boxr(x + bw + 2.0, y, rw, h); + } + self.setc(false); + } + + /// Colour of gain that is ADDED (the spectrum's gain area and the upward compressor's lift): the inverse of the accent. + fn gain_colour(&self) -> [f32; 3] { + satcomp_ui::canvas::gain_colour(self.cv.bk, self.cv.fg, self.cv.ac) + } + + // ------------------------------------------------------------------ meters + fn update_gr(&mut self) { + let sh = self.env.shared; + let now = self.kit.now; + for b in 0..NB { + let g = sh.gr_pk[b].swap(0.0, Ordering::Relaxed); + self.gr_disp[b] = g.max(self.gr_disp[b] * 0.9); + if g >= self.gr_hold[b] { + self.gr_hold[b] = g; + self.gr_hold_t[b] = now; + } else if now - self.gr_hold_t[b] > 1.0 { + self.gr_hold[b] = (self.gr_hold[b] - 0.4).max(0.0); + } + self.gr_txt_pk[b] = self.gr_txt_pk[b].max(self.gr_disp[b]); + // upward compressor lift: same ballistics, shown by the centre-tapped meter + let l = sh.gl_pk[b].swap(0.0, Ordering::Relaxed); + self.gl_disp[b] = l.max(self.gl_disp[b] * 0.9); + if l >= self.gl_hold[b] { + self.gl_hold[b] = l; + self.gl_hold_t[b] = now; + } else if now - self.gl_hold_t[b] > 1.0 { + self.gl_hold[b] = (self.gl_hold[b] - 0.4).max(0.0); + } + self.gl_txt_pk[b] = self.gl_txt_pk[b].max(self.gl_disp[b]); + // post-saturator level meter + let pk = sh.sat_out_pk[b].swap(0.0, Ordering::Relaxed); + self.vu[b] = pk.max(self.vu[b] * 0.85); + if pk >= self.vu_hold[b] { + self.vu_hold[b] = pk; + self.vu_hold_t[b] = now; + } else if now - self.vu_hold_t[b] > 1.0 { + self.vu_hold[b] *= 0.9; + } + if pk >= 1.0 { + self.vu_clip_t[b] = now; + } + } + let lg = sh.lim_gr_pk.swap(0.0, Ordering::Relaxed); + self.lim_disp = lg.max(self.lim_disp * 0.9); + self.lim_txt_pk = self.lim_txt_pk.max(self.lim_disp); + if now - self.gr_txt_t >= 0.25 { + self.lim_txt = self.lim_txt_pk; + self.lim_txt_pk = 0.0; + self.gr_txt = self.gr_txt_pk; + self.gr_txt_pk = [0.0; NB]; + self.gl_txt = self.gl_txt_pk; + self.gl_txt_pk = [0.0; NB]; + self.gr_txt_t = now; + } + } + + /// vertical gain-reduction meter of the selected band; click cycles the range (3 / 6 / 12 / 18 dB) + fn draw_gr_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { + let b = self.sel(); + if self.hit(x, y, w, h) && self.kit.press && self.kit.act == 0 { + self.gr_ri = if self.gr_ri >= 3 { 0 } else { self.gr_ri + 1 }; + self.kit.press = false; + } + if self.sget(band_base(b) + UP) > 0.5 { + self.draw_gr_meter_up(x, y, w, h, b); + return; + } + let rng = |i: usize| [3.0f32, 6.0, 12.0, 18.0][i.min(3)]; + while self.gr_ri < 3 && self.gr_disp[b] > rng(self.gr_ri) { + self.gr_ri += 1; + } + let rg = rng(self.gr_ri); + self.setc(false); + self.cv.boxr(x, y, w, h); + self.setc(true); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, ((h - 2.0) * (self.gr_disp[b] / rg).min(1.0)).floor()); + self.setc(false); + let hp = y + 1.0 + ((h - 3.0) * (self.gr_hold[b] / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, hp, w - 2.0, 1.0); + self.cv.set_font(1); + // compressor GR as a number in a window at the top of the bar (positive, like the bar; slow refresh) + self.cv.setbg(); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, 11.0); + self.setc(false); + self.cv.fill(x + 1.0, y + 12.0, w - 2.0, 1.0); + let gs = format!("{:.1}", self.gr_txt[b]); + self.cv.textc(x, y + 3.0, w, &gs); + let mj = if rg == 3.0 { 1.0 } else if rg == 6.0 { 2.0 } else if rg == 12.0 { 3.0 } else { 6.0 }; + let stp = if rg <= 6.0 { 0.5 } else { 1.0 }; + for j in 1..=((rg / stp) as i32) { + let v = j as f32 * stp; + let ty = y + 1.0 + (h - 2.0) * (v / rg); + if v == v.floor() && (v.floor() % mj) == 0.0 { + self.cv.fill(x + w - 5.0, ty, 4.0, 1.0); + let s = format!("{}", v as i32); + self.cv.text(x + 2.0, (ty - 4.0).min(y + h - 11.0), &s); + } else { + self.cv.fill(x + w - 3.0, ty, 2.0, 1.0); + } + } + } + + /// The meter of a band in upward mode: centre-tapped. Gain LIFT grows upward from the centre line in the spectrum's gain + /// colour (inverse of the accent), gain reduction (the band is not reducing in this mode, but the scale stays symmetric) + /// grows downward in the accent. Same range cycling as the plain meter; the number window shows the lift. + fn draw_gr_meter_up(&mut self, x: f32, y: f32, w: f32, h: f32, b: usize) { + let both = self.sget(band_base(b) + UP) > 1.5; + let rng = |i: usize| [3.0f32, 6.0, 12.0, 18.0][i.min(3)]; + let peak = self.gl_disp[b].max(self.gr_disp[b]); + while self.gr_ri < 3 && peak > rng(self.gr_ri) { + self.gr_ri += 1; + } + let rg = rng(self.gr_ri); + let inv = self.gain_colour(); + let cy = y + (h * 0.5).floor(); + let half = ((h - 2.0) * 0.5).floor(); + self.setc(false); + self.cv.boxr(x, y, w, h); + // lift up from the centre, reduction down from it + self.cv.setrgb(inv); + let up_px = (half * (self.gl_disp[b] / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, cy - up_px, w - 2.0, up_px); + self.setc(true); + let dn_px = (half * (self.gr_disp[b] / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, cy + 1.0, w - 2.0, dn_px); + // holds + self.setc(false); + let hu = cy - (half * (self.gl_hold[b] / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, hu, w - 2.0, 1.0); + let hd = cy + 1.0 + (half * (self.gr_hold[b] / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, hd, w - 2.0, 1.0); + // centre line + self.cv.fill(x + 1.0, cy, w - 2.0, 1.0); + self.cv.set_font(1); + // number window at the top: the lift, in the gain colour + self.cv.setbg(); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, 11.0); + self.setc(false); + self.cv.fill(x + 1.0, y + 12.0, w - 2.0, 1.0); + let l = self.gl_txt[b]; + let gs = if l >= 9.95 { format!("+{:.0}", l) } else if l > 0.04 { format!("+{:.1}", l) } else { "0.0".to_string() }; + self.cv.setrgb(inv); + self.cv.textc(x, y + 3.0, w, &gs); + self.setc(false); + // UP/DWN also reduces: a second number window at the bottom, in the accent colour + if both { + self.cv.setbg(); + self.cv.fill(x + 1.0, y + h - 12.0, w - 2.0, 11.0); + self.setc(false); + self.cv.fill(x + 1.0, y + h - 13.0, w - 2.0, 1.0); + let r = self.gr_txt[b]; + let rs = if r > 0.04 { format!("-{:.1}", r) } else { "0.0".to_string() }; + self.setc(true); + self.cv.textc(x, y + h - 10.0, w, &rs); + self.setc(false); + } + // scale: ticks and numbers mirrored around the centre + let mj = if rg == 3.0 { 1.0 } else if rg == 6.0 { 2.0 } else if rg == 12.0 { 3.0 } else { 6.0 }; + let stp = if rg <= 6.0 { 0.5 } else { 1.0 }; + for j in 1..=((rg / stp) as i32) { + let v = j as f32 * stp; + let off = (half + 1.0) * (v / rg); + for (ty, dir) in [(cy + off, 1.0f32), (cy - off, -1.0)] { + if (dir < 0.0 && ty < y + 13.0) || (both && dir > 0.0 && ty > y + h - 13.0) { + continue; // under a number window + } + if v == v.floor() && (v.floor() % mj) == 0.0 { + self.cv.fill(x + w - 5.0, ty, 4.0, 1.0); + let s = format!("{}", v as i32); + self.cv.text(x + 2.0, (ty - 4.0).clamp(y + 14.0, y + h - if both { 24.0 } else { 11.0 }), &s); + } else { + self.cv.fill(x + w - 3.0, ty, 2.0, 1.0); + } + } + } + } + + fn diff_box(&mut self, x: f32, y: f32, w: f32, h: f32) { + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.set_font(1); + self.cv.text(x + 3.0, y + 3.0, "IN>OUT"); + self.cv.set_font(2); + let s = format!("{:+.1}dB", self.rd_diff); + self.cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, &s); + let cx = x + (w * 0.5).floor(); + let d = self.env.shared.diff_disp.load(Ordering::Relaxed).clamp(-12.0, 12.0) / 12.0; + let bw = (d.abs() * (w * 0.5 - 3.0)).floor(); + if d >= 0.0 { + self.cv.fill(cx, y + h - 4.0, bw, 2.0); + } else { + self.cv.fill(cx - bw, y + h - 4.0, bw, 2.0); + } + self.cv.fill(cx, y + h - 6.0, 1.0, 5.0); + } + + // ------------------------------------------------------------------ viewport: spectrum + crossover + fn draw_spectrum(&mut self, x: f32, y: f32, w: f32, h: f32) { + let sh = self.env.shared; + sh.spec_vis_ms.store(sh.now_ms(), Ordering::Relaxed); + let now = self.kit.now; + let sr = sh.sample_rate.load(Ordering::Relaxed); + { + let t = &sh.tap_out; + self.s.spec_out.update(now, t.w.load(Ordering::Acquire), |i| t.get(i)); + let t = &sh.tap_dry; + self.s.spec_dry.update(now, t.w.load(Ordering::Acquire), |i| t.get(i)); + } + let n = (w - 2.0) as usize; + let (co, cd) = (self.spec_out.columns(n, sr), self.spec_dry.columns(n, sr)); + let hh = |v: f32| (((v + 100.0) / 95.0).clamp(0.0, 1.0) * (h - 2.0)).floor(); + let inv = self.gain_colour(); + // spectrum look (Appearance): solid UI-colour fill under the output, or background fill with a stroke (accent shows the gap to dry) + let solid = self.env.params.fft_solid.load(Ordering::Relaxed); + self.setc(false); + self.cv.boxr(x, y, w, h); + let mut prev: Option = None; + for i in 0..n { + let (ho, hd) = (hh(co[i]), hh(cd[i])); + let (lo, hi) = (ho.min(hd), ho.max(hd)); + self.setc(false); + if solid && lo > 0.0 { + self.cv.fill(x + 1.0 + i as f32, y + h - 1.0 - lo, 1.0, lo); + } + if hi > lo { + // between output and dry: accent = the compressor took it away, inverted accent = output is above dry + if hd > ho { + self.setc(true); + } else { + self.cv.setrgb(inv); + } + self.cv.fill(x + 1.0 + i as f32, y + h - 1.0 - hi, 1.0, hi - lo); + } + if !solid { + // white stroke along the output spectrum, joined to its neighbour so steep edges stay connected + self.setc(false); + let (a, b) = match prev { + Some(p) => (p.min(ho), p.max(ho)), + None => (ho, ho), + }; + self.cv.fill(x + 1.0 + i as f32, y + h - 1.0 - b, 1.0, (b - a).max(1.0)); + } + prev = Some(ho); + } + self.setc(false); + } + + fn draw_crossover(&mut self, x: f32, y: f32, w: f32, h: f32) { + let mut f = [self.env.dsp.x1 as f32, self.env.dsp.x2 as f32, self.env.dsp.x3 as f32]; + f[1] = f[1].max(f[0] * 1.05); + f[2] = f[2].max(f[1] * 1.05); + let px: Vec = f.iter().map(|&v| freq_to_x(v, x + 1.0, w - 2.0)).collect(); + // drag a crossover line (the nearest one within 6 px) + if self.hit(x, y, w, h) && self.kit.press && self.kit.act == 0 { + let (k, d) = (0..3).map(|k| (k, (self.kit.mx - px[k]).abs())).fold((0, f32::MAX), |a, c| if c.1 < a.1 { c } else { a }); + if d < 6.0 { + self.kit.act = [ACT_X1, ACT_X2, ACT_X3][k]; + self.kit.press = false; + } + } + for k in 0..3 { + let act = [ACT_X1, ACT_X2, ACT_X3][k]; + if self.kit.act == act && self.kit.down { + let v = x_to_freq(self.kit.mx, x + 1.0, w - 2.0); + let lo = if k == 0 { 20.0 } else { f[k - 1] * 1.05 }; + let hi = if k == 2 { 20000.0 } else { f[k + 1] / 1.05 }; + self.setv(XOV[k], v.clamp(lo, hi.max(lo))); + } + } + let active = self.kit.act; + // dotted lines + self.setc(false); + for k in 0..3 { + let lit = active == [ACT_X1, ACT_X2, ACT_X3][k]; + if lit { + self.setc(true); + } + let mut yy = y + 1.0; + while yy < y + h - 2.0 { + self.cv.fill(px[k].floor(), yy, 1.0, 2.0); + yy += 4.0; + } + self.setc(false); + } + // Band handles. The handle sits at the band's threshold on the spectrum's dB axis: drag = threshold (double-click = + // default), click = select. A line marks the band's frequency range, a small bar hangs from the handle for the gain + // reduction, and a horizontal bar on top of it shows the band's level change (left = quieter, right = louder). + let sel = self.sel(); + let edges = [x + 1.0, px[0], px[1], px[2], x + w - 1.0]; + let y_of = |t: f32| y + h - 1.0 - ((t + 100.0) / 95.0).clamp(0.0, 1.0) * (h - 2.0); + for b in 0..NB { + let o = band_base(b); + let (lo_f, hi_f) = (if b == 0 { 20.0 } else { f[b - 1] }, if b == NB - 1 { 20000.0 } else { f[b] }); + let cx = freq_to_x((lo_f * hi_f).sqrt(), x + 1.0, w - 2.0).floor(); + let (bw, bx) = if b == sel { (26.0, cx - 13.0) } else { (18.0, cx - 9.0) }; + let cyy = y_of(self.sget(o + THRESH)).clamp(y + 11.0, y + h - 7.0).floor(); + let by = cyy - 6.0; + if self.hit(bx, by, bw, 12.0) && self.kit.press && self.kit.act == 0 { + self.select_band(b); + if self.dbl(160 + b as i32) { + let d = self.kit.meta[o + THRESH].def; + self.click_set(o + THRESH, d); + } else { + self.kit.act = ACT_THR + b as i32; + } + self.kit.press = false; + } + if self.kit.act == ACT_THR + b as i32 && self.kit.down { + let t = (y + h - 1.0 - self.kit.my) / (h - 2.0) * 95.0 - 100.0; + self.setv(o + THRESH, t.clamp(-40.0, 0.0)); + } + let on = self.sget(o + ON) > 0.5; + let held = self.kit.act == ACT_THR + b as i32; + // range line + self.setc(false); + let (xl, xr) = (edges[b], edges[b + 1]); + self.cv.fill(xl.floor(), cyy, (xr - xl).floor().max(1.0), 1.0); + // gain reduction bar from the centre of the handle, 2 px per dB + let gr = self.gr_disp[b]; + if gr > 0.05 && on { + self.setc(true); + self.cv.fill(cx - 1.0, by + 12.0, 3.0, (gr * 2.0).min(36.0).floor().max(1.0)); + } + // upward compressor lift: a bar rising from the top of the handle, above the level-change tick, in the gain colour + let gl = self.gl_disp[b]; + if gl > 0.05 && on { + let room = (by - 6.0 - y - 1.0).max(0.0); + let lh = (gl * 2.0).min(36.0).min(room).floor().max(1.0); + let ic = self.gain_colour(); + self.cv.setrgb(ic); + self.cv.fill(cx - 1.0, by - 6.0 - lh, 3.0, lh); + } + // level change across the band on top of the handle: centre tick, bar to the left (accent) or right + let d = if on { self.env.shared.band_diff[b].load(Ordering::Relaxed).clamp(-12.0, 12.0) } else { 0.0 }; + let half = ((bw * 0.5 + 2.0) * d.abs() / 12.0).floor(); + self.setc(d < -0.05); + if d < 0.0 { + self.cv.fill(cx - half, by - 4.0, half, 2.0); + } else { + self.cv.fill(cx + 1.0, by - 4.0, half, 2.0); + } + self.setc(false); + self.cv.fill(cx, by - 5.0, 1.0, 4.0); + self.setc(held); + if b == sel { + self.cv.fill(bx, by, bw, 12.0); + self.cv.setbg(); + } else { + self.cv.setbg(); + self.cv.fill(bx, by, bw, 12.0); + self.setc(held); + self.cv.boxr(bx, by, bw, 12.0); + } + self.cv.set_font(1); + self.cv.textc(bx, by + 2.0, bw, BAND_LETTERS[b]); + self.setc(false); + } + } + + /// Post-saturator level of the selected band: digital bar (-48..0 dB), accent stroke on top while it clips (held ~1 s). + fn draw_vu(&mut self, x: f32, y: f32, w: f32, h: f32) { + let b = self.sel(); + self.setc(false); + self.cv.boxr(x, y, w, h); + let lvf = |v: f32| ((8.6858896 * v.max(0.0000001).ln() + 48.0) / 48.0).clamp(0.0, 1.0); + let ih = h - 2.0; + let lh = (ih * lvf(self.vu[b])).floor(); + if lh > 0.0 { + self.cv.fill(x + 1.0, y + h - 1.0 - lh, w - 2.0, lh); + } + // segment gaps give the digital look + self.cv.setbg(); + let mut k = 2.0; + while k < ih { + self.cv.fill(x + 1.0, y + h - 1.0 - k, w - 2.0, 1.0); + k += 3.0; + } + // held peak + self.setc(false); + if self.vu_hold[b] > 0.0001 { + let hy = (ih * lvf(self.vu_hold[b])).floor().max(1.0); + self.cv.fill(x + 1.0, y + h - 1.0 - hy, w - 2.0, 1.0); + } + // scale ticks every 6 dB + for db in (0..=48).step_by(6) { + let ty = y + 1.0 + ih * (db as f32 / 48.0); + self.cv.fill(x + w - 4.0, ty.floor(), 3.0, 1.0); + } + if self.kit.now - self.vu_clip_t[b] < 1.0 { + self.setc(true); + self.cv.fill(x + 1.0, y + 1.0, w - 2.0, 3.0); + } + self.setc(false); + } + + // ------------------------------------------------------------------ band modules + /// shape selector: [<] NAME [>]; click the name or right-click anywhere for the full list + /// ASYM of the selected band's current shaper: how much of the shaper's even part (the part that carries DC and sub-audio + /// pulses) is kept. One value per shaper, stored in the project / presets (not a host parameter). Drag, wheel, double-click = 100 %. + fn asym_cell(&mut self, b: usize, x: f32, y: f32, w: f32, h: f32) { + let shape = ((self.sget(band_base(b) + SHAPE) + 0.5).floor() as i32).clamp(0, CUSTOM) as usize; + let cell = self.env.params.asym_cell(b).clone(); + let get = || crate::params::asym_from(&cell.lock())[shape] as f32; + let set = |v: f32| { + let mut g = cell.lock(); + if g.len() < SHAPER_NAMES.len() { + g.resize(SHAPER_NAMES.len(), 100.0); + } + g[shape] = v.clamp(0.0, 100.0); + }; + let hv = self.hit(x, y, w, h); + if hv && self.kit.press && self.kit.act == 0 { + if self.dbl(170 + b as i32) { + set(100.0); + } else { + self.kit.act = ACT_ASYM; + self.asym_drag = (self.kit.my, get() * 0.01); + } + self.kit.press = false; + } + if hv && self.kit.wheel != 0 { + let d = if self.kit.wheel > 0 { 1.0 } else { -1.0 } * if self.kit.shift { 0.5 } else { 3.0 }; + set((get() + d).round()); + } + if self.kit.act == ACT_ASYM && self.kit.down { + let k = if self.kit.shift { 0.0008 } else { 0.006 }; + let t = (self.asym_drag.1 + (self.asym_drag.0 - self.kit.my) * k).clamp(0.0, 1.0); + set((t * 100.0).round()); + } + let v = get(); + let act = self.kit.act == ACT_ASYM; + self.setc(act); + self.cv.boxr(x, y, w, h); + self.cv.set_font(1); + let ty = y + ((h - 8.0) * 0.5).floor(); + self.cv.text(x + 3.0, ty, "ASYM"); + self.cv.textr(x, ty, w - 3.0, &format!("{:.0}%", v)); + self.cv.fill(x + 2.0, y + h - 3.0, (((v * 0.01) * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(false); + } + + fn shape_selector(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32) { + let aw = 16.0; + let cy = y + h * 0.5; + let hv = self.hit(x, y, w, h); + let mut sel = (self.sget(n) + 0.5).floor() as i32; + if hv && self.kit.wheel != 0 { + let d = if self.kit.wheel > 0 { -1 } else { 1 }; + self.click_set(n, (sel + d).clamp(0, CUSTOM) as f32); + } + let open = |s: &mut Self| { + let items = SHAPER_NAMES.iter().enumerate().map(|(i, n)| MItem { label: n.to_string(), kind: 0, id: i as i32 }).collect(); + let band = s.sel(); + s.menu = Some(Menu { kind: MenuKind::Shape(band), x, y: y + h, items, checked: sel, scroll: 0 }); + }; + if hv && self.kit.rpress { + open(self); + self.kit.rpress = false; + } + if hv && self.kit.press && self.kit.act == 0 { + if self.kit.mx < x + aw { + self.click_set(n, if sel <= 0 { CUSTOM as f32 } else { (sel - 1) as f32 }); + } else if self.kit.mx >= x + w - aw { + self.click_set(n, if sel >= CUSTOM { 0.0 } else { (sel + 1) as f32 }); + } else { + open(self); + } + self.kit.press = false; + } + sel = (self.sget(n) + 0.5).floor() as i32; + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.fill(x + aw, y, 1.0, h); + self.cv.fill(x + w - aw - 1.0, y, 1.0, h); + self.cv.tri((x + aw * 0.5 + 2.0, cy - 3.0), (x + aw * 0.5 + 2.0, cy + 3.0), (x + aw * 0.5 - 2.0, cy)); + self.cv.tri((x + w - aw * 0.5 - 2.0, cy - 3.0), (x + w - aw * 0.5 - 2.0, cy + 3.0), (x + w - aw * 0.5 + 2.0, cy)); + self.cv.set_font(2); + let name = SHAPER_NAMES[sel.clamp(0, CUSTOM) as usize].to_uppercase(); + self.cv.textc(x + aw, y + ((h - 8.0) * 0.5).floor(), w - 2.0 * aw, &name); + } + + // ------------------------------------------------------------------ About page: signal flow + /// IN > crossover > three SAT + COMP bands > sum > EQ > OUT. A band is lit while it takes gain reduction, dim when switched + /// off; the EQ is lit when it does something and dim when bypassed; the sidechain key drops into the compressors. + fn draw_flow_at(&mut self, r: Rect, _byp: bool) { + let prev = self.kit.dk; + let sh = self.env.shared; + self.setc(false); + self.cv.boxr(r.x, r.y, r.w, r.h); + self.cv.set_font(1); + self.cv.text(r.x + 6.0, r.y + 5.0, "SIGNAL FLOW"); + let eq = self.env.dsp.eq; + let eq_any = eq.bands.iter().any(|b| b.on) || eq.tilt != 0.0 || eq.gain != 0.0; + let eq_byp = self.sget(EQ_BYPASS) > 0.5; + let sc_on = self.sget(SC_ON) > 0.5; + let lim_on = self.sget(LIM_ON) > 0.5; + let (bh, bwb) = (22.0f32, 92.0f32); + // main line: IN, X-OVER, [four bands], SUM, EQ, LIM, OUT. The diagram is centred: the gaps share what the widths leave over + let w = [24.0f32, 58.0, bwb, 34.0, 30.0, 30.0, 30.0]; + let gw = [1.0f32, 2.0, 2.0, 1.2, 1.2, 1.2]; + let unit = (r.w - 24.0 - w.iter().sum::()) / gw.iter().sum::(); + let mut bx = [0.0f32; 7]; + let mut cx = r.x + 12.0; + for i in 0..7 { + bx[i] = cx.floor(); + cx += w[i] + if i < 6 { gw[i] * unit } else { 0.0 }; + } + // the band rows are centred between the title and the caption; the main line runs at their middle + let mid = ((r.y + 24.0) + (r.y + r.h - 22.0)) * 0.5; + let cy = (mid - bh * 0.5).floor(); + let (bhb, step) = (18.0f32, 22.0f32); + let top = (mid - (3.0 * step + bhb) * 0.5).floor(); + let ys: [f32; NB] = std::array::from_fn(|i| top + i as f32 * step); + let ym: [f32; NB] = std::array::from_fn(|i| ys[i] + bhb * 0.5); + let my = cy + 11.0; + // signal levels for the flowing dots: input side (loudest band input), per band in / out, output + let lvf = |v: f32| ((8.6858896 * v.max(1e-7).ln() + 48.0) / 48.0).clamp(0.0, 1.0); + let lo = lvf(self.ovl.max(self.ovr)); + let mut b_in = [0.0f32; NB]; + let mut b_out = [0.0f32; NB]; + for b in 0..NB { + let on = self.sget(band_base(b) + ON) > 0.5; + b_in[b] = lvf(sh.sat_vz[b].load(Ordering::Relaxed)); + b_out[b] = if on { (lvf(self.vu[b]) - self.gr_disp[b] / 48.0).max(0.0) } else { b_in[b] }; + } + let inl = b_in.iter().cloned().fold(0.0, f32::max); + let phase = ((self.kit.now * 26.0) as f32) % 6.0; + // dots walk along a polyline, 6 px apart, sized by level (the animated "dashes" of the flow) + let along = |c: &Canvas, pts: &[(f32, f32)], lv: f32| { + if lv <= 0.02 { + return; + } + let sz = (1.0 + lv * 2.99).floor(); + let (mut acc, mut d) = (0.0f32, phase); + for sg in pts.windows(2) { + let (a, b) = (sg[0], sg[1]); + let len = (b.0 - a.0).abs() + (b.1 - a.1).abs(); + while d < acc + len && len > 0.0 { + let t = (d - acc) / len; + let (px, py) = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t); + c.fill((px - sz * 0.5).floor(), (py - sz * 0.5).floor() + 0.5, sz, sz); + d += 6.0; + } + acc += len; + } + }; + let arrow = |c: &Canvas, x0: f32, x1: f32, y: f32| { + c.fill(x0, y, x1 - x0 - 3.0, 1.0); + c.tri((x1 - 4.0, y - 3.0), (x1 - 4.0, y + 4.0), (x1, y + 0.5)); + }; + // ---- lines, arrows and flowing dots + self.setc(false); + let fork = (bx[1] + w[1] + ((bx[2] - bx[1] - w[1]) * 0.5).floor()).floor(); + let join = (bx[2] + bwb + ((bx[3] - bx[2] - bwb) * 0.5).floor()).floor(); + arrow(&self.cv, bx[0] + w[0], bx[1], my); + self.cv.fill(bx[1] + w[1], my, fork - bx[1] - w[1] + 1.0, 1.0); + self.cv.fill(fork, ym[0], 1.0, ym[NB - 1] - ym[0] + 1.0); + for i in 0..NB { + arrow(&self.cv, fork, bx[2], ym[i]); + self.cv.fill(bx[2] + bwb, ym[i], join - bx[2] - bwb + 1.0, 1.0); + } + self.cv.fill(join, ym[0], 1.0, ym[NB - 1] - ym[0] + 1.0); + arrow(&self.cv, join, bx[3], my); + for i in 3..6 { + arrow(&self.cv, bx[i] + w[i], bx[i + 1], my); + } + along(&self.cv, &[(bx[0] + w[0], my), (bx[1] - 4.0, my)], inl); + along(&self.cv, &[(bx[1] + w[1], my), (fork, my)], inl); + for i in 0..NB { + let on = self.sget(band_base(i) + ON) > 0.5; + let into = [(fork, my), (fork, ym[i]), (bx[2] - 4.0, ym[i])]; + along(&self.cv, &into, if on { b_in[i] } else { 0.0 }); + let out = [(bx[2] + bwb, ym[i]), (join, ym[i]), (join, my)]; + along(&self.cv, &out, b_out[i]); + } + along(&self.cv, &[(join, my), (bx[3] - 4.0, my)], lo); + for i in 3..6 { + along(&self.cv, &[(bx[i] + w[i], my), (bx[i + 1] - 4.0, my)], lo); + } + // ---- main-line blocks + let names = ["IN", "X-OVER", "", "SUM", "EQ", "LIM", "OUT"]; + for i in [0usize, 1, 3, 4, 5, 6] { + let (x, bwi) = (bx[i], w[i]); + let dim = (i == 4 && (eq_byp || !eq_any)) || (i == 5 && !lim_on); + self.set_dk(if dim { prev * 0.5 } else { prev }); + let lit = (i == 4 && eq_any && !eq_byp) || (i == 5 && lim_on && self.lim_disp > 0.1); + // the EQ and LIM blocks are switches: click one to bypass it or bring it back + let hov = (i == 4 || i == 5) && self.hit(x, cy, bwi, bh); + if hov && self.kit.press && self.kit.act == 0 { + self.kit.press = false; + if i == 4 { + self.click_set(EQ_BYPASS, if eq_byp { 0.0 } else { 1.0 }); + } else { + self.click_set(LIM_ON, if lim_on { 0.0 } else { 1.0 }); + } + } + self.setc(hov); + if lit { + self.cv.fill(x, cy, bwi, bh); + self.cv.setbg(); + } else { + self.cv.setbg(); + self.cv.fill(x + 1.0, cy + 1.0, bwi - 2.0, bh - 2.0); + self.setc(hov); + self.cv.boxr(x, cy, bwi, bh); + } + self.cv.textc(x, cy + 7.0, bwi, names[i]); + self.setc(false); + } + // ---- the bands + for b in 0..NB { + let on = self.sget(band_base(b) + ON) > 0.5; + // lit while the band works: reducing gain (downward) or lifting it (upward) + let lit = on && (self.gr_disp[b] > 0.1 || self.gl_disp[b] > 0.1); + self.set_dk(if on { prev } else { prev * 0.5 }); + // each band block is a switch: click to turn the band off or on + let hov = self.hit(bx[2], ys[b], bwb, bhb); + if hov && self.kit.press && self.kit.act == 0 { + self.kit.press = false; + self.click_set(band_base(b) + ON, if on { 0.0 } else { 1.0 }); + } + self.setc(hov); + if lit { + self.cv.fill(bx[2], ys[b], bwb, bhb); + self.cv.setbg(); + } else { + self.cv.setbg(); + self.cv.fill(bx[2] + 1.0, ys[b] + 1.0, bwb - 2.0, bhb - 2.0); + self.setc(hov); + self.cv.boxr(bx[2], ys[b], bwb, bhb); + } + // the compressor in the label follows the band's mode: down, up, or both + let comp = ["COMP", "UP", "UP/DWN"][(self.sget(band_base(b) + UP).round() as usize).min(2)]; + self.cv.textc(bx[2], ys[b] + 5.0, bwb, &format!("{} SAT>{}", BAND_NAMES[b], comp)); + self.setc(false); + } + self.set_dk(prev); + // sidechain key: SIDECHAIN box above, dropping into the top band's compressor + if sc_on { + let (kw, ky) = (78.0f32, r.y + 3.0); + let kx = (bx[2] + (bwb - kw) * 0.5).floor(); + let mx = (kx + kw * 0.5).floor(); + // the key box is a switch too: click to turn the sidechain off + let hov = self.hit(kx, ky, kw, 16.0); + if hov && self.kit.press && self.kit.act == 0 { + self.kit.press = false; + self.click_set(SC_ON, 0.0); + } + self.setc(hov); + self.cv.boxr(kx, ky, kw, 16.0); + self.cv.textc(kx, ky + 4.0, kw, "SIDECHAIN"); + self.setc(false); + self.cv.fill(mx, ky + 16.0, 1.0, ys[0] - ky - 16.0 - 3.0); + self.cv.tri((mx - 3.0, ys[0] - 4.0), (mx + 4.0, ys[0] - 4.0), (mx + 0.5, ys[0])); + self.cv.text(kx + kw + 8.0, ky + 4.0, "KEY > COMP"); + } + self.cv.text(r.x + 6.0, r.y + r.h - 15.0, "EACH BAND: SAT > COMP (DOWN, UP OR BOTH). CLICK A BAND, EQ OR LIM TO SWITCH IT"); + } + + // ------------------------------------------------------------------ popup menu + /// (x, y, w, h, visible rows) of the open menu, clamped to the canvas. + fn menu_geom(&mut self) -> Option<(f32, f32, f32, f32, usize)> { + self.cv.set_font(1); + let m = self.menu.as_ref()?; + let tw = m.items.iter().map(|i| self.cv.text_w(&i.label)).fold(0.0, f32::max); + let rows = m.items.len().min(MENU_ROWS); + let (mw, mh) = (tw + 26.0, MENU_ROW_H * rows as f32 + 2.0); + Some((m.x.min(super::W - mw).max(0.0), m.y.min(super::H - mh).max(0.0), mw, mh, rows)) + } + + fn menu_frame(&mut self) { + let Some((x, y, mw, mh, rows)) = self.menu_geom() else { return }; + let inside = self.hit(x, y, mw, mh); + let row = ((self.kit.my - y - 1.0) / MENU_ROW_H).floor() as i32; + let mut chosen: Option<(MenuKind, i32)> = None; + let mut close = false; + let (wheel, press, rpress) = (self.kit.wheel, self.kit.press, self.kit.rpress); + if let Some(m) = self.menu.as_mut() { + if wheel != 0 && m.items.len() > rows { + let max = m.items.len() - rows; + m.scroll = (m.scroll as i32 - wheel).clamp(0, max as i32) as usize; + } + if press { + if inside && row >= 0 && (row as usize) < rows { + if let Some(it) = m.items.get(m.scroll + row as usize) { + if it.kind == 0 { + chosen = Some((m.kind, it.id)); + } else { + // header / separator: swallow the click, keep the menu open + self.kit.press = false; + self.kit.rpress = false; + self.kit.wheel = 0; + return; + } + } + } + close = true; + } + if rpress { + close = true; + } + } + if close || chosen.is_some() { + self.menu = None; + if let Some((kind, id)) = chosen { + match kind { + MenuKind::Shape(band) => self.click_set(band_base(band) + SHAPE, id as f32), + MenuKind::Size => self.request_scale(SIZES[(id as usize).min(SIZES.len() - 1)]), + MenuKind::Preset => self.preset_action(id), + MenuKind::Slope(k) => self.click_set(XOV_SLOPE[k], id as f32), + MenuKind::Palette if id >= 1000 => self.set_light(!self.light), + MenuKind::Palette => self.set_pal(id as usize), + } + } + } + // a menu swallows every click and wheel turn while it is open + self.kit.press = false; + self.kit.rpress = false; + self.kit.wheel = 0; + } + + fn menu_draw(&mut self) { + let Some((x, y, mw, mh, rows)) = self.menu_geom() else { return }; + let Some(m) = self.menu.as_ref() else { return }; + let items: Vec = m.items.iter().skip(m.scroll).take(rows).cloned().collect(); + let checked = m.checked; + let (more_up, more_down) = (m.scroll > 0, m.scroll + rows < m.items.len()); + self.cv.dk = 1.0; + self.cv.setbg(); + self.cv.fill(x, y, mw, mh); + self.setc(false); + self.cv.boxr(x, y, mw, mh); + self.cv.set_font(1); + let hov = ((self.kit.my - y - 1.0) / MENU_ROW_H).floor() as i32; + let inside = self.hit(x, y, mw, mh); + for (i, it) in items.iter().enumerate() { + let iy = y + 1.0 + i as f32 * MENU_ROW_H; + match it.kind { + 2 => { + self.setc(false); + self.cv.fill(x + 4.0, iy + 6.0, mw - 8.0, 1.0); + } + 1 => { + self.cv.dk = 0.5; + self.setc(false); + self.cv.text(x + 6.0, iy + 1.0, &it.label); + self.cv.dk = 1.0; + } + _ => { + self.setc(false); + if inside && hov == i as i32 { + self.cv.fill(x + 1.0, iy, mw - 2.0, MENU_ROW_H); + self.cv.setbg(); + } + if it.id == checked { + self.cv.fill(x + 5.0, iy + 5.0, 4.0, 4.0); + } + self.cv.text(x + 14.0, iy + 1.0, &it.label); + } + } + } + self.setc(false); + if more_up { + self.cv.tri((x + mw - 10.0, y + 7.0), (x + mw - 4.0, y + 7.0), (x + mw - 7.0, y + 3.0)); + } + if more_down { + self.cv.tri((x + mw - 10.0, y + mh - 7.0), (x + mw - 4.0, y + mh - 7.0), (x + mw - 7.0, y + mh - 3.0)); + } + } + + /// 12x12 pencil icon; lit while the draw view is open, bright on hover. + fn pencil_glyph(&mut self, x: f32, y: f32, on: bool, hover: bool) { + let prev = self.kit.dk; // keep the bypass dimming of the surrounding module + self.set_dk(prev * if on || hover { 1.0 } else { 0.6 }); + self.setc(on); + let l = |s: &Self, a: f32, b: f32, c: f32, d: f32| s.cv.line(x + a, y + b, x + c, y + d); + l(self, 8.0, 1.0, 10.0, 3.0); // eraser cap + l(self, 8.0, 1.0, 1.0, 8.0); // body + l(self, 10.0, 3.0, 3.0, 10.0); + l(self, 1.0, 8.0, 0.0, 11.0); // tip + l(self, 3.0, 10.0, 0.0, 11.0); + self.set_dk(prev); + self.setc(false); + } + + /// Transfer curve of the selected band's saturator at its current drive and bias. Drag in the plot = SAT GAIN (marker on + /// the left edge), pencil (top right) = draw the band's custom curve, live input peak marked on the curve. + fn draw_sat_plot(&mut self, x: f32, y: f32, w: f32, h: f32) { + let b = self.sel(); + let o = band_base(b); + let gain_n = o + SAT_GAIN; + let sh = self.env.shared; + let bp = self.env.dsp.bands[b]; + let sat_on = bp.drive > 0.0 || bp.bias != 0.0; + let pre = (bp.drive * 0.01 * 36.0 * 0.11512925).exp(); + let bias = bp.bias * 0.01; + self.lut.sync(bp.shape, &bp.curve); + // static curve as heard: the shaper minus the part of its even half that ASYM removes + let ak = bp.asym[(bp.shape.max(0) as usize).min(bp.asym.len() - 1)] * 0.01; + let eff = move |l: &ShaperLut, v: f64| { + let r = 0.5 * (1.0 - ak); + l.eval(v) * (1.0 - r) - r * l.eval(-v) + }; + // pencil: toggles the draw view; entering selects the Custom shaper so edits are audible + let pen = self.hit(x + w - 14.0, y + 2.0, 12.0, 12.0); + if pen && self.kit.press && self.kit.act == 0 { + self.curve_edit = !self.curve_edit; + self.edit_seen = false; + if self.curve_edit { + self.click_set(o + SHAPE, CUSTOM as f32); + // symmetry is the default tool, unless the stored curve is lopsided: opening must not alter it + self.sym_mode = self.env.params.curve_snapshot(b).is_odd(); + } + self.kit.press = false; + } + if self.curve_edit { + if (self.sget(o + SHAPE) + 0.5).floor() as i32 == CUSTOM { + self.edit_seen = true; + } else if self.edit_seen { + self.curve_edit = false; // another shaper was chosen + } + } + let hv = self.hit(x, y, w, h) && !self.curve_edit; + // the SAT readout in the bottom right corner: click = measure 3 s, then write this band's SAT GAIN (click again cancels) + let tb = self.hit(x + w - 84.0, y + h - 14.0, 82.0, 12.0); + if hv && self.kit.press && self.kit.act == 0 { + if tb { + sh.sat_req[b].store(true, Ordering::Relaxed); + self.kit.press = false; + } else { + self.begin_drag(gain_n); + } + } + if hv && self.kit.wheel != 0 { + self.wheel_adj(gain_n); + } + let gain_act = self.kit.act == gain_n as i32; + self.setc(gain_act); + self.cv.boxr(x, y, w, h); + for i in 0..(w / 2.0).floor() as i32 { + self.cv.fill(x + i as f32 * 2.0, y + (h / 2.0).floor(), 1.0, 1.0); + } + for i in 0..(h / 2.0).floor() as i32 { + self.cv.fill(x + (w / 2.0).floor(), y + i as f32 * 2.0, 1.0, 1.0); + } + if self.curve_edit { + self.close_glyph(x + w - 14.0, y + 2.0, pen); + } else { + self.pencil_glyph(x + w - 14.0, y + 2.0, false, pen); + } + if self.curve_edit { + self.draw_curve_edit(x, y, w, h); + return; + } + let pk = sh.sat_vz[b].load(Ordering::Relaxed).min(1.0); + let n = 64; + let (mut lx, mut ly) = (0.0, 0.0); + for i in 0..=n { + let vx = -1.0 + 2.0 * i as f64 / n as f64; + let mut vy = if sat_on { eff(&self.lut, vx * pre + bias) } else { vx }; + vy = vy.clamp(-1.0, 1.0); + let px = x + ((vx + 1.0) * 0.5) as f32 * (w - 1.0); + let py = y + (1.0 - ((vy + 1.0) * 0.5) as f32) * (h - 1.0); + self.setc(sat_on && pk > 0.002 && vx.abs() <= pk as f64); + if i > 0 { + self.cv.line(lx, ly, px, py); + } + lx = px; + ly = py; + } + if sat_on && pk > 0.002 { + self.setc(true); + for sgn in [1.0f64, -1.0] { + let vy = eff(&self.lut, sgn * pk as f64 * pre + bias).clamp(-1.0, 1.0) as f32; + let vx = sgn as f32 * pk; + self.cv.fill(x + (vx + 1.0) * 0.5 * (w - 1.0) - 1.0, y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0) - 1.0, 3.0, 3.0); + } + self.setc(false); + } + // SAT GAIN level marker on the left edge (-24..+12 dB) + let tot = self.sget(gain_n); + let ty = y + (1.0 - (tot.clamp(-24.0, 12.0) + 24.0) / 36.0) * (h - 3.0); + self.setc(gain_act); + self.cv.fill(x + 1.0, ty, 7.0, 2.0); + if gain_act { + for i in 0..(w / 3.0).floor() as i32 { + self.cv.fill(x + i as f32 * 3.0, ty, 1.0, 1.0); + } + } + self.setc(false); + self.cv.set_font(1); + self.cv.text(x + 3.0, y + 3.0, &format!("OUT {:+.1}dB", tot)); + let s = if sh.sat_meas[b].load(Ordering::Relaxed) { + self.setc(appearance::blink(self.kit.now)); + format!("MEAS {:.1}s", sh.sat_mt[b].load(Ordering::Relaxed)) + } else { + format!("SAT {:+.1}dB", self.rd_sat[b]) + }; + self.cv.textr(x, y + h - 14.0, w - 3.0, &s); + self.setc(false); + } + + /// Draw view of the selected band's custom curve (unity input, independent of drive/bias). + /// Left click empty space = add a point (and drag it), drag = move, double click = remove. + /// The two end points are fixed in x and cannot be removed. + fn draw_curve_edit(&mut self, x: f32, y: f32, w: f32, h: f32) { + let b = self.sel(); + let mut c = self.env.params.curve_snapshot(b); + let before = c; + // tool icons left of the close cross: free draw (pencil), symmetry + let (pen_x, sym_x) = (x + w - 28.0, x + w - 42.0); + let (hp, hs) = (self.hit(pen_x, y + 2.0, 12.0, 12.0), self.hit(sym_x, y + 2.0, 12.0, 12.0)); + if self.kit.press && self.kit.act == 0 { + if hp && self.sym_mode { + self.sym_mode = false; + self.kit.press = false; + } else if hs && !self.sym_mode { + // free -> symmetric keeps the odd part of the curve (what a symmetric curve can hold) + c = Curve::from_odd_half(&c.odd_half()); + self.sym_mode = true; + self.kit.press = false; + } + } + let sym = self.sym_mode; + // domain [-1,1]^2 is inset so end points and the icons never collide (symmetric margins keep the centre cross true) + let (ex, ey, ew, eh) = (x + 9.0, y + 14.0, w - 18.0, h - 28.0); + let (px, py) = (|vx: f32| ex + (vx + 1.0) * 0.5 * (ew - 1.0), |vy: f32| ey + (1.0 - (vy + 1.0) * 0.5) * (eh - 1.0)); + let to_v = |mx: f32, my: f32| (((mx - ex) / (ew - 1.0)) * 2.0 - 1.0, 1.0 - ((my - ey) / (eh - 1.0)) * 2.0); + // working list: the whole curve, or in symmetry mode its right half (x > 0, ending at x = 1); the left is derived + let mut hv: Vec<(f32, f32)> = if sym { c.pts().iter().cloned().filter(|p| p.0 > 0.0).collect() } else { c.pts().to_vec() }; + if sym && hv.is_empty() { + hv.push((1.0, 1.0)); + } + let cap = if sym { MAX_PTS / 2 } else { MAX_PTS }; + let interior = |i: usize, n: usize| if sym { i + 1 < n } else { i > 0 && i + 1 < n }; + let xlo = |hv: &Vec<(f32, f32)>, i: usize| if i == 0 { if sym { 0.0 } else { -1.0 } } else { hv[i - 1].0 }; + // a point is picked on its own spot, or in symmetry mode on its mirror image + let pick = |s: &Self, hv: &Vec<(f32, f32)>| -> Option { + let mut best: Option<(usize, f32)> = None; + for (i, &(vx, vy)) in hv.iter().enumerate() { + let mut d = ((s.kit.mx - px(vx)).powi(2) + (s.kit.my - py(vy)).powi(2)).sqrt(); + if sym { + d = d.min(((s.kit.mx - px(-vx)).powi(2) + (s.kit.my - py(-vy)).powi(2)).sqrt()); + } + if d <= 6.0 && best.map_or(true, |b| d < b.1) { + best = Some((i, d)); + } + } + best.map(|b| b.0) + }; + let in_box = self.hit(x, y, w, h) && !self.hit(sym_x, y + 2.0, 56.0, 12.0); + if in_box && self.kit.press && self.kit.act == 0 { + let n = hv.len(); + if let Some(i) = pick(self, &hv) { + if self.dbl(200 + i as i32) && interior(i, n) { + hv.remove(i); + self.kit.last_clk_n = 0; + } else { + self.kit.act = ACT_CURVE; + self.cpt = i; + } + } else if n < cap { + let (mut vx, mut vy) = to_v(self.kit.mx, self.kit.my); + if sym && vx < 0.0 { + vx = -vx; + vy = -vy; + } + let at = if sym { hv.iter().position(|p| p.0 > vx) } else { (1..n).find(|&k| hv[k].0 > vx) }.unwrap_or(n - 1); + let room = vx - xlo(&hv, at) >= MIN_GAP && hv[at].0 - vx >= MIN_GAP; + if room { + hv.insert(at, (vx, vy.clamp(-1.0, 1.0))); + self.kit.act = ACT_CURVE; + self.cpt = at; + self.kit.last_clk_n = 0; // a creating click never counts towards a double click + } + } + self.kit.press = false; + } + if self.kit.act == ACT_CURVE && self.kit.down && self.cpt < hv.len() { + let (mut vx, mut vy) = to_v(self.kit.mx, self.kit.my); + let i = self.cpt; + if sym { + // dragging the ghost half moves the real point the other way round + if vx < 0.0 { + vx = -vx; + vy = -vy; + } + } + let n = hv.len(); + if interior(i, n) { + hv[i].0 = vx.clamp(xlo(&hv, i) + MIN_GAP, hv[i + 1].0 - MIN_GAP); + } + hv[i].1 = vy.clamp(-1.0, 1.0); + } + c = if sym { Curve::from_odd_half(&hv) } else { Curve::from_points(&hv) }; + if c != before { + let cell = self.curve_cell(b); + *cell.lock() = c.pts().to_vec(); + } + // identity reference (dotted), the curve, then the points + let prev = self.kit.dk; + self.set_dk(prev * 0.5); + self.setc(false); + for i in 0..(ew / 3.0).floor() as i32 { + let vx = -1.0 + 2.0 * i as f32 / (ew / 3.0).floor(); + self.cv.fill(px(vx), py(vx), 1.0, 1.0); // identity + self.cv.fill(px(vx), py(1.0), 1.0, 1.0); // domain frame (+-1) + self.cv.fill(px(vx), py(-1.0), 1.0, 1.0); + self.cv.fill(px(1.0), py(vx), 1.0, 1.0); + self.cv.fill(px(-1.0), py(vx), 1.0, 1.0); + } + self.set_dk(prev); + let n = 96; + let (mut lx, mut ly) = (px(-1.0), py(c.eval(-1.0) as f32)); + for i in 1..=n { + let vx = -1.0 + 2.0 * i as f32 / n as f32; + let (qx, qy) = (px(vx), py(c.eval(vx as f64) as f32)); + self.cv.line(lx, ly, qx, qy); + lx = qx; + ly = qy; + } + let hot = if self.kit.act == ACT_CURVE { Some(self.cpt) } else { pick(self, &hv) }; + let nh = hv.len(); + for (i, &(vx, vy)) in hv.iter().enumerate() { + let (qx, qy) = (px(vx).round(), py(vy).round()); + self.setc(hot == Some(i)); + let end = if sym { i + 1 == nh } else { i == 0 || i + 1 == nh }; + if end { + self.cv.boxr(qx - 2.0, qy - 2.0, 5.0, 5.0); // y-only end points + } else { + self.cv.fill(qx - 2.0, qy - 2.0, 5.0, 5.0); + } + if sym { + // the mirrored partner: a dim outline you can grab just the same + let (gx, gy) = (px(-vx).round(), py(-vy).round()); + let pd = self.kit.dk; + self.set_dk(pd * 0.6); + self.cv.boxr(gx - 2.0, gy - 2.0, 5.0, 5.0); + self.set_dk(pd); + } + } + self.setc(false); + // tools: pencil (free draw), symmetry + self.pencil_glyph(pen_x, y + 2.0, !sym, hp); + self.sym_glyph(sym_x, y + 2.0, sym, hs); + self.cv.set_font(1); + self.cv.text(x + 3.0, y + 3.0, "DRAW"); + self.cv.textr(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, MAX_PTS)); + } + + /// Sidechain control row under the spectrum: SC gain | HP | LP | SOLO (solo = hear the key as the detectors see it, + /// i.e. after gain / HP / LP). Global: the key is conditioned once, then split into the four bands. + fn sc_row(&mut self, x: f32, y: f32) { + let h = SC_ROW_H; + let cells = [(SC_GAIN, "SC", 160.0f32), (SC_HP, "HP", 135.0), (SC_LP, "LP", 135.0)]; + let mut cx = x; + for (n, lbl, w) in cells { + let hv = self.hit(cx, y, w, h); + if hv && self.kit.press && self.kit.act == 0 { + self.begin_drag(n); + } + if hv && self.kit.wheel != 0 { + self.wheel_adj(n); + } + let act = self.kit.act == n as i32; + self.setc(act); + self.cv.boxr(cx, y, w, h); + self.cv.set_font(1); + self.cv.text(cx + 4.0, y + 5.0, lbl); + let v = self.sget(n); + let t = self.fmt(n, v); + self.cv.textr(cx, y + 5.0, w - 4.0, &t); + let tn = self.n2t(n, v); + self.cv.fill(cx + 2.0, y + h - 3.0, ((tn * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(false); + cx += w - 1.0; + } + let solo = self.env.shared.sc_solo.load(Ordering::Relaxed); + if self.btn(cx, y, x + VW - cx, h, "SOLO", if solo { 2 } else { 0 }) { + self.env.shared.sc_solo.store(!solo, Ordering::Relaxed); + } + } + + /// One crossover: its frequency as a slider cell with a small slope button at the right end (click = list of 12 / 24 / 48 / 96 dB per octave) + fn xover_row(&mut self, k: usize, x: f32, y: f32) { + let bw = 34.0; + self.cell1(XOV[k], x, y, RW - bw + 1.0, 16.0, &format!("XOV{}", k + 1)); + let cur = (self.sget(XOV_SLOPE[k]) + 0.5).floor().clamp(0.0, 3.0) as i32; + let open = matches!(&self.menu, Some(Menu { kind: MenuKind::Slope(m), .. }) if *m == k); + if self.btn(x + RW - bw, y, bw, 16.0, &format!("{}dB", [12, 24, 48, 96][cur as usize]), open as u8) { + let items = [12, 24, 48, 96].iter().enumerate().map(|(i, v)| MItem { label: format!("{} dB/oct", v), kind: 0, id: i as i32 }).collect(); + self.menu = Some(Menu { kind: MenuKind::Slope(k), x: x + RW - bw - 36.0, y: y + 16.0, items, checked: cur, scroll: 0 }); + } + } + + /// back to the factory state of EQ band `b`: on / type / freq / Q / gain + fn reset_eq_band(&mut self, b: usize) { + for k in 0..5 { + let n = eq_base(b) + k; + let d = self.kit.meta[n].def; + self.click_set(n, d); + } + } + + /// short read-out row: label left, value right, centre-tap level bar on the bottom edge + fn diff_row(&mut self, x: f32, y: f32, w: f32, h: f32, lbl: &str, db: f32) { + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.set_font(1); + let ty = y + ((h - 8.0) * 0.5).floor(); + self.cv.text(x + 3.0, ty, lbl); + self.cv.textr(x, ty, w - 3.0, &format!("{:+.1}dB", db)); + let cx = x + (w * 0.5).floor(); + let d = db.clamp(-12.0, 12.0) / 12.0; + let bw = (d.abs() * (w * 0.5 - 3.0)).floor(); + if d >= 0.0 { + self.cv.fill(cx, y + h - 3.0, bw, 2.0); + } else { + self.cv.fill(cx - bw, y + h - 3.0, bw, 2.0); + } + self.cv.fill(cx, y + h - 5.0, 1.0, 4.0); + } + + fn band_row(&mut self, y: f32) { + let sel = self.sel(); + let f = [self.env.dsp.x1 as f32, self.env.dsp.x2 as f32, self.env.dsp.x3 as f32]; + let f = [f[0], f[1].max(f[0] * 1.05), f[2].max(f[1].max(f[0] * 1.05) * 1.05)]; + let ranges = [(0.0, f[0]), (f[0], f[1]), (f[1], f[2]), (f[2], 20000.0)]; + let short = |v: f32| { + if v < 1.0 { + "0".to_string() + } else if v < 1000.0 { + format!("{:.0}", v) + } else if v < 9950.0 { + format!("{:.1}k", v * 0.001) + } else { + format!("{:.0}k", v * 0.001) + } + }; + let tw = (VW - 96.0) / NB as f32; + for b in 0..NB { + let x = VX + tw * b as f32; + let base = band_base(b); + let on = self.sget(base + ON) > 0.5; + self.sq_tog(base + ON, x + 7.0, y + 4.0, 8.0); + self.set_dk(if self.sget(8) > 0.5 { 0.5 } else { 1.0 }); + if self.btn(x, y, tw, 16.0, "", (b == sel) as u8) { + self.select_band(b); + } + // two-letter label left (after the on / off square), frequency range right, no unit + if b == sel { + self.cv.setbg(); + } else { + self.setc(false); + } + self.cv.set_font(1); + self.cv.text(x + 20.0, y + 4.0, BAND_LETTERS[b]); + self.cv.textr(x, y + 4.0, tw - 5.0, &format!("{}-{}", short(ranges[b].0), short(ranges[b].1))); + self.setc(false); + self.sqind(x + 7.0, y + 4.0, 8.0, on, b == sel, !on); + } + let base = band_base(sel); + let (d, s) = (self.sget(base + DELTA) > 0.5, self.sget(base + SOLO) > 0.5); + if self.btn(VX + VW - 96.0, y, 48.0, 16.0, "DELTA", if d { 2 } else { 0 }) { + self.click_set(base + DELTA, if d { 0.0 } else { 1.0 }); + } + if self.btn(VX + VW - 48.0, y, 48.0, 16.0, "SOLO", if s { 2 } else { 0 }) { + self.click_set(base + SOLO, if s { 0.0 } else { 1.0 }); + } + + } + + fn band_cells(&mut self, y0: f32) { + let b = self.sel(); + let o = band_base(b); + let rows = [y0, y0 + CELL_P, y0 + 2.0 * CELL_P, y0 + 3.0 * CELL_P]; + let ph = 3.0 * CELL_P + CELL_H; + // saturator module: the transfer plot is square (rows 2-4), selector and drive row above it + let sat_w = ph - CELL_P; + let sat_x = VX + sat_w + 6.0; + // compressor section sits flush right (GR meter + three columns); what is left over is the gap to the saturator + let col0 = VX + VW - (3.0 * CELL_W + 12.0); + let meter_x = col0 - 6.0 - 30.0; + self.shape_selector(o + SHAPE, VX, y0, sat_w, 19.0); + let drive_w = (sat_w * 0.5).floor(); + self.cell1(o + DRIVE, VX, y0 + 19.0, drive_w, 19.0, "DRIVE"); + self.cell1(o + BIAS, VX + drive_w - 1.0, y0 + 19.0, sat_w - drive_w + 1.0, 19.0, "BIAS"); + self.draw_sat_plot(VX, y0 + CELL_P, sat_w, sat_w); + // The theme editor's 4 x 3 grid starts right of the saturator's left half, so while editing the saturator's right + // column (ASYM / TONE / HP / LP / SAT MIX / SAT GAIN), its band VU and the GR meter are hidden to give it the room. + if !self.app.editing() { + // two stacked slider groups (the halves share one border line): ASYM over TONE, HP over LP + self.asym_cell(b, sat_x, rows[0], CELL_W, 19.0); + self.cell1(o + TONE, sat_x, rows[0] + 18.0, CELL_W, 20.0, "TONE"); + self.cell1(o + HP, sat_x, rows[1], CELL_W, 19.0, "HP"); + self.cell1(o + LP, sat_x, rows[1] + 18.0, CELL_W, 20.0, "LP"); + self.cell(o + SAT_MIX, sat_x, rows[2], CELL_W, CELL_H, "SAT MIX"); + self.cell_o(o + SAT_GAIN, sat_x, rows[3], CELL_W, CELL_H, "SAT GAIN"); + // band level after the saturator, in the gap between the saturator and compressor sections + self.draw_vu(sat_x + CELL_W + 8.0, y0, 24.0, ph); + // gain reduction meter + self.draw_gr_meter(meter_x, y0, 30.0, ph); + } + if self.app.editing() { + // theme editor: its cells take the compressor section (4 x 3 grid) + self.theme_cells(CellGrid { x0: VX + VW - (3.0 * CELL_W + 12.0) - (CELL_W + 6.0), y0, cw: CELL_W, ch: CELL_H, px: CELL_W + 6.0, py: CELL_P }); + return; + } + // compressor: 3 columns x 4 rows + let cells = [ + [(THRESH, "THRESH"), (RATIO, "RATIO"), (ATTACK, "ATTACK"), (RELEASE, "RELEASE")], + [(KNEE, "KNEE"), (KNEE_SHAPE, "K.SHAPE"), (GR_DIST, "GR DIST"), (SPEED, "SPEED")], + [(DETECTOR, "PEAK>RMS"), (FF_FB, "FF>FB"), (COMP_MIX, "COMP MIX"), (COMP_GAIN, "CMP GAIN")], + ]; + for (c, col) in cells.iter().enumerate() { + let cx = col0 + (CELL_W + 6.0) * c as f32; + if c == 1 { + // the COMP DOWN / UP switch over RANGE, KNEE over K.SHAPE (two stacked groups, the halves share a border line), + // then GR DIST and SPEED as single cells + self.up_group(b, cx, rows[0]); + self.cell1(o + KNEE, cx, rows[1], CELL_W, 19.0, "KNEE"); + self.cell1(o + KNEE_SHAPE, cx, rows[1] + 18.0, CELL_W, 20.0, "K.SHAPE"); + self.cell(o + GR_DIST, cx, rows[2], CELL_W, CELL_H, "GR DIST"); + self.cell(o + SPEED, cx, rows[3], CELL_W, CELL_H, "SPEED"); + continue; + } + for (r, (off, lbl)) in col.iter().enumerate() { + if *off == COMP_GAIN { + self.cell_o(o + off, cx, rows[r], CELL_W, CELL_H, lbl); + } else if *off == FF_FB && self.sget(SC_ON) > 0.5 { + // KEY MIX stands in for FF>FB while the sidechain is on (one global value for all bands) + self.cell(SC_MIX, cx, rows[r], CELL_W, CELL_H, "KEY MIX"); + } else { + self.cell(o + off, cx, rows[r], CELL_W, CELL_H, lbl); + } + } + } + } + + /// Compressor mode switch (DWNWARD / UPWARD / UP/DWN, click or wheel steps through them) with the RANGE slider (the most + /// the upward part lifts) stacked under it; the range reads dim while the band is in the plain downward mode. + fn up_group(&mut self, b: usize, x: f32, y: f32) { + let n = band_base(b) + UP; + let mode = (self.sget(n) + 0.5).floor().clamp(0.0, 2.0) as i32; + let label = ["DWNWARD", "UPWARD", "UP/DWN"][mode as usize]; + if self.btn(x, y, CELL_W, 19.0, label, (mode > 0) as u8) { + self.click_set(n, ((mode + 1) % 3) as f32); + } else if self.hit(x, y, CELL_W, 19.0) && self.kit.wheel != 0 { + let nx = (mode + if self.kit.wheel > 0 { 1 } else { -1 }).clamp(0, 2); + if nx != mode { + self.click_set(n, nx as f32); + } + } + let keep = self.kit.dk; + if mode == 0 { + self.set_dk(keep * 0.5); + } + self.cell1(range_slot(b), x, y + 18.0, CELL_W, 20.0, "RANGE"); + self.set_dk(keep); + self.setc(false); + } + + fn out_column(&mut self, y0: f32) { + let sh = self.env.shared; + let gmatch = self.sget(7) > 0.5; + let meas = sh.out_meas.load(Ordering::Relaxed); + self.setc(false); + self.cv.set_font(1); + let (lbl, val) = if gmatch { + if meas { + ("MEAS", format!("{:.1}/3.0s", sh.out_mt.load(Ordering::Relaxed))) + } else { + ("LOCK", format!("{:+05.1}dB", self.env.params.match_trim.load(Ordering::Relaxed))) + } + } else { + ("TRIM", "-----dB".to_string()) + }; + self.cv.text(RX, y0 + 4.0, lbl); + self.cv.textr(RX, y0 + 4.0, RW, &val); + let blink = ((self.kit.now * 4.0).floor() as i64) & 1 == 1; + let lit = if gmatch { if meas && blink { 1 } else { 2 } } else { 0 }; + if self.btn(RX, y0 + 18.0, RW, 16.0, "GAIN MATCH", lit) { + if gmatch { + self.click_set(7, 0.0); + } else { + self.click_set(7, 1.0); + sh.match_req.store(true, Ordering::Relaxed); + } + } + self.diff_box(RX, y0 + CELL_P, RW, CELL_H); + self.cell(5, RX, y0 + 2.0 * CELL_P, RW, CELL_H, "MIX"); + self.cell_o(6, RX, y0 + 3.0 * CELL_P, RW, CELL_H, "OUT GAIN"); + } + + // ------------------------------------------------------------------ EQ page + /// filter glyphs. kind: 0 HPF, 1 LPF, 2 low shelf, 3 high shelf, 4 bell, 5 all-pass, 6 band-pass, 7 notch + fn eq_glyph(&mut self, kind: u8, cx: f32, cy: f32) { + let gk = 0.75; + let (gx0, gy0) = (cx - 9.0 * gk, cy - 5.5 * gk); + let seg = |ax: f32, ay: f32, bx: f32, by: f32| { + self.cv.line(gx0 + ax * gk, gy0 + ay * gk, gx0 + bx * gk, gy0 + by * gk); + }; + match kind { + 0 => { + seg(0.85, 8.0, 5.23, 1.0); + seg(5.23, 1.0, 18.85, 1.0); + } + 1 => { + seg(0.0, 1.0, 13.6, 1.0); + seg(13.6, 1.0, 18.0, 8.0); + } + 2 => { + seg(0.0, 1.0, 6.88, 1.0); + seg(6.88, 1.0, 11.5, 9.0); + seg(11.5, 9.0, 18.0, 9.0); + } + 3 => { + seg(0.0, 9.0, 6.5, 9.0); + seg(6.5, 9.0, 11.1, 1.0); + seg(11.1, 1.0, 18.0, 1.0); + } + 5 => { + // flat magnitude, phase turn: a line with a dot + seg(0.0, 5.0, 18.0, 5.0); + seg(7.0, 2.0, 11.0, 2.0); + seg(7.0, 8.0, 11.0, 8.0); + seg(7.0, 2.0, 7.0, 8.0); + seg(11.0, 2.0, 11.0, 8.0); + } + 6 => { + seg(0.0, 10.0, 4.5, 10.0); + seg(4.5, 10.0, 7.5, 1.0); + seg(7.5, 1.0, 10.5, 1.0); + seg(10.5, 1.0, 13.5, 10.0); + seg(13.5, 10.0, 18.0, 10.0); + } + 7 => { + seg(0.0, 1.0, 5.69, 1.0); + seg(5.69, 1.0, 9.27, 9.0); + seg(9.27, 9.0, 12.84, 1.0); + seg(12.84, 1.0, 18.0, 1.0); + } + _ => { + seg(0.0, 10.45, 5.69, 10.45); + seg(5.69, 10.45, 9.27, 2.45); + seg(9.27, 2.45, 12.84, 10.45); + seg(12.84, 10.45, 18.0, 10.45); + } + } + } + + /// the 7 filters of the EQ (5 bands + tilt pair) as (coefficients, active) + fn eq_filters(&self) -> Vec<([f64; 5], bool)> { + let sr = self.env.shared.sample_rate.load(Ordering::Relaxed) as f64; + let eq = &self.env.dsp.eq; + let mut v = Vec::new(); + for b in 0..5 { + let bp = &eq.bands[b]; + let c = eq_coef(eq_kind(b, bp.ty), bp.freq.clamp(20.0, 20000.0), bp.gain.clamp(-18.0, 18.0), bp.q.clamp(0.1, 10.0), sr); + v.push((c, bp.on)); + } + let t = eq.tilt.clamp(-12.0, 12.0); + let pv = if eq.pivot < 19.5 { 600.0 } else { eq.pivot.min(20000.0) }; + v.push((eq_coef(2, pv, -t * 0.5, 0.4, sr), t != 0.0)); + v.push((eq_coef(3, pv, t * 0.5, 0.4, sr), t != 0.0)); + v + } + + /// EQ viewport: the spectrum behind, the summed response curve and the five draggable band nodes + fn draw_eq(&mut self, x: f32, y: f32, w: f32, h: f32) { + self.draw_spectrum(x, y, w, h); + let sr = self.env.shared.sample_rate.load(Ordering::Relaxed) as f64; + let filters = self.eq_filters(); + let (x0, pw) = (x + 1.0, w - 2.0); + let (cy, span) = (y + (h * 0.5).floor(), h * 0.5 - 8.0); + let gy = |db: f32| cy - (db / 18.0).clamp(-1.0, 1.0) * span; + // 0 dB line, dotted, in the background colour then UI colour so it reads over the spectrum + self.setc(false); + let mut xx = x0; + while xx < x0 + pw { + self.cv.fill(xx, cy, 2.0, 1.0); + xx += 4.0; + } + // pivot of the tilt: dashed vertical line (drag = pivot, drag empty space sideways = tilt) + let pvx = freq_to_x(self.env.dsp.eq.pivot as f32, x0, pw); + self.setc(self.kit.act == ACT_PIVOT); + let dash = if self.kit.act == ACT_PIVOT { 3.0 } else { 2.0 }; + for i in 0..((h - 2.0) / 3.0).floor() as i32 { + self.cv.fill(pvx.floor(), y + 1.0 + i as f32 * 3.0, 1.0, dash); + } + // response curve + let wk = |f: f32| 2.0 * std::f64::consts::PI * (f as f64).min(sr * 0.49) / sr; + self.setc(true); + let n = pw as i32; + let mut last: Option<(f32, f32)> = None; + for i in 0..=n { + let f = x_to_freq(x0 + i as f32 * pw / n as f32, x0, pw); + let mut db = 0.0f64; + for (c, on) in &filters { + if *on { + db += mag_db(c, wk(f)); + } + } + let p = (x0 + i as f32 * pw / n as f32, gy(db as f32)); + if let Some(l) = last { + self.cv.line(l.0, l.1, p.0, p.1); + self.cv.line(l.0, l.1 + 1.0, p.0, p.1 + 1.0); + } + last = Some(p); + } + // nodes + let eq = self.env.dsp.eq; + let mut best: Option = None; + let mut bd = 100.0f32; + let mut pos = [(0.0f32, 0.0f32); 5]; + for b in 0..5 { + let bp = &eq.bands[b]; + let has_gain = matches!(eq_kind(b, bp.ty), 2 | 3 | 4); + pos[b] = (freq_to_x(bp.freq as f32, x0, pw), if has_gain { gy(bp.gain as f32) } else { cy }); + let d2 = (self.kit.mx - pos[b].0).powi(2) + (self.kit.my - pos[b].1).powi(2); + if d2 < bd { + bd = d2; + best = Some(b); + } + } + let hv = self.hit(x, y, w, h); + if hv && self.kit.wheel != 0 { + if let Some(b) = best { + self.wheel_adj(eq_base(b) + 3); + } + } + if hv && self.kit.press && self.kit.act == 0 { + if let Some(b) = best { + self.eq_sel = b; + if self.dbl(140 + b as i32) { + self.reset_eq_band(b); + } else { + if self.sget(eq_base(b)) < 0.5 { + self.click_set(eq_base(b), 1.0); + } + self.kit.act = ACT_NODE + b as i32; + } + } else if (self.kit.mx - pvx).abs() <= 3.0 { + if self.dbl(145) { + let d = self.kit.meta[EQ_PIVOT].def; + self.click_set(EQ_PIVOT, d); + } else { + self.kit.act = ACT_PIVOT; + self.gdx = pvx - self.kit.mx; + } + } else if self.dbl(146) { + self.click_set(EQ_TILT, 0.0); + } else { + self.kit.act = ACT_TILT; + self.tacc = self.sget(EQ_TILT); + self.tlast = self.kit.mx; + } + self.kit.press = false; + } + if self.kit.act == ACT_PIVOT && self.kit.down { + let f = x_to_freq(self.kit.mx + self.gdx, x0, pw); + self.setv(EQ_PIVOT, f); + } + if self.kit.act == ACT_TILT && self.kit.down { + self.tacc += (self.kit.mx - self.tlast) * (24.0 / pw) * if self.kit.shift { 0.15 } else { 1.0 }; + self.tlast = self.kit.mx; + self.tacc = self.tacc.clamp(-12.0, 12.0); + let t = self.tacc; + self.setv(EQ_TILT, t); + } + if self.kit.act >= ACT_NODE && self.kit.act < ACT_NODE + 5 && self.kit.down { + let b = (self.kit.act - ACT_NODE) as usize; + let f = x_to_freq(self.kit.mx, x0, pw); + self.setv(eq_base(b) + 2, f); + if matches!(eq_kind(b, self.env.dsp.eq.bands[b].ty), 2 | 3 | 4) { + let g = ((cy - self.kit.my) / span * 18.0).clamp(-18.0, 18.0); + self.setv(eq_base(b) + 4, g); + } + } + for b in 0..5 { + let on = eq.bands[b].on; + let (px, py) = pos[b]; + let sel = b == self.eq_sel; + let bw = 12.0; + self.setc(false); + if on { + self.cv.fill(px.floor() - 6.0, py.floor() - 6.0, bw, bw); + self.cv.setbg(); + } else { + self.cv.setbg(); + self.cv.fill(px.floor() - 6.0, py.floor() - 6.0, bw, bw); + self.setc(false); + self.cv.boxr(px.floor() - 6.0, py.floor() - 6.0, bw, bw); + } + if sel { + self.setc(true); + self.cv.boxr(px.floor() - 8.0, py.floor() - 8.0, bw + 4.0, bw + 4.0); + if on { + self.setc(false); + self.cv.setbg(); + } else { + self.setc(false); + } + } else if !on { + self.setc(false); + } + self.cv.set_font(1); + self.cv.textc(px.floor() - 6.0, py.floor() - 4.0, bw, &format!("{}", b + 1)); + } + self.setc(false); + self.cv.set_font(1); + let t = self.env.dsp.eq.tilt; + let txt = if t.abs() < 0.05 { "TILT 0.0dB".to_string() } else { format!("TILT {:+.1}dB", t) }; + self.cv.text(x + 3.0, y + 2.0, &txt); + } + + /// the five EQ band toggles: type name while on, "EQ n" while off + fn eq_row(&mut self, y: f32) { + for b in 0..5 { + let x = VX + EQ_P * b as f32; + let on = self.sget(eq_base(b)) > 0.5; + let ty = (self.sget(eq_base(b) + 1) + 0.5).floor() as i32; + let label = if on { KIND_NAMES[eq_kind(b, ty) as usize].to_string() } else { format!("EQ {}", b + 1) }; + if self.btn(x, y, EQ_W, 16.0, &label, on as u8) { + self.eq_sel = b; + if self.dbl(150 + b as i32) { + self.reset_eq_band(b); + } else { + self.click_set(eq_base(b), if on { 0.0 } else { 1.0 }); + } + } + } + let d = self.rd_eq_diff; + self.diff_row(VX + EQ_P * 5.0, y, EQ_PW, 16.0, "I>O", d); + } + + fn eq_cells(&mut self, y0: f32) { + // the whole page dims while the EQ (or the plug-in) is bypassed + let page_dk = if self.sget(EQ_BYPASS) > 0.5 || self.sget(8) > 0.5 { 0.5 } else { 1.0 }; + for b in 0..5 { + let x = VX + EQ_P * b as f32; + let o = eq_base(b); + let on = self.sget(o) > 0.5; + self.set_dk(page_dk * if on { 1.0 } else { 0.5 }); + // type glyph grid (2 x 3) + let ty = (self.sget(o + 1) + 0.5).floor() as i32; + self.setc(false); + self.cv.boxr(x, y0, EQ_W, CELL_H); + for t in 0..6usize { + let gp = ((CELL_H - 2.0) * 0.5).floor(); + let (gx, gy) = (x + 1.0 + (t % 3) as f32 * EQ_W / 3.0, y0 + 1.0 + (t / 3) as f32 * gp); + let cur = t as i32 == ty; + if self.hit(gx, gy, EQ_W / 3.0 - 1.0, gp - 1.0) && self.kit.press && self.kit.act == 0 { + self.click_set(o + 1, t as f32); + self.kit.press = false; + } + self.setc(false); + if cur { + self.cv.fill(gx, gy, EQ_W / 3.0 - 1.0, gp - 1.0); + self.cv.setbg(); + } + self.eq_glyph(EQ_KINDS[b][t], gx + EQ_W / 6.0, gy + (gp - 1.0) * 0.5); + self.setc(false); + } + self.cell(o + 3, x, y0 + CELL_P, EQ_W, CELL_H, "Q"); + self.cell(o + 2, x, y0 + 2.0 * CELL_P, EQ_W, CELL_H, "FREQ"); + if matches!(eq_kind(b, ty), 2 | 3 | 4) { + self.cell(o + 4, x, y0 + 3.0 * CELL_P, EQ_W, CELL_H, "GAIN"); + } else { + self.setc(false); + self.cv.boxr(x, y0 + 3.0 * CELL_P, EQ_W, CELL_H); + self.cv.set_font(1); + self.cv.text(x + 3.0, y0 + 3.0 * CELL_P + 3.0, "GAIN"); + self.cv.set_font(2); + self.cv.textc(x, y0 + 3.0 * CELL_P + (CELL_H * 0.4 + 1.0).floor(), EQ_W, "---"); + } + } + self.set_dk(page_dk); + let x = VX + EQ_P * 5.0; + self.cell(EQ_PIVOT, x, y0, EQ_PW, CELL_H, "PIVOT"); + self.cell(EQ_TILT, x, y0 + CELL_P, EQ_PW, CELL_H, "TILT"); + self.cell(EQ_MIX, x, y0 + 2.0 * CELL_P, EQ_PW, CELL_H, "EQ MIX"); + self.cell_o(EQ_GAIN, x, y0 + 3.0 * CELL_P, EQ_PW, CELL_H, "EQ GAIN"); + } + + // ------------------------------------------------------------------ frame + pub fn frame(&mut self) { + let sh = self.env.shared; + #[cfg(test)] + { + if let Some(p) = self.s.test_apply.take() { + self.apply_preset(&p); + } + if std::mem::take(&mut self.s.test_want_capture) { + self.s.test_capture = Some(self.capture("test")); + } + } + // a finished sat level match writes that band's SAT GAIN (the audio thread cannot set parameters) + for b in 0..NB { + if sh.sat_result_new[b].swap(false, Ordering::Acquire) { + let v = sh.sat_result[b].load(Ordering::Relaxed); + self.click_set(band_base(b) + SAT_GAIN, v); + } + } + // readouts refresh ~8x/s + if self.kit.now - self.rd_last >= 0.12 { + self.rd_last = self.kit.now; + self.rd_pk = self.opk_max; + for b in 0..NB { + self.rd_sat[b] = sh.sat_db[b].load(Ordering::Relaxed); + } + self.rd_rms = sh.fms.load(Ordering::Relaxed); + self.rd_diff = sh.diff_disp.load(Ordering::Relaxed); + self.rd_eq_diff = sh.eq_diff.load(Ordering::Relaxed); + } + // Theme editor: every widget draws as a dummy with the input masked; only the editor cells and the picker get it. + let editing = self.app.editing(); + self.begin_frame_editing(); + if editing { + self.logo_pend = -1.0; + self.eq_page = false; + self.curve_edit = false; + self.menu = None; + } + self.env.dsp = self.env.params.to_dsp(); + self.update_gr(); + self.menu_frame(); + + // drag update (single active widget): slots (vertical drag) below VIEW_ACT, viewport drags from VIEW_ACT + if self.kit.act != 0 && self.kit.act < VIEW_ACT { + let a = self.kit.act as usize; + if self.kit.down { + let k = self.kit.shift; + let t_new = (self.kit.act_t + (self.kit.last_my - self.kit.my) * if k { 0.0008 } else { 0.006 }).clamp(0.0, 1.0); + self.kit.act_t = t_new; + self.commit(a, t_new); + } else { + self.end_touch(a); + self.kit.act = 0; + } + } + if self.kit.act >= VIEW_ACT && !self.kit.down { + for n in XOV { + self.end_touch(n); + } + self.end_touch(EQ_TILT); + self.end_touch(EQ_PIVOT); + for b in 0..NB { + self.end_touch(band_base(b) + THRESH); + } + for b in 0..5 { + for k in 2..5 { + self.end_touch(eq_base(b) + k); + } + } + self.kit.act = 0; + } + self.kit.last_my = self.kit.my; + + let byp = self.sget(8) > 0.5; + let eq_byp = self.sget(EQ_BYPASS) > 0.5; + let band_on = self.sget(band_base(self.sel()) + ON) > 0.5; + + self.resize_grip(); + + // ---------- header: logo, title, preset bar, sidechain (not wired yet), EQ page toggle, output meter + self.set_dk(1.0); + self.logo(13.0, 5.0); + self.setc(false); + self.cv.set_font(2); + let title = format!("SATXCOMP {}", version_short()); + let tw = self.cv.text_w(&title); + if self.hit(42.0, 5.0, tw + 4.0, 21.0) && self.kit.press && self.kit.act == 0 { + self.app.about = if self.app.about == 0 { 1 } else { 0 }; + self.app.about_scroll = 0; + self.kit.press = false; + } + // hovering highlights the title (a UI-coloured rectangle behind it, the text in the background colour): it opens About + if self.hit(42.0, 5.0, tw + 4.0, 21.0) { + self.cv.fill(42.0, 8.0, tw + 4.0, 15.0); + self.cv.setbg(); + } + self.cv.text(44.0, 12.0, &title); + self.setc(false); + self.preset_bar(); + // sidechain key: white = on and the host gave a bus, red = on but no bus + let sc_on = self.sget(SC_ON) > 0.5; + let sc_lit = if !sc_on { 0 } else if sh.sc_bus.load(Ordering::Relaxed) { 1 } else { 2 }; + if self.btn(402.0, 8.0, 76.0, 16.0, "SIDECHAIN", sc_lit) { + self.click_set(SC_ON, if sc_on { 0.0 } else { 1.0 }); + } + if !sc_on && sh.sc_solo.load(Ordering::Relaxed) { + sh.sc_solo.store(false, Ordering::Relaxed); // solo never outlives the sidechain switch + } + { + // EQ page toggle; the square in it bypasses the whole EQ module (X = bypassed, like SatComp) + let eq = self.env.dsp.eq; + let eq_any = eq.bands.iter().any(|b| b.on) || eq.tilt != 0.0 || eq.gain != 0.0; + self.sq_tog(EQ_BYPASS, 486.0, 12.0, 8.0); + if self.btn(478.0, 8.0, 46.0, 16.0, "", self.eq_page as u8) { + self.eq_page = !self.eq_page; + } + self.sqind(486.0, 12.0, 8.0, eq_any, self.eq_page, eq_byp); + // label drawn by hand so it keeps a clear gap from the square + if self.eq_page { + self.cv.setbg(); + } else { + self.setc(false); + } + self.cv.set_font(1); + self.cv.text(501.0, 12.0, "EQ"); + self.setc(false); + } + // LIM switch + output peak meter + let lim_on = self.sget(LIM_ON) > 0.5; + if self.btn(RX, 8.0, 30.0, 16.0, "LIM", lim_on as u8) { + self.click_set(LIM_ON, if lim_on { 0.0 } else { 1.0 }); + } + self.out_meter(RX + 34.0, 8.0, RW - 34.0, 16.0); + + // ---------- viewport row; right column: delta / bypass, levels, then the parameter group on the bottom edge + let delta = sh.delta_on.load(Ordering::Relaxed); + if self.btn(RX, VY, RW * 0.5, 16.0, "DELTA", if delta { 2 } else { 0 }) { + sh.delta_on.store(!delta, Ordering::Relaxed); + } + if self.btn(RX + RW * 0.5, VY, RW * 0.5, 16.0, "BYPASS", byp as u8) { + self.click_set(8, if byp { 0.0 } else { 1.0 }); + } + let ab = self.app.about > 0; + self.set_dk(if byp || (self.eq_page && eq_byp) { 0.5 } else { 1.0 }); + if ab { + // About / Appearance / Changelog replace the viewport and the band section (the right column stays) + self.set_dk(if byp { 0.5 } else { 1.0 }); + self.draw_about(Rect::new(VX, VY + 22.0, VW, CELLS_Y + 3.0 * CELL_P + CELL_H - VY - 22.0), byp); + } else if self.eq_page { + self.draw_eq(VX, VY, VW, VH); + } else { + // the sidechain controls and the scope settings take the bottom of the viewport while they are on + let scope_on = self.s.scope_on(); + let (sc_h, sp_h) = (if sc_on { SC_ROW_H } else { 0.0 }, if scope_on { SC_ROW_H } else { 0.0 }); + let vh = VH - sc_h - sp_h; + self.scope_icon(false); + if self.s.scope_on() { + self.draw_scope(VX, VY, VW, vh); + } else { + self.draw_spectrum(VX, VY, VW, vh); + self.draw_crossover(VX, VY, VW, vh); + } + self.scope_icon(true); + self.set_dk(if byp { 0.5 } else { 1.0 }); + if sc_on { + self.sc_row(VX, VY + vh); + } + if scope_on { + self.scope_row(VX, VY + vh + sc_h); + } + } + self.set_dk(1.0); + self.cv.set_font(1); + self.setc(false); + // limiter reduction first (same order as SatComp): accent once it has engaged + let lim_on = self.sget(LIM_ON) > 0.5; + self.setc(lim_on && self.lim_txt > 0.05); + self.cv.text(RX, VY + 22.0, "LIM"); + let s1 = if lim_on { format!("{:04.1}dB", self.lim_txt) } else { "-----dB".to_string() }; + self.cv.textr(RX, VY + 22.0, RW, &s1); + let s1 = if self.rd_pk > 0.00001 { format!("{:+05.1}dB", 8.6858896 * self.rd_pk.ln()) } else { "-----dB".into() }; + self.setc(self.rd_pk > 0.9999); + self.cv.text(RX, VY + 34.0, "PK"); + self.cv.textr(RX, VY + 34.0, RW, &s1); + self.setc(false); + let s1 = if self.rd_rms > 0.000000001 { format!("{:+05.1}dB", 4.3429448 * self.rd_rms.ln()) } else { "-----dB".into() }; + self.cv.text(RX, VY + 46.0, "RMS"); + self.cv.textr(RX, VY + 46.0, RW, &s1); + // parameter group, evenly spaced and aligned to the viewport's bottom edge: three crossovers, oversampling + let os_y = VY + VH - 16.0; + for k in 0..3 { + let y = os_y - (3 - k) as f32 * 22.0; + self.xover_row(k, RX, y); + } + self.set_dk(1.0); // oversampling stays lit while bypassed + let os_i = (self.sget(3) + 0.5).floor() as i32; + for i in 0..3 { + let l = ["x1", "x2", "x4"][i as usize]; + if self.btn(RX + i as f32 * RW / 3.0, os_y, RW / 3.0, 16.0, l, (os_i == i) as u8) { + self.click_set(3, i as f32); + } + } + self.set_dk(1.0); + + // ---------- band row, band cells, output column + if ab { + } else if self.eq_page { + self.set_dk(if byp || eq_byp { 0.5 } else { 1.0 }); + self.eq_row(BAND_Y); + self.eq_cells(CELLS_Y); + } else { + self.band_row(BAND_Y); + self.set_dk(if byp || !band_on { 0.5 } else { 1.0 }); + self.band_cells(CELLS_Y); + } + // lookahead belongs to the output module: visible on both pages + self.set_dk(1.0); + self.cell1(4, RX, BAND_Y, RW, 16.0, "L.AHEAD"); + self.out_column(CELLS_Y); + self.menu_draw(); + self.poll_dialog(); + self.run_pending(); + if editing { + // the colour picker / on-screen keyboard sit over the viewport, live on top of the masked dummy page + let over = Rect::new(VX + ((VW - 266.0) * 0.5).floor(), VY + ((VH - 128.0) * 0.5).floor(), 266.0, 128.0); + self.unmask_in(); + let osk = self.app.osk_open(); + if osk { + self.mask_in(); // picker stays visible underneath but inert + } + self.theme_picker(over); + if osk { + self.unmask_in(); + self.theme_osk(over); + } + } + } +} diff --git a/rust/satxcomp-plugin/src/gui/ui/scope.rs b/rust/satxcomp-plugin/src/gui/ui/scope.rs new file mode 100644 index 0000000..bd7779f --- /dev/null +++ b/rust/satxcomp-plugin/src/gui/ui/scope.rs @@ -0,0 +1,279 @@ +//! Waveform scope ("transient meter"): an alternate view of the viewport (spectrum). Half or full wave peak display of the +//! output in the UI colour, with the gain reduction the compressor removed stacked on top in the accent colour. + +use super::*; + +const SRC: [&str; 3] = ["OUT+GR", "OUT", "GR"]; +const WAVE: [&str; 2] = ["HALF", "FULL"]; +/// time window steps (seconds) and their labels +const WIN_S: [f32; 10] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0]; +const WIN_L: [&str; 10] = ["250ms", "0.5s", "0.75s", "1s", "1.5s", "2s", "3s", "4s", "6s", "8s"]; +/// ceiling steps: +2 dB (0 dBFS sits at about 79 % of the height: room to watch inter-sample overshoots) down to -14 dB +/// (the top edge is 20 % of full scale) +const CEIL_N: usize = 17; + +fn ceil_db(i: usize) -> i32 { + 2 - i as i32 +} + +/// (output peak, peak before the reduction) of absolute column `j` on a grid of `k` buckets per column, read from a ring whose +/// newest bucket index is `head - 1`. Pure in (ring contents, j, k): once a column is complete it never changes. +fn scope_col(ring: &satcomp_dsp::ScopeRing, head: usize, j: i64, k: f64) -> (f32, f32) { + let len = satcomp_dsp::ScopeRing::LEN as i64; + let b0 = j as f64 * k; + let i0 = b0.floor() as i64; + let i1 = ((b0 + k).floor() as i64).max(i0 + 1); + let (mut o, mut p) = (0.0f32, 0.0f32); + for i in i0..i1 { + if i < 0 || head as i64 - i >= len { + continue; + } + let (a, b) = ring.get(i as usize); + o = o.max(a); + p = p.max(b); + } + (o, p.max(o)) +} + +fn fmt_db(db: i32) -> String { + if db > 0 { format!("+{db}dB") } else { format!("{db}dB") } +} + +// Packed settings (params.scope, default (5 << 4) | (2 << 8) = 2 s window, 0 dB ceiling): bit 0 on, bits 1-2 source, +// bit 3 full wave, bits 4-7 window step, bits 8-12 ceiling step (ceil_db). + +impl State { + pub fn scope_on(&self) -> bool { + self.scope_cfg & 1 != 0 && self.app.edit.is_none() + } +} + +impl<'a> Gui<'a> { + fn sc_get(&self, shift: u32, bits: i32) -> usize { + ((self.scope_cfg >> shift) & bits) as usize + } + + fn sc_set(&mut self, shift: u32, bits: i32, v: usize) { + self.scope_cfg = (self.scope_cfg & !(bits << shift)) | ((v as i32 & bits) << shift); + self.env.params.scope.store(self.scope_cfg, Ordering::Relaxed); + } + + /// Toggle icon in the top right corner of the viewport (draw = false: handle the click only). + pub(super) fn scope_icon(&mut self, draw: bool) { + let (x, y) = (VX + VW - 16.0, VY + 3.0); + let on = self.scope_cfg & 1 != 0; + if !draw { + if self.hit(x, y, 13.0, 12.0) && self.kit.press && self.kit.act == 0 { + self.sc_set(0, 1, !on as usize); + self.kit.press = false; + } + return; + } + // 3 bars of different heights, like a tiny waveform + self.setc(false); + if on { + self.cv.fill(x, y, 13.0, 12.0); + self.cv.setbg(); + } else { + self.cv.setbg(); + self.cv.fill(x, y, 13.0, 12.0); + self.setc(false); + self.cv.boxr(x, y, 13.0, 12.0); + } + for (i, bh) in [3.0f32, 7.0, 4.0, 6.0].iter().enumerate() { + self.cv.fill(x + 2.0 + i as f32 * 3.0, y + 10.0 - bh, 2.0, *bh); + } + self.setc(false); + } + + pub(super) fn draw_scope(&mut self, x: f32, y: f32, w: f32, h: f32) { + let (src, full) = (self.sc_get(1, 3).min(2), self.sc_get(3, 1) == 1); + let (win, ceil) = (self.sc_get(4, 15).min(WIN_S.len() - 1), self.sc_get(8, 31).min(CEIL_N - 1)); + // viewport drag (relative): x steps through the window, y moves the ceiling (down = lower ceiling = zoomed in) + if self.hit(x, y, w, h) && self.kit.press && self.kit.act == 0 { + self.kit.act = ACT_SCOPE; + self.scope_drag = (self.kit.mx, self.kit.my, win, ceil); + self.kit.press = false; + } + let dragging = self.kit.act == ACT_SCOPE; + if dragging && self.kit.down { + let (sx, sy, w0, c0) = self.scope_drag; + let nw = (w0 as f32 + (self.kit.mx - sx) / w * (WIN_S.len() - 1) as f32).round().clamp(0.0, (WIN_S.len() - 1) as f32); + let nc = (c0 as f32 + (self.kit.my - sy) / h * (CEIL_N - 1) as f32).round().clamp(0.0, (CEIL_N - 1) as f32); + self.sc_set(4, 15, nw as usize); + self.sc_set(8, 31, nc as usize); + } + let (win, ceil) = (self.sc_get(4, 15).min(WIN_S.len() - 1), self.sc_get(8, 31).min(CEIL_N - 1)); + let zoom = 10f32.powf(-ceil_db(ceil) as f32 / 20.0); // 1 / ceiling amplitude + self.setc(false); + self.cv.boxr(x, y, w, h); + let ring = self.env.shared.scope.clone(); + let head = ring.head(); + let ncol = (w - 2.0) as usize; + let k = WIN_S[win] as f64 / satcomp_dsp::ScopeRing::BUCKET_S / ncol as f64; // buckets per column (fractional) + // Steady scrolling: the audio thread delivers buckets in host-block chunks, and a column grouped relative to the newest + // bucket changes every frame. So (1) the read position eases toward the head instead of jumping with each chunk, and + // (2) columns sit on a fixed grid in absolute bucket time and only complete ones are drawn: a column's content never + // changes once it exists, the picture just advances. + let target = head as f64 - 4.0; + let dt = (self.kit.now - self.scope_t).clamp(0.0, 0.25); + self.scope_t = self.kit.now; + if self.scope_pos <= 0.0 || (target - self.scope_pos).abs() > 4000.0 { + self.scope_pos = target; + } else { + self.scope_pos += (target - self.scope_pos) * (1.0 - (-dt * 10.0).exp()); + } + let last = (self.scope_pos / k).floor() as i64 - 1; // newest complete column + let mut cols = vec![(0.0f32, 0.0f32); ncol]; + for (c, col) in cols.iter_mut().enumerate() { + *col = scope_col(&ring, head, last - (ncol - 1 - c) as i64, k); + } + let span = if full { ((h - 2.0) * 0.5).floor() } else { h - 2.0 }; + let hpx = |v: f32| ((v * zoom).min(1.0) * span).floor(); + let base = if full { y + (h * 0.5).floor() } else { y + h - 1.0 }; + // output (UI colour) + if src < 2 { + self.setc(false); + for (c, &(o, _)) in cols.iter().enumerate() { + let ho = hpx(o); + if ho > 0.0 { + let cx = x + 1.0 + c as f32; + if full { + self.cv.fill(cx, base - ho, 1.0, 2.0 * ho + 1.0); + } else { + self.cv.fill(cx, base - ho, 1.0, ho + 1.0); + } + } + } + } + // reduction (accent): what the compressor took off, stacked on the output (or alone from the baseline) + if src != 1 { + self.setc(true); + for (c, &(o, p)) in cols.iter().enumerate() { + let cx = x + 1.0 + c as f32; + let (lo, hi) = if src == 0 { (hpx(o), hpx(p)) } else { (0.0, hpx(p - o)) }; + if hi > lo { + if full { + self.cv.fill(cx, base - hi, 1.0, hi - lo); + self.cv.fill(cx, base + lo + 1.0, 1.0, hi - lo); + } else { + self.cv.fill(cx, base - hi, 1.0, hi - lo); + } + } + } + } + self.setc(false); + if full { + self.cv.fill(x + 1.0, base, 1.0, 1.0); // centre tick + } + if zoom < 0.999 { + // ceiling above 0 dBFS: a faint UI-colour line marks 0 dBFS (the ceiling of a normal signal); anything above it + // is an overshoot + let off = (zoom * span).floor(); + let keep = self.kit.dk; + self.set_dk(keep * 0.35); + self.setc(false); + self.cv.fill(x + 1.0, base - off, w - 2.0, 1.0); + if full { + self.cv.fill(x + 1.0, base + off, w - 2.0, 1.0); + } + self.set_dk(keep); + self.setc(false); + } + if dragging { + let t = format!("WIN {} CEIL {}", WIN_L[win], fmt_db(ceil_db(ceil))); + let tw = self.cv.text_w(&t); + self.cv.setbg(); + self.cv.fill(x + 4.0, y + 4.0, tw + 8.0, 13.0); + self.setc(false); + self.cv.boxr(x + 4.0, y + 4.0, tw + 8.0, 13.0); + self.cv.set_font(1); + self.cv.text(x + 8.0, y + 8.0, &t); + } + } + + /// Settings under the scope: source and wave type cycle on click; window and ceiling are drag sliders (stepped). + pub(super) fn scope_row(&mut self, x: f32, y: f32) { + let h = 17.0; + // four equal cells across the viewport (neighbours share their border pixel) + let cw = ((VW + 3.0) / 4.0).floor(); + let ceil_w = VW + 3.0 - 3.0 * cw; + let mut cx = x; + // SRC and WAVE: click / wheel cycles + for (lbl, names, shift, bits, w) in [("SRC", &SRC[..], 1u32, 3i32, cw), ("WAVE", &WAVE[..], 3, 1, cw)] { + let n = names.len(); + let cur = self.sc_get(shift, bits).min(n - 1); + if self.hit(cx, y, w, h) { + if self.kit.press && self.kit.act == 0 { + self.sc_set(shift, bits, (cur + 1) % n); + self.kit.press = false; + } else if self.kit.wheel != 0 { + let nx = (cur as i32 + if self.kit.wheel > 0 { 1 } else { -1 }).clamp(0, n as i32 - 1) as usize; + self.sc_set(shift, bits, nx); + } + } + self.setc(false); + self.cv.boxr(cx, y, w, h); + self.cv.set_font(1); + self.cv.text(cx + 4.0, y + 5.0, lbl); + self.cv.textr(cx, y + 5.0, w - 4.0, names[cur]); + cx += w - 1.0; + } + // WIN and CEIL: horizontal drag sliders over their cell, stepped + for (k, lbl, shift, bits, n, w) in [(0usize, "WIN", 4u32, 15i32, WIN_S.len(), cw), (1, "CEIL", 8, 31, CEIL_N, ceil_w)] { + let act = ACT_SCOPE + 1 + k as i32; + let cur = self.sc_get(shift, bits).min(n - 1); + if self.hit(cx, y, w, h) { + if self.kit.press && self.kit.act == 0 { + self.kit.act = act; + self.kit.press = false; + } else if self.kit.wheel != 0 { + let nx = (cur as i32 + if self.kit.wheel > 0 { -1 } else { 1 }).clamp(0, n as i32 - 1) as usize; + self.sc_set(shift, bits, nx); + } + } + if self.kit.act == act && self.kit.down { + let f = ((self.kit.mx - cx - 2.0) / (w - 4.0)).clamp(0.0, 1.0); + self.sc_set(shift, bits, (f * (n - 1) as f32 + 0.5).floor() as usize); + } + let cur = self.sc_get(shift, bits).min(n - 1); + self.setc(self.kit.act == act); + self.cv.boxr(cx, y, w, h); + self.cv.set_font(1); + self.cv.text(cx + 4.0, y + 5.0, lbl); + let val = if k == 0 { WIN_L[cur].to_string() } else { fmt_db(ceil_db(cur)) }; + self.cv.textr(cx, y + 5.0, w - 4.0, &val); + let t = cur as f32 / (n - 1) as f32; + self.cv.fill(cx + 2.0, y + h - 3.0, ((t * (w - 4.0)).floor()).max(1.0), 1.0); + self.setc(false); + cx += w - 1.0; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_complete_column_does_not_change_as_new_buckets_arrive() { + let ring = satcomp_dsp::ScopeRing::new(); + let val = |i: usize| 0.2 + 0.3 * ((i as f32 * 0.37).sin().abs()); + for i in 0..2000 { + ring.push(val(i), val(i) * 1.5); + } + // k = 3.7 buckets per column (a fractional window), the same columns read at two different heads + let k = 3.7; + let head0 = ring.head(); + let before: Vec<_> = (400..420).map(|j| scope_col(&ring, head0, j, k)).collect(); + for i in 2000..2013 { + ring.push(val(i), val(i) * 1.5); + } + let after: Vec<_> = (400..420).map(|j| scope_col(&ring, ring.head(), j, k)).collect(); + assert_eq!(before, after); + // a column reads the maximum of the buckets it spans: column 500 covers buckets 1850..1853 + let (o, _) = scope_col(&ring, ring.head(), 500, k); + let want = (1850..1853).map(val).fold(0.0f32, f32::max); + assert!((o - want).abs() < 1e-6, "{o} vs {want}"); + } +} diff --git a/rust/satxcomp-plugin/src/lib.rs b/rust/satxcomp-plugin/src/lib.rs new file mode 100644 index 0000000..a056cfd --- /dev/null +++ b/rust/satxcomp-plugin/src/lib.rs @@ -0,0 +1,314 @@ +//! SatXComp: 4-band multiband saturator + compressor with a post EQ. nih-plug shell around `satxcomp_dsp::XEngine`. + +mod gui; +mod params; +mod presets; + +use nih_plug::prelude::*; +use params::SatXCompParams; +use satcomp_dsp::shapers::Curve; +use satcomp_dsp::{ScopeRing, TapRing}; +use satxcomp_dsp::XEngine; +use std::num::NonZeroU32; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Instant; + +/// State shared between the audio thread and the editor (all lock-free). +pub struct Shared { + pub tap_out: Arc, + pub tap_dry: Arc, + /// per 2 ms bucket: output peak and the same with the gain reduction added back (waveform scope) + pub scope: Arc, + pub epoch: Instant, + pub sample_rate: AtomicF32, + // audio -> UI. Peaks accumulate with fetch_max and are consumed with swap(0). + pub opk: [AtomicF32; 2], + pub clip: AtomicBool, + pub gr_pk: [AtomicF32; 4], + /// per band: gain lift of the upward compressor (dB, >= 0), accumulated like `gr_pk` + pub gl_pk: [AtomicF32; 4], + /// per band: level change across the strip, dB + pub band_diff: [AtomicF32; 4], + /// output limiter gain reduction (dB, positive), accumulated like `gr_pk` + pub lim_gr_pk: AtomicF32, + /// per band: decaying peak of the saturator input + pub sat_vz: [AtomicF32; 4], + /// per band: post-saturator peak since the UI last took it (fetch_max / swap(0)) + pub sat_out_pk: [AtomicF32; 4], + pub fms: AtomicF32, + pub diff_disp: AtomicF32, + /// level change across the EQ stage, dB + pub eq_diff: AtomicF32, + pub out_meas: AtomicBool, + pub out_mt: AtomicF32, + // UI -> audio + pub match_req: AtomicBool, + /// per band: SAT GAIN level match request (UI -> audio), live loudness change across the saturator (dB), measurement + /// state and progress, and the finished result the UI writes to the band's SAT GAIN (audio -> UI) + pub sat_req: [AtomicBool; 4], + pub sat_db: [AtomicF32; 4], + pub sat_meas: [AtomicBool; 4], + pub sat_mt: [AtomicF32; 4], + pub sat_result: [AtomicF32; 4], + pub sat_result_new: [AtomicBool; 4], + pub delta_on: AtomicBool, + /// monitor the conditioned sidechain key instead of the output (UI -> audio) + pub sc_solo: AtomicBool, + /// the host provided a sidechain bus in the last block (audio -> UI) + pub sc_bus: AtomicBool, + /// last time (ms since epoch + 1000) a spectrum view drew; the audio thread only feeds the taps while this is fresh + pub spec_vis_ms: AtomicU64, +} + +impl Shared { + pub fn new() -> Self { + Self { + tap_out: Arc::new(TapRing::new()), + tap_dry: Arc::new(TapRing::new()), + scope: Arc::new(ScopeRing::new()), + epoch: Instant::now(), + sample_rate: AtomicF32::new(48000.0), + opk: [AtomicF32::new(0.0), AtomicF32::new(0.0)], + clip: AtomicBool::new(false), + gr_pk: [AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0)], + gl_pk: [AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0)], + band_diff: [AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0)], + lim_gr_pk: AtomicF32::new(0.0), + sat_vz: [AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0)], + sat_out_pk: [AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0), AtomicF32::new(0.0)], + fms: AtomicF32::new(1e-9), + diff_disp: AtomicF32::new(0.0), + eq_diff: AtomicF32::new(0.0), + out_meas: AtomicBool::new(false), + out_mt: AtomicF32::new(0.0), + match_req: AtomicBool::new(false), + sat_req: std::array::from_fn(|_| AtomicBool::new(false)), + sat_db: std::array::from_fn(|_| AtomicF32::new(0.0)), + sat_meas: std::array::from_fn(|_| AtomicBool::new(false)), + sat_mt: std::array::from_fn(|_| AtomicF32::new(0.0)), + sat_result: std::array::from_fn(|_| AtomicF32::new(0.0)), + sat_result_new: std::array::from_fn(|_| AtomicBool::new(false)), + delta_on: AtomicBool::new(false), + sc_solo: AtomicBool::new(false), + sc_bus: AtomicBool::new(true), + spec_vis_ms: AtomicU64::new(0), + } + } + pub fn now_ms(&self) -> u64 { + self.epoch.elapsed().as_millis() as u64 + 1000 + } +} + +impl Default for Shared { + fn default() -> Self { + Self::new() + } +} + +pub struct SatXComp { + params: Arc, + shared: Arc, + engine: XEngine, + last_latency: u32, + last_curves: [Curve; 4], + last_asym: [[f64; satxcomp_dsp::params::SHAPER_COUNT]; 4], +} + +impl SatXComp { + fn new_engine(&self, sr: f64) -> XEngine { + let mut e = XEngine::new(sr); + e.tap_out = self.shared.tap_out.clone(); + e.tap_dry = self.shared.tap_dry.clone(); + e.scope = self.shared.scope.clone(); + e.match_trim = self.params.match_trim.load(Ordering::Relaxed) as f64; + e + } +} + +impl Default for SatXComp { + fn default() -> Self { + let shared = Arc::new(Shared::new()); + let mut engine = XEngine::new(48000.0); + engine.tap_out = shared.tap_out.clone(); + engine.tap_dry = shared.tap_dry.clone(); + engine.scope = shared.scope.clone(); + Self { params: Arc::new(SatXCompParams::default()), shared, engine, last_latency: u32::MAX, last_curves: [Curve::linear(); 4], last_asym: [[100.0; satxcomp_dsp::params::SHAPER_COUNT]; 4] } + } +} + +impl Plugin for SatXComp { + const NAME: &'static str = "SatXComp"; + const VENDOR: &'static str = "thomchantra"; + const URL: &'static str = ""; + const EMAIL: &'static str = ""; + const VERSION: &'static str = env!("CARGO_PKG_VERSION"); + + // First layout = stereo + stereo sidechain; hosts without sidechain support fall back to the second. + 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)], + names: PortNames { aux_inputs: &["Sidechain"], ..PortNames::const_default() }, + ..AudioIOLayout::const_default() + }, + AudioIOLayout { + main_input_channels: NonZeroU32::new(2), + main_output_channels: NonZeroU32::new(2), + ..AudioIOLayout::const_default() + }, + ]; + + type SysExMessage = (); + type BackgroundTask = (); + + fn params(&self) -> Arc { + self.params.clone() + } + + fn editor(&mut self, _async_executor: AsyncExecutor) -> Option> { + gui::create(self.params.clone(), self.shared.clone()) + } + + fn initialize(&mut self, _layout: &AudioIOLayout, buffer_config: &BufferConfig, context: &mut impl InitContext) -> bool { + let sr = buffer_config.sample_rate as f64; + self.shared.sample_rate.store(sr as f32, Ordering::Relaxed); + let mut engine = self.new_engine(sr); + engine.set_params(&self.params.to_dsp()); + self.engine = engine; + self.last_latency = self.engine.latency(); + context.set_latency_samples(self.last_latency); + true + } + + fn reset(&mut self) { + let sr = self.engine.sample_rate(); + let mut engine = self.new_engine(sr); + engine.set_params(&self.params.to_dsp_rt(&mut self.last_curves, &mut self.last_asym)); + self.engine = engine; + } + + fn process(&mut self, buffer: &mut Buffer, aux: &mut AuxiliaryBuffers, context: &mut impl ProcessContext) -> ProcessStatus { + let sh = &self.shared; + self.engine.set_params(&self.params.to_dsp_rt(&mut self.last_curves, &mut self.last_asym)); + let lat = self.engine.latency(); + if lat != self.last_latency { + self.last_latency = lat; + context.set_latency_samples(lat); + } + for b in 0..4 { + if sh.sat_req[b].swap(false, Ordering::Relaxed) { + self.engine.request_sat_match(b); + } + } + if sh.match_req.swap(false, Ordering::Relaxed) { + self.engine.request_match(); + } + self.engine.delta_on = sh.delta_on.load(Ordering::Relaxed); + self.engine.tap_on = sh.now_ms().saturating_sub(sh.spec_vis_ms.load(Ordering::Relaxed)) < 300; + self.engine.sc_solo = sh.sc_solo.load(Ordering::Relaxed); + let ch = buffer.as_slice(); + let sc_in = aux.inputs.first_mut().map(|b| b.as_slice_immutable()); + let sc_pair = match sc_in { + Some([a, b]) => Some((&a[..], &b[..])), + _ => None, + }; + sh.sc_bus.store(sc_pair.is_some(), Ordering::Relaxed); + if let [l, r] = ch { + self.engine.process_sc(l, r, sc_pair); + } + let e = &mut self.engine; + sh.opk[0].fetch_max(e.opk[0] as f32, Ordering::Relaxed); + sh.opk[1].fetch_max(e.opk[1] as f32, Ordering::Relaxed); + e.opk = [0.0; 2]; + if e.clip_f { + sh.clip.store(true, Ordering::Relaxed); + e.clip_f = false; + } + sh.lim_gr_pk.fetch_max(e.lim_gr_pk as f32, Ordering::Relaxed); + e.lim_gr_pk = 0.0; + for b in 0..4 { + sh.gr_pk[b].fetch_max(e.gr_pk[b] as f32, Ordering::Relaxed); + e.gr_pk[b] = 0.0; + sh.gl_pk[b].fetch_max(e.gl_pk[b] as f32, Ordering::Relaxed); + e.gl_pk[b] = 0.0; + sh.band_diff[b].store(e.band_diff[b] as f32, Ordering::Relaxed); + } + for b in 0..4 { + sh.sat_vz[b].store(e.sat_vz[b] as f32, Ordering::Relaxed); + sh.sat_out_pk[b].fetch_max(e.sat_out[b] as f32, Ordering::Relaxed); + e.sat_out[b] = 0.0; + sh.sat_db[b].store(e.sat_db[b] as f32, Ordering::Relaxed); + sh.sat_meas[b].store(e.sat_matching(b), Ordering::Relaxed); + sh.sat_mt[b].store(e.sat_match_progress(b) as f32, Ordering::Relaxed); + if let Some(v) = e.take_sat_result(b) { + sh.sat_result[b].store(v as f32, Ordering::Relaxed); + sh.sat_result_new[b].store(true, Ordering::Release); + } + } + sh.fms.store(e.fms as f32, Ordering::Relaxed); + sh.diff_disp.store(e.diff_disp as f32, Ordering::Relaxed); + sh.eq_diff.store(e.eq_diff as f32, Ordering::Relaxed); + sh.out_meas.store(e.out_matching(), Ordering::Relaxed); + sh.out_mt.store(e.out_match_progress() as f32, Ordering::Relaxed); + self.params.match_trim.store(e.match_trim as f32, Ordering::Relaxed); + ProcessStatus::Normal + } +} + +impl Vst3Plugin for SatXComp { + // 16 bytes, must stay stable forever once released (plug-in identity). + const VST3_CLASS_ID: [u8; 16] = *b"thomchantraSatXC"; + const VST3_SUBCATEGORIES: &'static [Vst3SubCategory] = &[Vst3SubCategory::Fx, Vst3SubCategory::Dynamics, Vst3SubCategory::Distortion]; +} + +impl ClapPlugin for SatXComp { + const CLAP_ID: &'static str = "com.thomchantra.satxcomp"; + const CLAP_DESCRIPTION: Option<&'static str> = Some("4-band saturator + compressor with EQ"); + const CLAP_MANUAL_URL: Option<&'static str> = None; + const CLAP_SUPPORT_URL: Option<&'static str> = None; + const CLAP_FEATURES: &'static [ClapFeature] = &[ClapFeature::AudioEffect, ClapFeature::Compressor, ClapFeature::Distortion, ClapFeature::Stereo]; +} + +nih_export_vst3!(SatXComp); +nih_export_clap!(SatXComp); + +#[cfg(test)] +mod tests { + use super::*; + use satxcomp_dsp::XParams; + + #[test] + fn generated_defaults_match_engine_defaults() { + let p = SatXCompParams::default(); + // plug-in parameters are f32, the engine's are f64: compare the EQ Q the way the plug-in stores it + let mut want = XParams::default(); + for b in want.eq.bands.iter_mut() { + b.q = b.q as f32 as f64; + } + assert_eq!(p.to_dsp(), want); + } + + #[test] + fn every_table_slot_resolves_and_is_unique() { + let p = SatXCompParams::default(); + let mut seen = std::collections::HashSet::new(); + for &(n, id, mn, mx, df) in params::TABLE { + assert!(n < params::SLOTS, "{id}"); + assert!(seen.insert(n), "slot {n} used twice"); + assert!(p.ptr(n).is_some(), "{id}"); + assert!(mn < mx && df >= mn && df <= mx, "{id} range"); + } + } + + #[test] + fn ids_are_unique_and_identity_is_thomchantra() { + let mut ids = std::collections::HashSet::new(); + for &(_, id, ..) in params::TABLE { + assert!(ids.insert(id), "{id}"); + } + assert_eq!(::VST3_CLASS_ID.len(), 16); + assert!(::CLAP_ID.starts_with("com.thomchantra.")); + } +} diff --git a/rust/satxcomp-plugin/src/params.rs b/rust/satxcomp-plugin/src/params.rs new file mode 100644 index 0000000..e475da0 --- /dev/null +++ b/rust/satxcomp-plugin/src/params.rs @@ -0,0 +1,915 @@ +// GENERATED by tools/gen_xparams.py. Do not edit by hand. + +use nih_plug::prelude::*; +use nih_plug_egui::EguiState; +use satcomp_dsp::shapers::Curve; +use satxcomp_dsp::params::SHAPER_COUNT; +use satxcomp_dsp::{BandParams, EqBandParams, EqParams, XParams}; +use std::sync::atomic::{AtomicBool, AtomicI32}; +use std::sync::Arc; + +/// Highest UI slot number + 1. +pub const SLOTS: usize = 164; + +/// (slot number, id, min, max, default) for every parameter. +pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[ + (1, "x1", 20.0, 2000.0, 150.0), + (2, "x2", 200.0, 20000.0, 800.0), + (9, "x3", 200.0, 20000.0, 3500.0), + (3, "os", 0.0, 2.0, 0.0), + (4, "lookahead", 0.0, 10.0, 0.0), + (5, "mix", 0.0, 100.0, 100.0), + (6, "out_gain", -24.0, 12.0, 0.0), + (7, "gain_match", 0.0, 1.0, 0.0), + (8, "bypass", 0.0, 1.0, 0.0), + (106, "x1_slope", 0.0, 3.0, 1.0), + (107, "x2_slope", 0.0, 3.0, 1.0), + (108, "x3_slope", 0.0, 3.0, 1.0), + (110, "sc_on", 0.0, 1.0, 0.0), + (111, "sc_gain", -24.0, 24.0, 0.0), + (112, "sc_hp", 20.0, 2000.0, 20.0), + (113, "sc_lp", 200.0, 20000.0, 20000.0), + (114, "sc_mix", 0.0, 100.0, 100.0), + (10, "lo_on", 0.0, 1.0, 1.0), + (11, "lo_solo", 0.0, 1.0, 0.0), + (12, "lo_delta", 0.0, 1.0, 0.0), + (13, "lo_shape", 0.0, 14.0, 0.0), + (14, "lo_drive", 0.0, 100.0, 0.0), + (15, "lo_bias", -100.0, 100.0, 0.0), + (16, "lo_tone", 1000.0, 20000.0, 20000.0), + (17, "lo_sat_mix", 0.0, 100.0, 100.0), + (18, "lo_sat_gain", -24.0, 12.0, 0.0), + (19, "lo_thresh", -40.0, 0.0, 0.0), + (20, "lo_ratio", 1.0, 20.0, 4.0), + (21, "lo_attack", 0.05, 100.0, 10.0), + (22, "lo_release", 5.0, 2000.0, 150.0), + (23, "lo_speed", 0.0, 100.0, 50.0), + (24, "lo_knee", 0.0, 24.0, 6.0), + (25, "lo_knee_shape", 0.0, 100.0, 0.0), + (26, "lo_detector", 0.0, 100.0, 30.0), + (27, "lo_ff_fb", 0.0, 100.0, 0.0), + (28, "lo_gr_dist", 0.0, 100.0, 0.0), + (29, "lo_comp_mix", 0.0, 100.0, 100.0), + (30, "lo_comp_gain", -12.0, 24.0, 0.0), + (31, "lo_hp", 20.0, 2000.0, 20.0), + (32, "lo_lp", 200.0, 20000.0, 20000.0), + (33, "lo_up", 0.0, 2.0, 0.0), + (160, "lo_up_range", 0.0, 24.0, 12.0), + (34, "mid_on", 0.0, 1.0, 1.0), + (35, "mid_solo", 0.0, 1.0, 0.0), + (36, "mid_delta", 0.0, 1.0, 0.0), + (37, "mid_shape", 0.0, 14.0, 0.0), + (38, "mid_drive", 0.0, 100.0, 0.0), + (39, "mid_bias", -100.0, 100.0, 0.0), + (40, "mid_tone", 1000.0, 20000.0, 20000.0), + (41, "mid_sat_mix", 0.0, 100.0, 100.0), + (42, "mid_sat_gain", -24.0, 12.0, 0.0), + (43, "mid_thresh", -40.0, 0.0, 0.0), + (44, "mid_ratio", 1.0, 20.0, 4.0), + (45, "mid_attack", 0.05, 100.0, 10.0), + (46, "mid_release", 5.0, 2000.0, 150.0), + (47, "mid_speed", 0.0, 100.0, 50.0), + (48, "mid_knee", 0.0, 24.0, 6.0), + (49, "mid_knee_shape", 0.0, 100.0, 0.0), + (50, "mid_detector", 0.0, 100.0, 30.0), + (51, "mid_ff_fb", 0.0, 100.0, 0.0), + (52, "mid_gr_dist", 0.0, 100.0, 0.0), + (53, "mid_comp_mix", 0.0, 100.0, 100.0), + (54, "mid_comp_gain", -12.0, 24.0, 0.0), + (55, "mid_hp", 20.0, 2000.0, 20.0), + (56, "mid_lp", 200.0, 20000.0, 20000.0), + (57, "mid_up", 0.0, 2.0, 0.0), + (161, "mid_up_range", 0.0, 24.0, 12.0), + (58, "mh_on", 0.0, 1.0, 1.0), + (59, "mh_solo", 0.0, 1.0, 0.0), + (60, "mh_delta", 0.0, 1.0, 0.0), + (61, "mh_shape", 0.0, 14.0, 0.0), + (62, "mh_drive", 0.0, 100.0, 0.0), + (63, "mh_bias", -100.0, 100.0, 0.0), + (64, "mh_tone", 1000.0, 20000.0, 20000.0), + (65, "mh_sat_mix", 0.0, 100.0, 100.0), + (66, "mh_sat_gain", -24.0, 12.0, 0.0), + (67, "mh_thresh", -40.0, 0.0, 0.0), + (68, "mh_ratio", 1.0, 20.0, 4.0), + (69, "mh_attack", 0.05, 100.0, 10.0), + (70, "mh_release", 5.0, 2000.0, 150.0), + (71, "mh_speed", 0.0, 100.0, 50.0), + (72, "mh_knee", 0.0, 24.0, 6.0), + (73, "mh_knee_shape", 0.0, 100.0, 0.0), + (74, "mh_detector", 0.0, 100.0, 30.0), + (75, "mh_ff_fb", 0.0, 100.0, 0.0), + (76, "mh_gr_dist", 0.0, 100.0, 0.0), + (77, "mh_comp_mix", 0.0, 100.0, 100.0), + (78, "mh_comp_gain", -12.0, 24.0, 0.0), + (79, "mh_hp", 20.0, 2000.0, 20.0), + (80, "mh_lp", 200.0, 20000.0, 20000.0), + (81, "mh_up", 0.0, 2.0, 0.0), + (162, "mh_up_range", 0.0, 24.0, 12.0), + (82, "hi_on", 0.0, 1.0, 1.0), + (83, "hi_solo", 0.0, 1.0, 0.0), + (84, "hi_delta", 0.0, 1.0, 0.0), + (85, "hi_shape", 0.0, 14.0, 0.0), + (86, "hi_drive", 0.0, 100.0, 0.0), + (87, "hi_bias", -100.0, 100.0, 0.0), + (88, "hi_tone", 1000.0, 20000.0, 20000.0), + (89, "hi_sat_mix", 0.0, 100.0, 100.0), + (90, "hi_sat_gain", -24.0, 12.0, 0.0), + (91, "hi_thresh", -40.0, 0.0, 0.0), + (92, "hi_ratio", 1.0, 20.0, 4.0), + (93, "hi_attack", 0.05, 100.0, 10.0), + (94, "hi_release", 5.0, 2000.0, 150.0), + (95, "hi_speed", 0.0, 100.0, 50.0), + (96, "hi_knee", 0.0, 24.0, 6.0), + (97, "hi_knee_shape", 0.0, 100.0, 0.0), + (98, "hi_detector", 0.0, 100.0, 30.0), + (99, "hi_ff_fb", 0.0, 100.0, 0.0), + (100, "hi_gr_dist", 0.0, 100.0, 0.0), + (101, "hi_comp_mix", 0.0, 100.0, 100.0), + (102, "hi_comp_gain", -12.0, 24.0, 0.0), + (103, "hi_hp", 20.0, 2000.0, 20.0), + (104, "hi_lp", 200.0, 20000.0, 20000.0), + (105, "hi_up", 0.0, 2.0, 0.0), + (163, "hi_up_range", 0.0, 24.0, 12.0), + (120, "eq1_on", 0.0, 1.0, 1.0), + (121, "eq1_type", 0.0, 5.0, 1.0), + (122, "eq1_freq", 20.0, 20000.0, 80.0), + (123, "eq1_q", 0.1, 10.0, 0.71), + (124, "eq1_gain", -18.0, 18.0, 0.0), + (125, "eq2_on", 0.0, 1.0, 1.0), + (126, "eq2_type", 0.0, 5.0, 2.0), + (127, "eq2_freq", 20.0, 20000.0, 200.0), + (128, "eq2_q", 0.1, 10.0, 0.71), + (129, "eq2_gain", -18.0, 18.0, 0.0), + (130, "eq3_on", 0.0, 1.0, 0.0), + (131, "eq3_type", 0.0, 5.0, 2.0), + (132, "eq3_freq", 20.0, 20000.0, 1000.0), + (133, "eq3_q", 0.1, 10.0, 0.71), + (134, "eq3_gain", -18.0, 18.0, 0.0), + (135, "eq4_on", 0.0, 1.0, 0.0), + (136, "eq4_type", 0.0, 5.0, 2.0), + (137, "eq4_freq", 20.0, 20000.0, 5000.0), + (138, "eq4_q", 0.1, 10.0, 0.71), + (139, "eq4_gain", -18.0, 18.0, 0.0), + (140, "eq5_on", 0.0, 1.0, 1.0), + (141, "eq5_type", 0.0, 5.0, 1.0), + (142, "eq5_freq", 20.0, 20000.0, 10000.0), + (143, "eq5_q", 0.1, 10.0, 0.71), + (144, "eq5_gain", -18.0, 18.0, 0.0), + (145, "eq_tilt", -12.0, 12.0, 0.0), + (146, "eq_pivot", 20.0, 20000.0, 600.0), + (147, "eq_mix", 0.0, 100.0, 100.0), + (148, "eq_gain", -12.0, 12.0, 0.0), + (149, "eq_bypass", 0.0, 1.0, 0.0), + (150, "lim_on", 0.0, 1.0, 1.0), +]; + +#[derive(Params)] +pub struct SatXCompParams { + #[persist = "editor-state"] + pub editor_state: Arc, + /// Colour scheme index (see satcomp-ui palettes; >= 20 = user theme); UI-only. + #[persist = "palette-v2"] + pub palette_v2: Arc, + #[persist = "light-mode"] + pub light: Arc, + /// Spectrum fill: true = solid UI-colour area under the output, false = outline; UI-only. + #[persist = "fft-solid"] + pub fft_solid: Arc, + /// UI font index; UI-only. + #[persist = "ui-font"] + pub font: Arc, + /// Active user colour theme (`name|` + 36 hex digits) so a project keeps its look on a machine without the themes file. + #[persist = "custom-theme"] + pub custom_theme: Arc>, + #[persist = "preset-name"] + pub preset_name: Arc>, + /// Band shown on the main page (0 lo, 1 ml, 2 mh, 3 hi); UI-only. + #[persist = "sel-band"] + pub sel_band: Arc, + /// User-drawn waveshaper curve of the lo band (shaper 14); saved with the project and presets. + #[persist = "custom-curve-lo"] + pub curve_lo: Arc>>, + /// User-drawn waveshaper curve of the mid band (shaper 14); saved with the project and presets. + #[persist = "custom-curve-mid"] + pub curve_mid: Arc>>, + /// User-drawn waveshaper curve of the mh band (shaper 14); saved with the project and presets. + #[persist = "custom-curve-mh"] + pub curve_mh: Arc>>, + /// User-drawn waveshaper curve of the hi band (shaper 14); saved with the project and presets. + #[persist = "custom-curve-hi"] + pub curve_hi: Arc>>, + /// ASYM of the lo band, one value (0..100 %) per waveshaper; saved with the project and presets (absent = all 100 %). + #[persist = "asym-lo"] + pub asym_lo: Arc>>, + /// ASYM of the mid band, one value (0..100 %) per waveshaper; saved with the project and presets (absent = all 100 %). + #[persist = "asym-mid"] + pub asym_mid: Arc>>, + /// ASYM of the mh band, one value (0..100 %) per waveshaper; saved with the project and presets (absent = all 100 %). + #[persist = "asym-mh"] + pub asym_mh: Arc>>, + /// ASYM of the hi band, one value (0..100 %) per waveshaper; saved with the project and presets (absent = all 100 %). + #[persist = "asym-hi"] + pub asym_hi: Arc>>, + /// Packed waveform-scope view settings (see gui/ui/scope.rs); UI-only, saved with the project. + #[persist = "scope-v3"] + pub scope: Arc, + #[persist = "match-trim"] + pub match_trim: Arc, + #[id = "x1"] + pub x1: FloatParam, + #[id = "x2"] + pub x2: FloatParam, + #[id = "x3"] + pub x3: FloatParam, + #[id = "os"] + pub os: IntParam, + #[id = "lookahead"] + pub lookahead: FloatParam, + #[id = "mix"] + pub mix: FloatParam, + #[id = "out_gain"] + pub out_gain: FloatParam, + #[id = "gain_match"] + pub gain_match: BoolParam, + #[id = "bypass"] + pub bypass: BoolParam, + #[id = "x1_slope"] + pub x1_slope: IntParam, + #[id = "x2_slope"] + pub x2_slope: IntParam, + #[id = "x3_slope"] + pub x3_slope: IntParam, + #[id = "sc_on"] + pub sc_on: BoolParam, + #[id = "sc_gain"] + pub sc_gain: FloatParam, + #[id = "sc_hp"] + pub sc_hp: FloatParam, + #[id = "sc_lp"] + pub sc_lp: FloatParam, + #[id = "sc_mix"] + pub sc_mix: FloatParam, + #[id = "lo_on"] + pub lo_on: BoolParam, + #[id = "lo_solo"] + pub lo_solo: BoolParam, + #[id = "lo_delta"] + pub lo_delta: BoolParam, + #[id = "lo_shape"] + pub lo_shape: IntParam, + #[id = "lo_drive"] + pub lo_drive: FloatParam, + #[id = "lo_bias"] + pub lo_bias: FloatParam, + #[id = "lo_tone"] + pub lo_tone: FloatParam, + #[id = "lo_sat_mix"] + pub lo_sat_mix: FloatParam, + #[id = "lo_sat_gain"] + pub lo_sat_gain: FloatParam, + #[id = "lo_thresh"] + pub lo_thresh: FloatParam, + #[id = "lo_ratio"] + pub lo_ratio: FloatParam, + #[id = "lo_attack"] + pub lo_attack: FloatParam, + #[id = "lo_release"] + pub lo_release: FloatParam, + #[id = "lo_speed"] + pub lo_speed: FloatParam, + #[id = "lo_knee"] + pub lo_knee: FloatParam, + #[id = "lo_knee_shape"] + pub lo_knee_shape: FloatParam, + #[id = "lo_detector"] + pub lo_detector: FloatParam, + #[id = "lo_ff_fb"] + pub lo_ff_fb: FloatParam, + #[id = "lo_gr_dist"] + pub lo_gr_dist: FloatParam, + #[id = "lo_comp_mix"] + pub lo_comp_mix: FloatParam, + #[id = "lo_comp_gain"] + pub lo_comp_gain: FloatParam, + #[id = "lo_hp"] + pub lo_hp: FloatParam, + #[id = "lo_lp"] + pub lo_lp: FloatParam, + #[id = "lo_up"] + pub lo_up: IntParam, + #[id = "lo_up_range"] + pub lo_up_range: FloatParam, + #[id = "mid_on"] + pub mid_on: BoolParam, + #[id = "mid_solo"] + pub mid_solo: BoolParam, + #[id = "mid_delta"] + pub mid_delta: BoolParam, + #[id = "mid_shape"] + pub mid_shape: IntParam, + #[id = "mid_drive"] + pub mid_drive: FloatParam, + #[id = "mid_bias"] + pub mid_bias: FloatParam, + #[id = "mid_tone"] + pub mid_tone: FloatParam, + #[id = "mid_sat_mix"] + pub mid_sat_mix: FloatParam, + #[id = "mid_sat_gain"] + pub mid_sat_gain: FloatParam, + #[id = "mid_thresh"] + pub mid_thresh: FloatParam, + #[id = "mid_ratio"] + pub mid_ratio: FloatParam, + #[id = "mid_attack"] + pub mid_attack: FloatParam, + #[id = "mid_release"] + pub mid_release: FloatParam, + #[id = "mid_speed"] + pub mid_speed: FloatParam, + #[id = "mid_knee"] + pub mid_knee: FloatParam, + #[id = "mid_knee_shape"] + pub mid_knee_shape: FloatParam, + #[id = "mid_detector"] + pub mid_detector: FloatParam, + #[id = "mid_ff_fb"] + pub mid_ff_fb: FloatParam, + #[id = "mid_gr_dist"] + pub mid_gr_dist: FloatParam, + #[id = "mid_comp_mix"] + pub mid_comp_mix: FloatParam, + #[id = "mid_comp_gain"] + pub mid_comp_gain: FloatParam, + #[id = "mid_hp"] + pub mid_hp: FloatParam, + #[id = "mid_lp"] + pub mid_lp: FloatParam, + #[id = "mid_up"] + pub mid_up: IntParam, + #[id = "mid_up_range"] + pub mid_up_range: FloatParam, + #[id = "mh_on"] + pub mh_on: BoolParam, + #[id = "mh_solo"] + pub mh_solo: BoolParam, + #[id = "mh_delta"] + pub mh_delta: BoolParam, + #[id = "mh_shape"] + pub mh_shape: IntParam, + #[id = "mh_drive"] + pub mh_drive: FloatParam, + #[id = "mh_bias"] + pub mh_bias: FloatParam, + #[id = "mh_tone"] + pub mh_tone: FloatParam, + #[id = "mh_sat_mix"] + pub mh_sat_mix: FloatParam, + #[id = "mh_sat_gain"] + pub mh_sat_gain: FloatParam, + #[id = "mh_thresh"] + pub mh_thresh: FloatParam, + #[id = "mh_ratio"] + pub mh_ratio: FloatParam, + #[id = "mh_attack"] + pub mh_attack: FloatParam, + #[id = "mh_release"] + pub mh_release: FloatParam, + #[id = "mh_speed"] + pub mh_speed: FloatParam, + #[id = "mh_knee"] + pub mh_knee: FloatParam, + #[id = "mh_knee_shape"] + pub mh_knee_shape: FloatParam, + #[id = "mh_detector"] + pub mh_detector: FloatParam, + #[id = "mh_ff_fb"] + pub mh_ff_fb: FloatParam, + #[id = "mh_gr_dist"] + pub mh_gr_dist: FloatParam, + #[id = "mh_comp_mix"] + pub mh_comp_mix: FloatParam, + #[id = "mh_comp_gain"] + pub mh_comp_gain: FloatParam, + #[id = "mh_hp"] + pub mh_hp: FloatParam, + #[id = "mh_lp"] + pub mh_lp: FloatParam, + #[id = "mh_up"] + pub mh_up: IntParam, + #[id = "mh_up_range"] + pub mh_up_range: FloatParam, + #[id = "hi_on"] + pub hi_on: BoolParam, + #[id = "hi_solo"] + pub hi_solo: BoolParam, + #[id = "hi_delta"] + pub hi_delta: BoolParam, + #[id = "hi_shape"] + pub hi_shape: IntParam, + #[id = "hi_drive"] + pub hi_drive: FloatParam, + #[id = "hi_bias"] + pub hi_bias: FloatParam, + #[id = "hi_tone"] + pub hi_tone: FloatParam, + #[id = "hi_sat_mix"] + pub hi_sat_mix: FloatParam, + #[id = "hi_sat_gain"] + pub hi_sat_gain: FloatParam, + #[id = "hi_thresh"] + pub hi_thresh: FloatParam, + #[id = "hi_ratio"] + pub hi_ratio: FloatParam, + #[id = "hi_attack"] + pub hi_attack: FloatParam, + #[id = "hi_release"] + pub hi_release: FloatParam, + #[id = "hi_speed"] + pub hi_speed: FloatParam, + #[id = "hi_knee"] + pub hi_knee: FloatParam, + #[id = "hi_knee_shape"] + pub hi_knee_shape: FloatParam, + #[id = "hi_detector"] + pub hi_detector: FloatParam, + #[id = "hi_ff_fb"] + pub hi_ff_fb: FloatParam, + #[id = "hi_gr_dist"] + pub hi_gr_dist: FloatParam, + #[id = "hi_comp_mix"] + pub hi_comp_mix: FloatParam, + #[id = "hi_comp_gain"] + pub hi_comp_gain: FloatParam, + #[id = "hi_hp"] + pub hi_hp: FloatParam, + #[id = "hi_lp"] + pub hi_lp: FloatParam, + #[id = "hi_up"] + pub hi_up: IntParam, + #[id = "hi_up_range"] + pub hi_up_range: FloatParam, + #[id = "eq1_on"] + pub eq1_on: BoolParam, + #[id = "eq1_type"] + pub eq1_type: IntParam, + #[id = "eq1_freq"] + pub eq1_freq: FloatParam, + #[id = "eq1_q"] + pub eq1_q: FloatParam, + #[id = "eq1_gain"] + pub eq1_gain: FloatParam, + #[id = "eq2_on"] + pub eq2_on: BoolParam, + #[id = "eq2_type"] + pub eq2_type: IntParam, + #[id = "eq2_freq"] + pub eq2_freq: FloatParam, + #[id = "eq2_q"] + pub eq2_q: FloatParam, + #[id = "eq2_gain"] + pub eq2_gain: FloatParam, + #[id = "eq3_on"] + pub eq3_on: BoolParam, + #[id = "eq3_type"] + pub eq3_type: IntParam, + #[id = "eq3_freq"] + pub eq3_freq: FloatParam, + #[id = "eq3_q"] + pub eq3_q: FloatParam, + #[id = "eq3_gain"] + pub eq3_gain: FloatParam, + #[id = "eq4_on"] + pub eq4_on: BoolParam, + #[id = "eq4_type"] + pub eq4_type: IntParam, + #[id = "eq4_freq"] + pub eq4_freq: FloatParam, + #[id = "eq4_q"] + pub eq4_q: FloatParam, + #[id = "eq4_gain"] + pub eq4_gain: FloatParam, + #[id = "eq5_on"] + pub eq5_on: BoolParam, + #[id = "eq5_type"] + pub eq5_type: IntParam, + #[id = "eq5_freq"] + pub eq5_freq: FloatParam, + #[id = "eq5_q"] + pub eq5_q: FloatParam, + #[id = "eq5_gain"] + pub eq5_gain: FloatParam, + #[id = "eq_tilt"] + pub eq_tilt: FloatParam, + #[id = "eq_pivot"] + pub eq_pivot: FloatParam, + #[id = "eq_mix"] + pub eq_mix: FloatParam, + #[id = "eq_gain"] + pub eq_gain: FloatParam, + #[id = "eq_bypass"] + pub eq_bypass: BoolParam, + #[id = "lim_on"] + pub lim_on: BoolParam, +} + +impl Default for SatXCompParams { + /// A new instance starts from the shared defaults file (the host then restores a saved project's own look over this). + fn default() -> Self { + Self::from_defaults(satcomp_ui::appearance::load_defaults_for("satxcomp")) + } +} + +impl SatXCompParams { + pub fn from_defaults(d: Option) -> Self { + Self { + editor_state: { + let (w, h) = d.as_ref().map(|d| d.size((664.0, 400.0))).unwrap_or((830, 500)); + EguiState::from_size(w, h) + }, + palette_v2: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.pal_index()).unwrap_or(0))), + light: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.light).unwrap_or(false))), + fft_solid: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.fill_solid).unwrap_or(false))), + font: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.face_index()).unwrap_or(0))), + custom_theme: Arc::new(parking_lot::Mutex::new(d.as_ref().map(|d| d.theme.clone()).unwrap_or_default())), + preset_name: Arc::new(parking_lot::Mutex::new(String::new())), + sel_band: Arc::new(AtomicI32::new(0)), + curve_lo: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])), + curve_mid: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])), + curve_mh: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])), + curve_hi: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])), + asym_lo: Arc::new(parking_lot::Mutex::new(Vec::new())), + asym_mid: Arc::new(parking_lot::Mutex::new(Vec::new())), + asym_mh: Arc::new(parking_lot::Mutex::new(Vec::new())), + asym_hi: Arc::new(parking_lot::Mutex::new(Vec::new())), + scope: Arc::new(AtomicI32::new((5 << 4) | (2 << 8))), + match_trim: Arc::new(AtomicF32::new(0.0)), + x1: FloatParam::new("X-Over 1", 150.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + x2: FloatParam::new("X-Over 2", 800.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + x3: FloatParam::new("X-Over 3", 3500.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + os: IntParam::new("Sat Oversampling", 0, IntRange::Linear { min: 0, max: 2 }), + lookahead: FloatParam::new("Lookahead", 0.0, FloatRange::Linear { min: 0.0, max: 10.0 }).with_unit(" ms").with_step_size(0.1), + mix: FloatParam::new("Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + out_gain: FloatParam::new("Out Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + gain_match: BoolParam::new("Gain Match", false), + bypass: BoolParam::new("Bypass", false), + x1_slope: IntParam::new("X-Slope 1", 1, IntRange::Linear { min: 0, max: 3 }), + x2_slope: IntParam::new("X-Slope 2", 1, IntRange::Linear { min: 0, max: 3 }), + x3_slope: IntParam::new("X-Slope 3", 1, IntRange::Linear { min: 0, max: 3 }), + sc_on: BoolParam::new("Sidechain", false), + sc_gain: FloatParam::new("SC Gain", 0.0, FloatRange::Linear { min: -24.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + sc_hp: FloatParam::new("SC HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + sc_lp: FloatParam::new("SC LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + sc_mix: FloatParam::new("Key Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_on: BoolParam::new("Lo On", true), + lo_solo: BoolParam::new("Lo Solo", false), + lo_delta: BoolParam::new("Lo Delta", false), + lo_shape: IntParam::new("Lo Shape", 0, IntRange::Linear { min: 0, max: 14 }), + lo_drive: FloatParam::new("Lo Drive", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + lo_bias: FloatParam::new("Lo Bias", 0.0, FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + lo_tone: FloatParam::new("Lo Tone", 20000.0, FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + lo_sat_mix: FloatParam::new("Lo Sat Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_sat_gain: FloatParam::new("Lo Sat Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + lo_thresh: FloatParam::new("Lo Thresh", 0.0, FloatRange::Linear { min: -40.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + lo_ratio: FloatParam::new("Lo Ratio", 4.0, FloatRange::Linear { min: 1.0, max: 20.0 }).with_step_size(0.1), + lo_attack: FloatParam::new("Lo Attack", 10.0, FloatRange::Linear { min: 0.05, max: 100.0 }).with_unit(" ms").with_step_size(0.01), + lo_release: FloatParam::new("Lo Release", 150.0, FloatRange::Linear { min: 5.0, max: 2000.0 }).with_unit(" ms").with_step_size(1.0), + lo_speed: FloatParam::new("Lo Speed", 50.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_knee: FloatParam::new("Lo Knee", 6.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + lo_knee_shape: FloatParam::new("Lo Knee Shape", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_detector: FloatParam::new("Lo Peak>RMS", 30.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_ff_fb: FloatParam::new("Lo FF>FB", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_gr_dist: FloatParam::new("Lo GR Dist", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_comp_mix: FloatParam::new("Lo Comp Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + lo_comp_gain: FloatParam::new("Lo Comp Gain", 0.0, FloatRange::Linear { min: -12.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + lo_hp: FloatParam::new("Lo HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + lo_lp: FloatParam::new("Lo LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + lo_up: IntParam::new("Lo Comp Mode", 0, IntRange::Linear { min: 0, max: 2 }), + lo_up_range: FloatParam::new("Lo Range", 12.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + mid_on: BoolParam::new("ML On", true), + mid_solo: BoolParam::new("ML Solo", false), + mid_delta: BoolParam::new("ML Delta", false), + mid_shape: IntParam::new("ML Shape", 0, IntRange::Linear { min: 0, max: 14 }), + mid_drive: FloatParam::new("ML Drive", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + mid_bias: FloatParam::new("ML Bias", 0.0, FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + mid_tone: FloatParam::new("ML Tone", 20000.0, FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + mid_sat_mix: FloatParam::new("ML Sat Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_sat_gain: FloatParam::new("ML Sat Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + mid_thresh: FloatParam::new("ML Thresh", 0.0, FloatRange::Linear { min: -40.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + mid_ratio: FloatParam::new("ML Ratio", 4.0, FloatRange::Linear { min: 1.0, max: 20.0 }).with_step_size(0.1), + mid_attack: FloatParam::new("ML Attack", 10.0, FloatRange::Linear { min: 0.05, max: 100.0 }).with_unit(" ms").with_step_size(0.01), + mid_release: FloatParam::new("ML Release", 150.0, FloatRange::Linear { min: 5.0, max: 2000.0 }).with_unit(" ms").with_step_size(1.0), + mid_speed: FloatParam::new("ML Speed", 50.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_knee: FloatParam::new("ML Knee", 6.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + mid_knee_shape: FloatParam::new("ML Knee Shape", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_detector: FloatParam::new("ML Peak>RMS", 30.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_ff_fb: FloatParam::new("ML FF>FB", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_gr_dist: FloatParam::new("ML GR Dist", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_comp_mix: FloatParam::new("ML Comp Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mid_comp_gain: FloatParam::new("ML Comp Gain", 0.0, FloatRange::Linear { min: -12.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + mid_hp: FloatParam::new("ML HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + mid_lp: FloatParam::new("ML LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + mid_up: IntParam::new("ML Comp Mode", 0, IntRange::Linear { min: 0, max: 2 }), + mid_up_range: FloatParam::new("ML Range", 12.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + mh_on: BoolParam::new("MH On", true), + mh_solo: BoolParam::new("MH Solo", false), + mh_delta: BoolParam::new("MH Delta", false), + mh_shape: IntParam::new("MH Shape", 0, IntRange::Linear { min: 0, max: 14 }), + mh_drive: FloatParam::new("MH Drive", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + mh_bias: FloatParam::new("MH Bias", 0.0, FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + mh_tone: FloatParam::new("MH Tone", 20000.0, FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + mh_sat_mix: FloatParam::new("MH Sat Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_sat_gain: FloatParam::new("MH Sat Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + mh_thresh: FloatParam::new("MH Thresh", 0.0, FloatRange::Linear { min: -40.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + mh_ratio: FloatParam::new("MH Ratio", 4.0, FloatRange::Linear { min: 1.0, max: 20.0 }).with_step_size(0.1), + mh_attack: FloatParam::new("MH Attack", 10.0, FloatRange::Linear { min: 0.05, max: 100.0 }).with_unit(" ms").with_step_size(0.01), + mh_release: FloatParam::new("MH Release", 150.0, FloatRange::Linear { min: 5.0, max: 2000.0 }).with_unit(" ms").with_step_size(1.0), + mh_speed: FloatParam::new("MH Speed", 50.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_knee: FloatParam::new("MH Knee", 6.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + mh_knee_shape: FloatParam::new("MH Knee Shape", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_detector: FloatParam::new("MH Peak>RMS", 30.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_ff_fb: FloatParam::new("MH FF>FB", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_gr_dist: FloatParam::new("MH GR Dist", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_comp_mix: FloatParam::new("MH Comp Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + mh_comp_gain: FloatParam::new("MH Comp Gain", 0.0, FloatRange::Linear { min: -12.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + mh_hp: FloatParam::new("MH HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + mh_lp: FloatParam::new("MH LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + mh_up: IntParam::new("MH Comp Mode", 0, IntRange::Linear { min: 0, max: 2 }), + mh_up_range: FloatParam::new("MH Range", 12.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + hi_on: BoolParam::new("Hi On", true), + hi_solo: BoolParam::new("Hi Solo", false), + hi_delta: BoolParam::new("Hi Delta", false), + hi_shape: IntParam::new("Hi Shape", 0, IntRange::Linear { min: 0, max: 14 }), + hi_drive: FloatParam::new("Hi Drive", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + hi_bias: FloatParam::new("Hi Bias", 0.0, FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + hi_tone: FloatParam::new("Hi Tone", 20000.0, FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + hi_sat_mix: FloatParam::new("Hi Sat Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_sat_gain: FloatParam::new("Hi Sat Gain", 0.0, FloatRange::Linear { min: -24.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + hi_thresh: FloatParam::new("Hi Thresh", 0.0, FloatRange::Linear { min: -40.0, max: 0.0 }).with_unit(" dB").with_step_size(0.1), + hi_ratio: FloatParam::new("Hi Ratio", 4.0, FloatRange::Linear { min: 1.0, max: 20.0 }).with_step_size(0.1), + hi_attack: FloatParam::new("Hi Attack", 10.0, FloatRange::Linear { min: 0.05, max: 100.0 }).with_unit(" ms").with_step_size(0.01), + hi_release: FloatParam::new("Hi Release", 150.0, FloatRange::Linear { min: 5.0, max: 2000.0 }).with_unit(" ms").with_step_size(1.0), + hi_speed: FloatParam::new("Hi Speed", 50.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_knee: FloatParam::new("Hi Knee", 6.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + hi_knee_shape: FloatParam::new("Hi Knee Shape", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_detector: FloatParam::new("Hi Peak>RMS", 30.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_ff_fb: FloatParam::new("Hi FF>FB", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_gr_dist: FloatParam::new("Hi GR Dist", 0.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_comp_mix: FloatParam::new("Hi Comp Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + hi_comp_gain: FloatParam::new("Hi Comp Gain", 0.0, FloatRange::Linear { min: -12.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + hi_hp: FloatParam::new("Hi HP", 20.0, FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), + hi_lp: FloatParam::new("Hi LP", 20000.0, FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + hi_up: IntParam::new("Hi Comp Mode", 0, IntRange::Linear { min: 0, max: 2 }), + hi_up_range: FloatParam::new("Hi Range", 12.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), + eq1_on: BoolParam::new("EQ1 On", true), + eq1_type: IntParam::new("EQ1 Type", 1, IntRange::Linear { min: 0, max: 5 }), + eq1_freq: FloatParam::new("EQ1 Freq", 80.0, FloatRange::Linear { min: 20.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + eq1_q: FloatParam::new("EQ1 Q", 0.71, FloatRange::Linear { min: 0.1, max: 10.0 }).with_step_size(0.01), + eq1_gain: FloatParam::new("EQ1 Gain", 0.0, FloatRange::Linear { min: -18.0, max: 18.0 }).with_unit(" dB").with_step_size(0.1), + eq2_on: BoolParam::new("EQ2 On", true), + eq2_type: IntParam::new("EQ2 Type", 2, IntRange::Linear { min: 0, max: 5 }), + eq2_freq: FloatParam::new("EQ2 Freq", 200.0, FloatRange::Linear { min: 20.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + eq2_q: FloatParam::new("EQ2 Q", 0.71, FloatRange::Linear { min: 0.1, max: 10.0 }).with_step_size(0.01), + eq2_gain: FloatParam::new("EQ2 Gain", 0.0, FloatRange::Linear { min: -18.0, max: 18.0 }).with_unit(" dB").with_step_size(0.1), + eq3_on: BoolParam::new("EQ3 On", false), + eq3_type: IntParam::new("EQ3 Type", 2, IntRange::Linear { min: 0, max: 5 }), + eq3_freq: FloatParam::new("EQ3 Freq", 1000.0, FloatRange::Linear { min: 20.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + eq3_q: FloatParam::new("EQ3 Q", 0.71, FloatRange::Linear { min: 0.1, max: 10.0 }).with_step_size(0.01), + eq3_gain: FloatParam::new("EQ3 Gain", 0.0, FloatRange::Linear { min: -18.0, max: 18.0 }).with_unit(" dB").with_step_size(0.1), + eq4_on: BoolParam::new("EQ4 On", false), + eq4_type: IntParam::new("EQ4 Type", 2, IntRange::Linear { min: 0, max: 5 }), + eq4_freq: FloatParam::new("EQ4 Freq", 5000.0, FloatRange::Linear { min: 20.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + eq4_q: FloatParam::new("EQ4 Q", 0.71, FloatRange::Linear { min: 0.1, max: 10.0 }).with_step_size(0.01), + eq4_gain: FloatParam::new("EQ4 Gain", 0.0, FloatRange::Linear { min: -18.0, max: 18.0 }).with_unit(" dB").with_step_size(0.1), + eq5_on: BoolParam::new("EQ5 On", true), + eq5_type: IntParam::new("EQ5 Type", 1, IntRange::Linear { min: 0, max: 5 }), + eq5_freq: FloatParam::new("EQ5 Freq", 10000.0, FloatRange::Linear { min: 20.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + eq5_q: FloatParam::new("EQ5 Q", 0.71, FloatRange::Linear { min: 0.1, max: 10.0 }).with_step_size(0.01), + eq5_gain: FloatParam::new("EQ5 Gain", 0.0, FloatRange::Linear { min: -18.0, max: 18.0 }).with_unit(" dB").with_step_size(0.1), + eq_tilt: FloatParam::new("EQ Tilt", 0.0, FloatRange::Linear { min: -12.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + eq_pivot: FloatParam::new("EQ Pivot", 600.0, FloatRange::Linear { min: 20.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), + eq_mix: FloatParam::new("EQ Mix", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + eq_gain: FloatParam::new("EQ Gain", 0.0, FloatRange::Linear { min: -12.0, max: 12.0 }).with_unit(" dB").with_step_size(0.1), + eq_bypass: BoolParam::new("EQ Bypass", false), + lim_on: BoolParam::new("Limiter", true), + } + } +} + +impl SatXCompParams { + /// Persisted custom curve of a band (0 lo, 1 ml, 2 mh, 3 hi), sanitised. + pub fn curve_snapshot(&self, band: usize) -> Curve { + let m = [&self.curve_lo, &self.curve_mid, &self.curve_mh, &self.curve_hi][band.min(3)]; + Curve::from_points(&m.lock()) + } + + pub fn asym_cell(&self, band: usize) -> &Arc>> { + [&self.asym_lo, &self.asym_mid, &self.asym_mh, &self.asym_hi][band.min(3)] + } + + /// ASYM per shaper of a band, sanitised (short / missing = 100 %). + pub fn asym_snapshot(&self, band: usize) -> [f64; SHAPER_COUNT] { + asym_from(&self.asym_cell(band).lock()) + } + + /// Snapshot for the DSP engine (UI side: may wait briefly for the curve locks). + pub fn to_dsp(&self) -> XParams { + let a = [self.asym_snapshot(0), self.asym_snapshot(1), self.asym_snapshot(2), self.asym_snapshot(3)]; + self.to_dsp_with([self.curve_snapshot(0), self.curve_snapshot(1), self.curve_snapshot(2), self.curve_snapshot(3)], a) + } + + /// Audio-thread snapshot: never blocks on a curve lock (the previous curve is reused while the UI holds it). + pub fn to_dsp_rt(&self, last: &mut [Curve; 4], last_asym: &mut [[f64; SHAPER_COUNT]; 4]) -> XParams { + for b in 0..4 { + if let Some(g) = self.asym_cell(b).try_lock() { + last_asym[b] = asym_from(&g); + } + } + for (b, m) in [&self.curve_lo, &self.curve_mid, &self.curve_mh, &self.curve_hi].into_iter().enumerate() { + if let Some(g) = m.try_lock() { + last[b] = Curve::from_points(&g); + } + } + self.to_dsp_with(*last, *last_asym) + } + + fn to_dsp_with(&self, curves: [Curve; 4], asyms: [[f64; SHAPER_COUNT]; 4]) -> XParams { + let lo = BandParams { curve: curves[0], asym: asyms[0], on: self.lo_on.value(), solo: self.lo_solo.value(), delta: self.lo_delta.value(), shape: self.lo_shape.value(), drive: self.lo_drive.value() as f64, bias: self.lo_bias.value() as f64, tone: self.lo_tone.value() as f64, sat_mix: self.lo_sat_mix.value() as f64, sat_gain: self.lo_sat_gain.value() as f64, thresh: self.lo_thresh.value() as f64, ratio: self.lo_ratio.value() as f64, attack: self.lo_attack.value() as f64, release: self.lo_release.value() as f64, speed: self.lo_speed.value() as f64, knee: self.lo_knee.value() as f64, knee_shape: self.lo_knee_shape.value() as f64, detector: self.lo_detector.value() as f64, ff_fb: self.lo_ff_fb.value() as f64, gr_dist: self.lo_gr_dist.value() as f64, comp_mix: self.lo_comp_mix.value() as f64, comp_gain: self.lo_comp_gain.value() as f64, hp: self.lo_hp.value() as f64, lp: self.lo_lp.value() as f64, up: self.lo_up.value(), up_range: self.lo_up_range.value() as f64 }; + let mid = BandParams { curve: curves[1], asym: asyms[1], on: self.mid_on.value(), solo: self.mid_solo.value(), delta: self.mid_delta.value(), shape: self.mid_shape.value(), drive: self.mid_drive.value() as f64, bias: self.mid_bias.value() as f64, tone: self.mid_tone.value() as f64, sat_mix: self.mid_sat_mix.value() as f64, sat_gain: self.mid_sat_gain.value() as f64, thresh: self.mid_thresh.value() as f64, ratio: self.mid_ratio.value() as f64, attack: self.mid_attack.value() as f64, release: self.mid_release.value() as f64, speed: self.mid_speed.value() as f64, knee: self.mid_knee.value() as f64, knee_shape: self.mid_knee_shape.value() as f64, detector: self.mid_detector.value() as f64, ff_fb: self.mid_ff_fb.value() as f64, gr_dist: self.mid_gr_dist.value() as f64, comp_mix: self.mid_comp_mix.value() as f64, comp_gain: self.mid_comp_gain.value() as f64, hp: self.mid_hp.value() as f64, lp: self.mid_lp.value() as f64, up: self.mid_up.value(), up_range: self.mid_up_range.value() as f64 }; + let mh = BandParams { curve: curves[2], asym: asyms[2], on: self.mh_on.value(), solo: self.mh_solo.value(), delta: self.mh_delta.value(), shape: self.mh_shape.value(), drive: self.mh_drive.value() as f64, bias: self.mh_bias.value() as f64, tone: self.mh_tone.value() as f64, sat_mix: self.mh_sat_mix.value() as f64, sat_gain: self.mh_sat_gain.value() as f64, thresh: self.mh_thresh.value() as f64, ratio: self.mh_ratio.value() as f64, attack: self.mh_attack.value() as f64, release: self.mh_release.value() as f64, speed: self.mh_speed.value() as f64, knee: self.mh_knee.value() as f64, knee_shape: self.mh_knee_shape.value() as f64, detector: self.mh_detector.value() as f64, ff_fb: self.mh_ff_fb.value() as f64, gr_dist: self.mh_gr_dist.value() as f64, comp_mix: self.mh_comp_mix.value() as f64, comp_gain: self.mh_comp_gain.value() as f64, hp: self.mh_hp.value() as f64, lp: self.mh_lp.value() as f64, up: self.mh_up.value(), up_range: self.mh_up_range.value() as f64 }; + let hi = BandParams { curve: curves[3], asym: asyms[3], on: self.hi_on.value(), solo: self.hi_solo.value(), delta: self.hi_delta.value(), shape: self.hi_shape.value(), drive: self.hi_drive.value() as f64, bias: self.hi_bias.value() as f64, tone: self.hi_tone.value() as f64, sat_mix: self.hi_sat_mix.value() as f64, sat_gain: self.hi_sat_gain.value() as f64, thresh: self.hi_thresh.value() as f64, ratio: self.hi_ratio.value() as f64, attack: self.hi_attack.value() as f64, release: self.hi_release.value() as f64, speed: self.hi_speed.value() as f64, knee: self.hi_knee.value() as f64, knee_shape: self.hi_knee_shape.value() as f64, detector: self.hi_detector.value() as f64, ff_fb: self.hi_ff_fb.value() as f64, gr_dist: self.hi_gr_dist.value() as f64, comp_mix: self.hi_comp_mix.value() as f64, comp_gain: self.hi_comp_gain.value() as f64, hp: self.hi_hp.value() as f64, lp: self.hi_lp.value() as f64, up: self.hi_up.value(), up_range: self.hi_up_range.value() as f64 }; + let eq = EqParams { bands: [EqBandParams { on: self.eq1_on.value(), ty: self.eq1_type.value(), freq: self.eq1_freq.value() as f64, q: self.eq1_q.value() as f64, gain: self.eq1_gain.value() as f64 }, EqBandParams { on: self.eq2_on.value(), ty: self.eq2_type.value(), freq: self.eq2_freq.value() as f64, q: self.eq2_q.value() as f64, gain: self.eq2_gain.value() as f64 }, EqBandParams { on: self.eq3_on.value(), ty: self.eq3_type.value(), freq: self.eq3_freq.value() as f64, q: self.eq3_q.value() as f64, gain: self.eq3_gain.value() as f64 }, EqBandParams { on: self.eq4_on.value(), ty: self.eq4_type.value(), freq: self.eq4_freq.value() as f64, q: self.eq4_q.value() as f64, gain: self.eq4_gain.value() as f64 }, EqBandParams { on: self.eq5_on.value(), ty: self.eq5_type.value(), freq: self.eq5_freq.value() as f64, q: self.eq5_q.value() as f64, gain: self.eq5_gain.value() as f64 }], tilt: self.eq_tilt.value() as f64, pivot: self.eq_pivot.value() as f64, mix: self.eq_mix.value() as f64, gain: self.eq_gain.value() as f64, bypass: self.eq_bypass.value() }; + XParams { + x1: self.x1.value() as f64, x2: self.x2.value() as f64, x3: self.x3.value() as f64, x1_slope: self.x1_slope.value(), x2_slope: self.x2_slope.value(), x3_slope: self.x3_slope.value(), os: self.os.value(), lookahead_ms: self.lookahead.value() as f64, + sc_on: self.sc_on.value(), sc_gain: self.sc_gain.value() as f64, sc_hp: self.sc_hp.value() as f64, sc_lp: self.sc_lp.value() as f64, key_mix: self.sc_mix.value() as f64, + bands: [lo, mid, mh, hi], eq, mix: self.mix.value() as f64, out_gain: self.out_gain.value() as f64, + gain_match: self.gain_match.value(), bypass: self.bypass.value(), lim_on: self.lim_on.value(), + } + } + + /// Parameter by UI slot number. + pub fn ptr(&self, n: usize) -> Option { + Some(match n { + 1 => self.x1.as_ptr(), + 2 => self.x2.as_ptr(), + 9 => self.x3.as_ptr(), + 3 => self.os.as_ptr(), + 4 => self.lookahead.as_ptr(), + 5 => self.mix.as_ptr(), + 6 => self.out_gain.as_ptr(), + 7 => self.gain_match.as_ptr(), + 8 => self.bypass.as_ptr(), + 106 => self.x1_slope.as_ptr(), + 107 => self.x2_slope.as_ptr(), + 108 => self.x3_slope.as_ptr(), + 110 => self.sc_on.as_ptr(), + 111 => self.sc_gain.as_ptr(), + 112 => self.sc_hp.as_ptr(), + 113 => self.sc_lp.as_ptr(), + 114 => self.sc_mix.as_ptr(), + 10 => self.lo_on.as_ptr(), + 11 => self.lo_solo.as_ptr(), + 12 => self.lo_delta.as_ptr(), + 13 => self.lo_shape.as_ptr(), + 14 => self.lo_drive.as_ptr(), + 15 => self.lo_bias.as_ptr(), + 16 => self.lo_tone.as_ptr(), + 17 => self.lo_sat_mix.as_ptr(), + 18 => self.lo_sat_gain.as_ptr(), + 19 => self.lo_thresh.as_ptr(), + 20 => self.lo_ratio.as_ptr(), + 21 => self.lo_attack.as_ptr(), + 22 => self.lo_release.as_ptr(), + 23 => self.lo_speed.as_ptr(), + 24 => self.lo_knee.as_ptr(), + 25 => self.lo_knee_shape.as_ptr(), + 26 => self.lo_detector.as_ptr(), + 27 => self.lo_ff_fb.as_ptr(), + 28 => self.lo_gr_dist.as_ptr(), + 29 => self.lo_comp_mix.as_ptr(), + 30 => self.lo_comp_gain.as_ptr(), + 31 => self.lo_hp.as_ptr(), + 32 => self.lo_lp.as_ptr(), + 33 => self.lo_up.as_ptr(), + 160 => self.lo_up_range.as_ptr(), + 34 => self.mid_on.as_ptr(), + 35 => self.mid_solo.as_ptr(), + 36 => self.mid_delta.as_ptr(), + 37 => self.mid_shape.as_ptr(), + 38 => self.mid_drive.as_ptr(), + 39 => self.mid_bias.as_ptr(), + 40 => self.mid_tone.as_ptr(), + 41 => self.mid_sat_mix.as_ptr(), + 42 => self.mid_sat_gain.as_ptr(), + 43 => self.mid_thresh.as_ptr(), + 44 => self.mid_ratio.as_ptr(), + 45 => self.mid_attack.as_ptr(), + 46 => self.mid_release.as_ptr(), + 47 => self.mid_speed.as_ptr(), + 48 => self.mid_knee.as_ptr(), + 49 => self.mid_knee_shape.as_ptr(), + 50 => self.mid_detector.as_ptr(), + 51 => self.mid_ff_fb.as_ptr(), + 52 => self.mid_gr_dist.as_ptr(), + 53 => self.mid_comp_mix.as_ptr(), + 54 => self.mid_comp_gain.as_ptr(), + 55 => self.mid_hp.as_ptr(), + 56 => self.mid_lp.as_ptr(), + 57 => self.mid_up.as_ptr(), + 161 => self.mid_up_range.as_ptr(), + 58 => self.mh_on.as_ptr(), + 59 => self.mh_solo.as_ptr(), + 60 => self.mh_delta.as_ptr(), + 61 => self.mh_shape.as_ptr(), + 62 => self.mh_drive.as_ptr(), + 63 => self.mh_bias.as_ptr(), + 64 => self.mh_tone.as_ptr(), + 65 => self.mh_sat_mix.as_ptr(), + 66 => self.mh_sat_gain.as_ptr(), + 67 => self.mh_thresh.as_ptr(), + 68 => self.mh_ratio.as_ptr(), + 69 => self.mh_attack.as_ptr(), + 70 => self.mh_release.as_ptr(), + 71 => self.mh_speed.as_ptr(), + 72 => self.mh_knee.as_ptr(), + 73 => self.mh_knee_shape.as_ptr(), + 74 => self.mh_detector.as_ptr(), + 75 => self.mh_ff_fb.as_ptr(), + 76 => self.mh_gr_dist.as_ptr(), + 77 => self.mh_comp_mix.as_ptr(), + 78 => self.mh_comp_gain.as_ptr(), + 79 => self.mh_hp.as_ptr(), + 80 => self.mh_lp.as_ptr(), + 81 => self.mh_up.as_ptr(), + 162 => self.mh_up_range.as_ptr(), + 82 => self.hi_on.as_ptr(), + 83 => self.hi_solo.as_ptr(), + 84 => self.hi_delta.as_ptr(), + 85 => self.hi_shape.as_ptr(), + 86 => self.hi_drive.as_ptr(), + 87 => self.hi_bias.as_ptr(), + 88 => self.hi_tone.as_ptr(), + 89 => self.hi_sat_mix.as_ptr(), + 90 => self.hi_sat_gain.as_ptr(), + 91 => self.hi_thresh.as_ptr(), + 92 => self.hi_ratio.as_ptr(), + 93 => self.hi_attack.as_ptr(), + 94 => self.hi_release.as_ptr(), + 95 => self.hi_speed.as_ptr(), + 96 => self.hi_knee.as_ptr(), + 97 => self.hi_knee_shape.as_ptr(), + 98 => self.hi_detector.as_ptr(), + 99 => self.hi_ff_fb.as_ptr(), + 100 => self.hi_gr_dist.as_ptr(), + 101 => self.hi_comp_mix.as_ptr(), + 102 => self.hi_comp_gain.as_ptr(), + 103 => self.hi_hp.as_ptr(), + 104 => self.hi_lp.as_ptr(), + 105 => self.hi_up.as_ptr(), + 163 => self.hi_up_range.as_ptr(), + 120 => self.eq1_on.as_ptr(), + 121 => self.eq1_type.as_ptr(), + 122 => self.eq1_freq.as_ptr(), + 123 => self.eq1_q.as_ptr(), + 124 => self.eq1_gain.as_ptr(), + 125 => self.eq2_on.as_ptr(), + 126 => self.eq2_type.as_ptr(), + 127 => self.eq2_freq.as_ptr(), + 128 => self.eq2_q.as_ptr(), + 129 => self.eq2_gain.as_ptr(), + 130 => self.eq3_on.as_ptr(), + 131 => self.eq3_type.as_ptr(), + 132 => self.eq3_freq.as_ptr(), + 133 => self.eq3_q.as_ptr(), + 134 => self.eq3_gain.as_ptr(), + 135 => self.eq4_on.as_ptr(), + 136 => self.eq4_type.as_ptr(), + 137 => self.eq4_freq.as_ptr(), + 138 => self.eq4_q.as_ptr(), + 139 => self.eq4_gain.as_ptr(), + 140 => self.eq5_on.as_ptr(), + 141 => self.eq5_type.as_ptr(), + 142 => self.eq5_freq.as_ptr(), + 143 => self.eq5_q.as_ptr(), + 144 => self.eq5_gain.as_ptr(), + 145 => self.eq_tilt.as_ptr(), + 146 => self.eq_pivot.as_ptr(), + 147 => self.eq_mix.as_ptr(), + 148 => self.eq_gain.as_ptr(), + 149 => self.eq_bypass.as_ptr(), + 150 => self.lim_on.as_ptr(), + _ => return None, + }) + } +} + +/// Persisted per-shaper ASYM values -> the DSP array (missing / non-finite entries = 100 %, clamped to 0..100). +pub fn asym_from(v: &[f32]) -> [f64; SHAPER_COUNT] { + let mut a = [100.0; SHAPER_COUNT]; + for (d, s) in a.iter_mut().zip(v) { + if s.is_finite() { + *d = (*s as f64).clamp(0.0, 100.0); + } + } + a +} diff --git a/rust/satxcomp-plugin/src/presets.rs b/rust/satxcomp-plugin/src/presets.rs new file mode 100644 index 0000000..2cbea73 --- /dev/null +++ b/rust/satxcomp-plugin/src/presets.rs @@ -0,0 +1,256 @@ +//! Presets: JSON files of parameter values keyed by parameter id, plus the three custom waveshaper curves. +//! Factory bank = every `presets/*.json` embedded at build time (+ built-in INIT). +//! User presets = `*.satxcomp` files; the dropdown lists the user folder, "Load preset..." opens any file. + +use crate::params::TABLE; +use include_dir::{include_dir, Dir}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +static FACTORY_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/presets"); + +pub const EXT: &str = "satxcomp"; +/// Never stored in a preset: Bypass is a performance switch, Gain Match is a level-dependent measurement. +pub const EXCLUDED: [&str; 2] = ["bypass", "gain_match"]; +/// Stored when a preset is saved, but only applied when the preset has it: the sidechain switch belongs to a sidechain +/// preset (a kick-keyed one must come back keyed), yet older presets and INIT never carry it and leave the switch alone +/// (it depends on the track's routing, so INIT must not switch it off either). +pub const OPTIONAL: [&str; 1] = ["sc_on"]; + +/// The value a preset gives parameter `id`: its stored one, else the default; `None` = leave the live value alone +/// (an optional id the preset does not carry, or an excluded one). +pub fn value_for(p: &Preset, id: &str, default: f32) -> Option { + if EXCLUDED.contains(&id) { + return None; + } + match p.params.get(id) { + Some(v) => Some(*v), + None if OPTIONAL.contains(&id) => None, + None => Some(default), + } +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct Preset { + pub format: String, + pub version: u32, + pub name: String, + pub params: BTreeMap, + /// Custom waveshaper curve points of the low, mid and high band (absent / empty = all linear). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curves: Vec>, + /// ASYM (0..100 %) per waveshaper of the low, mid and high band (absent / empty = all 100 %). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asym: Vec>, +} + +impl Preset { + pub fn new(name: &str, params: BTreeMap) -> Self { + Self { format: "satxcomp-preset".into(), version: 1, name: name.into(), params, curves: Vec::new(), asym: Vec::new() } + } + + /// All defaults. + pub fn init() -> Self { + let params = TABLE.iter().filter(|e| !EXCLUDED.contains(&e.1) && !OPTIONAL.contains(&e.1)).map(|e| (e.1.to_string(), e.4)).collect(); + Self::new("INIT", params) + } + + pub fn from_json(s: &str) -> Option { + let p: Preset = serde_json::from_str(s).ok()?; + (p.format == "satxcomp-preset").then_some(p) + } + + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).unwrap_or_default() + } + + /// ASYM values of band `b` (empty slice = all 100 %). + pub fn asym(&self, b: usize) -> &[f32] { + self.asym.get(b).map(|v| &v[..]).unwrap_or(&[]) + } + + /// Curve points of band `b` (empty slice = linear). + pub fn curve(&self, b: usize) -> &[(f32, f32)] { + self.curves.get(b).map(|v| &v[..]).unwrap_or(&[]) + } +} + +pub fn factory() -> Vec { + let mut v = vec![Preset::init()]; + let mut files: Vec<_> = FACTORY_DIR + .files() + .filter(|f| f.path().extension().map(|e| e == "json").unwrap_or(false)) + .collect(); + files.sort_by_key(|f| f.path().to_path_buf()); + for f in files { + if let Some(mut p) = f.contents_utf8().and_then(Preset::from_json) { + if p.name.is_empty() { + p.name = f.path().file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + } + v.push(p); + } + } + v +} + +/// ~/Library/Application Support/SatXComp/Presets (macOS), %APPDATA%\SatXComp\Presets (Windows), ~/.config/SatXComp/Presets +pub fn user_dir() -> Option { + #[cfg(target_os = "macos")] + let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support")); + #[cfg(windows)] + let base = std::env::var_os("APPDATA").map(PathBuf::from); + #[cfg(not(any(target_os = "macos", windows)))] + let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")); + base.map(|b| b.join("SatXComp").join("Presets")) +} + +/// (display name, path) of the user presets, sorted case-insensitively. +pub fn scan_user() -> Vec<(String, PathBuf)> { + let mut v = Vec::new(); + // tests are hermetic: the machine's own user presets must not change what the editor lists (the UI golden steps through them) + if cfg!(test) { + return v; + } + if let Some(d) = user_dir() { + if let Ok(rd) = std::fs::read_dir(d) { + for e in rd.flatten() { + let p = e.path(); + if p.extension().map(|x| x == EXT).unwrap_or(false) { + if let Some(stem) = p.file_stem() { + v.push((stem.to_string_lossy().into_owned(), p)); + } + } + } + } + } + v.sort_by_key(|a| a.0.to_lowercase()); + v +} + +pub fn load_file(path: &Path) -> Option { + Preset::from_json(&std::fs::read_to_string(path).ok()?) +} + +pub fn save_file(path: &Path, p: &Preset) -> std::io::Result<()> { + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + std::fs::write(path, p.to_json()) +} + +#[cfg(any(target_os = "macos", windows))] +pub fn open_dialog() -> Option { + let mut d = rfd::FileDialog::new().add_filter("SatXComp preset", &[EXT, "json"]).set_title("Load preset"); + if let Some(u) = user_dir().filter(|u| u.exists()) { + d = d.set_directory(u); + } + d.pick_file() +} + +#[cfg(any(target_os = "macos", windows))] +pub fn save_dialog(default_name: &str) -> Option { + let mut d = rfd::FileDialog::new() + .add_filter("SatXComp preset", &[EXT]) + .set_title("Save preset") + .set_file_name(format!("{default_name}.{EXT}")); + if let Some(u) = user_dir() { + let _ = std::fs::create_dir_all(&u); + d = d.set_directory(u); + } + d.save_file().map(|p| if p.extension().is_none() { p.with_extension(EXT) } else { p }) +} + +#[cfg(not(any(target_os = "macos", windows)))] +pub fn open_dialog() -> Option { + None +} +#[cfg(not(any(target_os = "macos", windows)))] +pub fn save_dialog(_default_name: &str) -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_sidechain_switch_is_applied_only_when_the_preset_carries_it() { + let mut p = Preset::init(); + assert_eq!(value_for(&p, "sc_on", 0.0), None, "INIT / old presets leave the switch alone"); + assert_eq!(value_for(&p, "bypass", 0.0), None); + assert_eq!(value_for(&p, "lo_drive", 7.0), Some(0.0)); + p.params.remove("lo_drive"); + assert_eq!(value_for(&p, "lo_drive", 7.0), Some(7.0), "ordinary ids fall back to the default"); + p.params.insert("sc_on".into(), 1.0); + assert_eq!(value_for(&p, "sc_on", 0.0), Some(1.0)); + assert!(Preset::from_json(&p.to_json()).unwrap().params.contains_key("sc_on"), "it roundtrips"); + } + + #[test] + fn init_is_all_defaults_roundtrips_and_excludes_performance_switches() { + let p = Preset::init(); + for id in EXCLUDED { + assert!(!p.params.contains_key(id), "{id} must not be stored"); + } + assert_eq!(p.params["lo_drive"], 0.0, "init drive is 0"); + assert_eq!(p.params["mid_thresh"], 0.0, "init threshold is 0"); + for id in OPTIONAL { + assert!(!p.params.contains_key(id), "{id} is optional: INIT does not carry it"); + } + assert_eq!(p.params.len(), TABLE.len() - EXCLUDED.len() - OPTIONAL.len()); + let q = Preset::from_json(&p.to_json()).unwrap(); + assert_eq!(q.params, p.params); + assert!(Preset::from_json("{\"format\":\"satcomp-preset\"}").is_none(), "a SatComp preset is not a SatXComp preset"); + } + + #[test] + fn curves_roundtrip_and_old_presets_load_without_them() { + let mut p = Preset::init(); + assert!(!p.to_json().contains("curves"), "not written when unused"); + p.curves = vec![vec![(-1.0, -1.0), (0.0, 0.3), (1.0, 1.0)], vec![], vec![(-1.0, 0.0), (1.0, 0.5)]]; + let q = Preset::from_json(&p.to_json()).unwrap(); + assert_eq!(q.curves, p.curves); + assert_eq!(q.curve(0).len(), 3); + assert!(q.curve(1).is_empty() && q.curve(7).is_empty()); + let old = r#"{"format":"satxcomp-preset","version":1,"name":"x","params":{}}"#; + assert!(Preset::from_json(old).unwrap().curves.is_empty()); + } + + #[test] + fn asym_roundtrips_and_old_presets_load_without_it() { + let mut p = Preset::init(); + assert!(!p.to_json().contains("asym"), "not written when unused"); + p.asym = vec![vec![100.0, 40.0], vec![], vec![0.0]]; + let q = Preset::from_json(&p.to_json()).unwrap(); + assert_eq!(q.asym, p.asym); + assert_eq!(q.asym(0)[1], 40.0); + assert!(q.asym(1).is_empty() && q.asym(9).is_empty()); + let a = crate::params::asym_from(q.asym(0)); + assert_eq!((a[0], a[1], a[14]), (100.0, 40.0, 100.0)); + let old = r#"{"format":"satxcomp-preset","version":1,"name":"x","params":{}}"#; + assert!(Preset::from_json(old).unwrap().asym.is_empty()); + } + + #[test] + fn the_factory_bank_has_the_four_presets_with_known_ids_and_values_in_range() { + let f = factory(); + for want in ["DRUMS_Smiley", "DRUMS_UTubes", "Deep n Bright", "Mildly Cooked"] { + assert!(f.iter().any(|p| p.name == want), "missing factory preset {want}"); + } + for p in &f { + for (k, v) in &p.params { + let e = TABLE.iter().find(|e| e.1 == k).unwrap_or_else(|| panic!("{}: unknown id {k}", p.name)); + assert!(*v >= e.2 - 1e-3 && *v <= e.3 + 1e-3, "{}: {k} = {v} outside {}..{}", p.name, e.2, e.3); + assert!(!EXCLUDED.contains(&k.as_str()), "{}: stores {k}", p.name); + } + } + let mc = f.iter().find(|p| p.name == "Mildly Cooked").unwrap(); + assert!(!mc.curves.is_empty(), "Mildly Cooked carries its custom curves"); + } + + #[test] + fn factory_starts_with_init() { + assert_eq!(factory()[0].name, "INIT"); + } +} diff --git a/rust/satxcomp-plugin/src/standalone.rs b/rust/satxcomp-plugin/src/standalone.rs new file mode 100644 index 0000000..e64e505 --- /dev/null +++ b/rust/satxcomp-plugin/src/standalone.rs @@ -0,0 +1,3 @@ +fn main() { + nih_plug::wrapper::standalone::nih_export_standalone::(); +} diff --git a/rust/tools/gen_lparams.py b/rust/tools/gen_lparams.py new file mode 100644 index 0000000..cff4612 --- /dev/null +++ b/rust/tools/gen_lparams.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Generates satlim-plugin/src/params.rs (SatLim parameters). Run from rust/: python3 tools/gen_lparams.py + +Parameter ids are permanent once released. Slot numbers are the UI's addressing scheme; the sat module keeps SatComp's slot numbers (1-7, 25, 27, bypass 26, out gain 22) so the shared sat UI code addresses the same cells. +""" +P = [] # (slot, id, display name, kind, min, max, default, step, unit) +def add(n, i, name, kind, mn, mx, df, step=None, unit=""): + P.append((n, i, name, kind, mn, mx, df, step, unit)) + +# SAT (the SatComp saturator module) +add(1, "shape", "Shape", "int", 0, 14, 0) +add(2, "drive", "Drive", "f", 0, 100, 0, 0.1, " %") +add(3, "bias", "Bias", "f", -100, 100, 0, 0.1, " %") +add(4, "sat_hp", "Sat HP", "f", 20, 2000, 20, 1, " Hz") +add(5, "sat_lp", "Sat LP", "f", 200, 20000, 20000, 1, " Hz") +add(6, "tone", "Tone", "f", 1000, 20000, 20000, 1, " Hz") +add(7, "os", "Oversampling", "int", 0, 3, 0) # x1 x2 x4 x8: saturator and clipper +add(25, "sat_mix", "Sat Mix", "f", 0, 100, 100, 1, " %") +add(27, "sat_gain", "Sat Gain", "f", -24, 12, 0, 0.1, " dB") +# LIMITER +add(12, "lookahead", "Lookahead", "bool", 0, 1, 1) # off = zero latency, sample peak, instant attack +add(8, "ceiling", "Ceiling", "f", -24, 0, -0.3, 0.1, " dB") +add(9, "threshold", "Threshold", "f", -30, 0, 0, 0.1, " dB") +add(10, "release", "Release", "f", 15, 80, 80, 1, " ms") +add(11, "clip", "Clip", "f", 0, 100, 0, 1, " %") +add(22, "out_gain", "Out Gain", "f", -24, 12, 0, 0.1, " dB") +add(26, "bypass", "Bypass", "bool", 0, 1, 0) + +def f(x): + return repr(float(x)) + +o = [] +o.append("// GENERATED by tools/gen_lparams.py. Do not edit by hand.\n") +o.append("use nih_plug::prelude::*;\nuse nih_plug_egui::EguiState;\nuse satcomp_dsp::shapers::{asym_from, Curve, SHAPER_COUNT};\nuse satlim_dsp::LimParams;\nuse std::sync::atomic::{AtomicBool, AtomicI32};\nuse std::sync::Arc;\n") +o.append("/// Highest UI slot number + 1.\npub const SLOTS: usize = %d;\n" % (max(p[0] for p in P) + 1)) +o.append("/// (slot number, id, min, max, default) for every parameter.") +o.append("pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[") +for n, i, name, k, mn, mx, df, st, u in P: + o.append(f' ({n}, "{i}", {f(mn)}, {f(mx)}, {f(df)}),') +o.append("];\n") +o.append("#[derive(Params)]\npub struct SatLimParams {") +o.append(' #[persist = "editor-state"]\n pub editor_state: Arc,') +o.append(' /// Colour scheme index in the palette table (-1 = not set yet); UI-only, saved with the project.\n #[persist = "palette-v2"]\n pub palette_v2: Arc,') +o.append(' /// Light mode (the inverted palette of the scheme); UI-only, saved with the project.\n #[persist = "light-mode"]\n pub light: Arc,') +o.append(' /// Scope fill: true = solid UI-colour bars, false = outline stroke along the peaks; UI-only.\n #[persist = "fft-solid"]\n pub fft_solid: Arc,') +o.append(' /// UI font index (see `satcomp_ui::canvas::FONT_NAMES`); UI-only, saved with the project.\n #[persist = "ui-font"]\n pub font: Arc,') +o.append(' /// Active user colour theme (`name|` + 18 hex digits) so a project keeps its look on a machine without the themes file.\n #[persist = "custom-theme"]\n pub custom_theme: Arc>,') +o.append(' /// Packed scope view settings (see gui/ui/scope.rs); UI-only, saved with the project.\n #[persist = "scope-v3"]\n pub scope: Arc,') +o.append(' /// Name of the last loaded/saved preset (display only).\n #[persist = "preset-name"]\n pub preset_name: Arc>,') +o.append(' /// User-drawn waveshaper curve (points on [-1,1]^2, shaper 14 "Custom"); saved with the project and presets.\n #[persist = "custom-curve"]\n pub custom_curve: Arc>>,') +o.append(' /// ASYM per waveshaper (0..100 %, index = shaper); saved with the project and presets (absent = all 100 %).\n #[persist = "asym"]\n pub asym: Arc>>,') +for n, i, name, k, mn, mx, df, st, u in P: + o.append(f' #[id = "{i}"]\n pub {i}: {"IntParam" if k=="int" else "BoolParam" if k=="bool" else "FloatParam"},') +o.append("}\n") +o.append("impl Default for SatLimParams {\n fn default() -> Self {\n Self {") +o.append(" editor_state: EguiState::from_size(340, 504),") +o.append(" palette_v2: Arc::new(AtomicI32::new(-1)),") +o.append(" light: Arc::new(AtomicBool::new(false)),") +o.append(" font: Arc::new(AtomicI32::new(0)),") +o.append(" fft_solid: Arc::new(AtomicBool::new(true)),") +o.append(" scope: Arc::new(AtomicI32::new((5 << 4) | (8 << 8))),") +o.append(" custom_theme: Arc::new(parking_lot::Mutex::new(String::new())),") +o.append(" preset_name: Arc::new(parking_lot::Mutex::new(String::new())),") +o.append(" custom_curve: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])),") +o.append(" asym: Arc::new(parking_lot::Mutex::new(Vec::new())),") +for n, i, name, k, mn, mx, df, st, u in P: + if k == "int": + o.append(f' {i}: IntParam::new("{name}", {int(df)}, IntRange::Linear {{ min: {int(mn)}, max: {int(mx)} }}),') + elif k == "bool": + o.append(f' {i}: BoolParam::new("{name}", {"true" if df else "false"}),') + else: + s = f' {i}: FloatParam::new("{name}", {f(df)}, FloatRange::Linear {{ min: {f(mn)}, max: {f(mx)} }})' + if u: s += f'.with_unit("{u}")' + if st: s += f'.with_step_size({f(st)})' + o.append(s + ",") +o.append(" }\n }\n}\n") +o.append("impl SatLimParams {") +o.append(" /// Sanitised copy of the persisted custom curve (the UI holds this lock only for a point edit).\n pub fn curve_snapshot(&self) -> Curve {\n Curve::from_points(&self.custom_curve.lock())\n }\n") +o.append(" /// ASYM per shaper, sanitised (short / missing = 100 %).\n pub fn asym_snapshot(&self) -> [f64; SHAPER_COUNT] {\n asym_from(&self.asym.lock())\n }\n") +o.append(" /// Snapshot for the DSP engine (UI side: may wait briefly for the curve lock).\n pub fn to_dsp(&self) -> LimParams {\n self.to_dsp_with(self.curve_snapshot(), self.asym_snapshot())\n }\n") +o.append(" /// Audio-thread snapshot: never blocks on the curve lock. While the UI holds it the previous curve is reused.\n pub fn to_dsp_rt(&self, last: &mut Curve, last_asym: &mut [f64; SHAPER_COUNT]) -> LimParams {\n if let Some(g) = self.custom_curve.try_lock() {\n *last = Curve::from_points(&g);\n }\n if let Some(g) = self.asym.try_lock() {\n *last_asym = asym_from(&g);\n }\n self.to_dsp_with(*last, *last_asym)\n }\n") +o.append(" fn to_dsp_with(&self, curve: Curve, asym: [f64; SHAPER_COUNT]) -> LimParams {") +o.append(" LimParams {") +o.append(" shape: self.shape.value(), curve, asym, drive: self.drive.value() as f64, bias: self.bias.value() as f64,") +o.append(" sat_hp: self.sat_hp.value() as f64, sat_lp: self.sat_lp.value() as f64, tone: self.tone.value() as f64,") +o.append(" sat_mix: self.sat_mix.value() as f64, sat_gain: self.sat_gain.value() as f64, os: self.os.value(),") +o.append(" lookahead: self.lookahead.value(), ceiling: self.ceiling.value() as f64, threshold: self.threshold.value() as f64,") +o.append(" release: self.release.value() as f64, clip: self.clip.value() as f64, out_gain: self.out_gain.value() as f64,") +o.append(" bypass: self.bypass.value(),") +o.append(" }\n }\n") +o.append(" /// Parameter by slot number (UI addressing).\n pub fn ptr(&self, n: usize) -> Option {\n Some(match n {") +for n, i, *_ in P: + o.append(f" {n} => self.{i}.as_ptr(),") +o.append(" _ => return None,\n })\n }\n}") +import os +os.makedirs("satlim-plugin/src", exist_ok=True) +open("satlim-plugin/src/params.rs", "w").write("\n".join(o) + "\n") +print(len(P), "params") diff --git a/rust/tools/gen_palettes.py b/rust/tools/gen_palettes.py index 2399303..db321cd 100644 --- a/rust/tools/gen_palettes.py +++ b/rust/tools/gen_palettes.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Rewrites the PALETTES table in satcomp-plugin/src/gui/canvas.rs from docs/colorscheme.md. Run from rust/.""" +"""Rewrites the PALETTES table in satcomp-ui/src/canvas.rs from docs/colorscheme.md. Run from rust/.""" import re t = open("../docs/colorscheme.md").read() th = [] @@ -12,7 +12,7 @@ def fl(h): out += [round(int(c[i:i + 2], 16) / 255, 4) for i in (1, 3, 5)] return "[" + ", ".join("%.1f" % v if v in (0.0, 1.0) else repr(v) for v in out) + "]" rs = f"pub const PALETTES: [(&str, [f32; 9], [f32; 9]); {len(th)}] = [\n" + "".join(f' ("{n}", {fl(d)}, {fl(l)}),\n' for n, d, l in th) + "];\n" -f = "satcomp-plugin/src/gui/canvas.rs" +f = "satcomp-ui/src/canvas.rs" c = open(f).read() a = c.index("pub const PALETTES"); b = c.index("];\n", a) + 3 open(f, "w").write(c[:a] + rs + c[b:]) diff --git a/rust/tools/gen_params.py b/rust/tools/gen_params.py index 2b0a103..9b89f8a 100644 --- a/rust/tools/gen_params.py +++ b/rust/tools/gen_params.py @@ -6,13 +6,13 @@ def add(n, field, name, kind, mn, mx, df, step=None, unit=""): P.append((n, field, name, kind, mn, mx, df, step, unit)) add(1, "shape", "Shape", "int", 0, 14, 0) -add(2, "drive", "Drive", "f", 0, 100, 25, 0.1, " %") +add(2, "drive", "Drive", "f", 0, 100, 0, 0.1, " %") add(3, "bias", "Bias", "f", -100, 100, 0, 0.1, " %") add(4, "sat_hp", "Sat HP", "f", 20, 2000, 20, 1, " Hz") add(5, "sat_lp", "Sat LP", "f", 200, 20000, 20000, 1, " Hz") add(6, "tone", "Tone", "f", 1000, 20000, 20000, 1, " Hz") add(7, "os", "Oversampling", "int", 0, 2, 0) -add(8, "thresh", "Thresh", "f", -40, 0, -18, 0.1, " dB") +add(8, "thresh", "Thresh", "f", -40, 0, 0, 0.1, " dB") add(9, "ratio", "Ratio", "f", 1, 20, 4, 0.1) add(10, "attack", "Attack", "f", 0.05, 100, 10, 0.01, " ms") add(11, "release", "Release", "f", 5, 2000, 150, 1, " ms") @@ -51,6 +51,7 @@ def add(n, field, name, kind, mn, mx, df, step=None, unit=""): add(65, "sc_hp", "SC HP", "f", 20, 2000, 20, 1, " Hz") add(66, "sc_lp", "SC LP", "f", 200, 20000, 20000, 1, " Hz") add(67, "sc_mix", "Key Mix", "f", 0, 100, 100, 1, " %") +add(68, "lim_on", "Limiter", "bool", 0, 1, 1) def f(x): s = repr(float(x)) @@ -58,7 +59,7 @@ def f(x): o = [] o.append("// GENERATED by tools/gen_params.py from the JSFX slider table. Do not edit by hand.\n") -o.append("use nih_plug::prelude::*;\nuse nih_plug_egui::EguiState;\nuse satcomp_dsp::shapers::Curve;\nuse satcomp_dsp::{EqBandParams, EqStageParams};\nuse std::sync::atomic::{AtomicBool, AtomicI32};\nuse std::sync::Arc;\n") +o.append("use nih_plug::prelude::*;\nuse nih_plug_egui::EguiState;\nuse satcomp_dsp::shapers::{asym_from, Curve, SHAPER_COUNT};\nuse satcomp_dsp::{EqBandParams, EqStageParams};\nuse std::sync::atomic::{AtomicBool, AtomicI32};\nuse std::sync::Arc;\n") o.append("/// (slider number, id, min, max, default, step) for every parameter; slider numbers follow SatComp.jsfx.") o.append("pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[") for n, fl, name, k, mn, mx, df, st, u in P: @@ -69,8 +70,12 @@ def f(x): o.append(' /// Colour scheme index (0 Black, 1 White, 2.. see palette table); UI-only, saved with the project.\n #[persist = "palette"]\n pub palette: Arc,') o.append(' /// Colour scheme index in the v0.5 palette table (-1 = not set yet: migrate from the legacy `palette`); UI-only.\n #[persist = "palette-v2"]\n pub palette_v2: Arc,') o.append(' /// Light mode (the inverted palette of the scheme); UI-only, saved with the project.\n #[persist = "light-mode"]\n pub light: Arc,') +o.append(' /// UI font index (see `gui::canvas::FONT_NAMES`); UI-only, saved with the project.\n #[persist = "ui-font"]\n pub font: Arc,') +o.append(' /// Active user colour theme (`name|` + 18 hex digits) so a project keeps its look on a machine without the themes file.\n #[persist = "custom-theme"]\n pub custom_theme: Arc>,') +o.append(' /// Packed scope view settings (see gui/ui/scope.rs); UI-only, saved with the project.\n #[persist = "scope-v3"]\n pub scope: Arc,') o.append(' /// Name of the last loaded/saved preset (display only).\n #[persist = "preset-name"]\n pub preset_name: Arc>,') o.append(' /// User-drawn waveshaper curve (points on [-1,1]^2, shaper 14 "Custom"); saved with the project and presets.\n #[persist = "custom-curve"]\n pub custom_curve: Arc>>,') +o.append(' /// ASYM per waveshaper (0..100 %, index = shaper); saved with the project and presets (absent = all 100 %).\n #[persist = "asym"]\n pub asym: Arc>>,') o.append(' /// Out-stage gain-match trim (dB) written by the 3 s measurement; saved with the project.\n #[persist = "match-trim"]\n pub match_trim: Arc,') for n, fl, name, k, mn, mx, df, st, u in P: o.append(f' #[id = "{fl}"]\n pub {fl}: {"IntParam" if k=="int" else "BoolParam" if k=="bool" else "FloatParam"},') @@ -80,8 +85,12 @@ def f(x): o.append(" palette: Arc::new(AtomicI32::new(0)),") o.append(" palette_v2: Arc::new(AtomicI32::new(-1)),") o.append(" light: Arc::new(AtomicBool::new(false)),") +o.append(" font: Arc::new(AtomicI32::new(0)),") +o.append(" scope: Arc::new(AtomicI32::new((5 << 4) | (2 << 8))),") +o.append(" custom_theme: Arc::new(parking_lot::Mutex::new(String::new())),") o.append(" preset_name: Arc::new(parking_lot::Mutex::new(String::new())),") o.append(" custom_curve: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])),") +o.append(" asym: Arc::new(parking_lot::Mutex::new(Vec::new())),") o.append(" match_trim: Arc::new(AtomicF32::new(0.0)),") for n, fl, name, k, mn, mx, df, st, u in P: if k == "int": @@ -96,12 +105,15 @@ def f(x): o.append(" }\n }\n}\n") o.append("impl SatCompParams {") o.append(" /// Sanitised copy of the persisted custom curve (the UI holds this lock only for a point edit).\n pub fn curve_snapshot(&self) -> Curve {\n Curve::from_points(&self.custom_curve.lock())\n }\n") -o.append(" /// Snapshot for the DSP engine.\n pub fn to_dsp(&self) -> satcomp_dsp::Params {") +o.append(" /// ASYM per shaper, sanitised (short / missing = 100 %).\n pub fn asym_snapshot(&self) -> [f64; SHAPER_COUNT] {\n asym_from(&self.asym.lock())\n }\n") +o.append(" /// Snapshot for the DSP engine (UI side: may wait briefly for the curve lock).\n pub fn to_dsp(&self) -> satcomp_dsp::Params {\n self.to_dsp_with(self.curve_snapshot(), self.asym_snapshot())\n }\n") +o.append(" /// Audio-thread snapshot: never blocks on the curve lock. While the UI holds it the previous curve is reused.\n pub fn to_dsp_rt(&self, last: &mut satcomp_dsp::shapers::Curve, last_asym: &mut [f64; SHAPER_COUNT]) -> satcomp_dsp::Params {\n if let Some(g) = self.custom_curve.try_lock() {\n *last = satcomp_dsp::shapers::Curve::from_points(&g);\n }\n if let Some(g) = self.asym.try_lock() {\n *last_asym = asym_from(&g);\n }\n self.to_dsp_with(*last, *last_asym)\n }\n") +o.append(" fn to_dsp_with(&self, curve: satcomp_dsp::shapers::Curve, asym: [f64; SHAPER_COUNT]) -> satcomp_dsp::Params {") o.append(" let stage = |bands: [(&IntParam, &FloatParam, &FloatParam, &FloatParam); 3], tilt: &FloatParam, pivot: &FloatParam, og: &FloatParam| EqStageParams {") o.append(" bands: [0, 1, 2].map(|i| EqBandParams { ty: bands[i].0.value() as f64, freq: bands[i].1.value() as f64, gain: bands[i].2.value() as f64, q: bands[i].3.value() as f64 }),") o.append(" tilt: tilt.value() as f64, pivot: pivot.value() as f64, out_gain: og.value() as f64,\n };") o.append(" satcomp_dsp::Params {") -o.append(" shape: self.shape.value(), curve: self.curve_snapshot(), drive: self.drive.value() as f64, bias: self.bias.value() as f64,") +o.append(" shape: self.shape.value(), curve, asym, drive: self.drive.value() as f64, bias: self.bias.value() as f64,") o.append(" sat_hp: self.sat_hp.value() as f64, sat_lp: self.sat_lp.value() as f64, tone: self.tone.value() as f64, os: self.os.value(),") o.append(" thresh: self.thresh.value() as f64, ratio: self.ratio.value() as f64, attack: self.attack.value() as f64,") o.append(" release: self.release.value() as f64, speed: self.speed.value() as f64, knee: self.knee.value() as f64,") @@ -116,6 +128,7 @@ def stage_expr(sp): o.append(" lookahead_ms: self.lookahead.value() as f64, eq_pre_bypass: self.eq_pre_bypass.value(),") o.append(" eq_post_bypass: self.eq_post_bypass.value(), eq_module_bypass: self.eq_module_bypass.value(),") o.append(" sc_on: self.sc_on.value(), sc_gain: self.sc_gain.value() as f64, sc_hp: self.sc_hp.value() as f64, sc_lp: self.sc_lp.value() as f64, sc_mix: self.sc_mix.value() as f64,") +o.append(" lim_on: self.lim_on.value(),") o.append(" }\n }\n") o.append(" /// Parameter by JSFX slider number (UI addressing).\n pub fn ptr(&self, n: usize) -> Option {\n Some(match n {") for n, fl, *_ in P: diff --git a/rust/tools/gen_xparams.py b/rust/tools/gen_xparams.py new file mode 100644 index 0000000..fe27146 --- /dev/null +++ b/rust/tools/gen_xparams.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Generates satxcomp-plugin/src/params.rs (SatXComp parameters). Run from rust/: python3 tools/gen_xparams.py + +Parameter ids are permanent once released. Slot numbers are the UI's addressing scheme (like SatComp's slider numbers): +globals 1-9 (x3 is 9), band b (lo, ml, mh, hi) starts at 10 + 24*b (to 105), crossover slopes 106-108, sidechain 110-114, +EQ band i starts at 120 + 5*i, EQ globals 145-149, limiter 150, band RANGE (upward compression) 160-163 (the band's UP switch is offset 23). +""" +P = [] # (slot, id, display name, kind, min, max, default, step, unit) +def add(n, i, name, kind, mn, mx, df, step=None, unit=""): + P.append((n, i, name, kind, mn, mx, df, step, unit)) + +add(1, "x1", "X-Over 1", "f", 20, 2000, 150, 1, " Hz") +add(2, "x2", "X-Over 2", "f", 200, 20000, 800, 1, " Hz") +add(9, "x3", "X-Over 3", "f", 200, 20000, 3500, 1, " Hz") +add(3, "os", "Sat Oversampling", "int", 0, 2, 0) +add(4, "lookahead", "Lookahead", "f", 0, 10, 0, 0.1, " ms") +add(5, "mix", "Mix", "f", 0, 100, 100, 1, " %") +add(6, "out_gain", "Out Gain", "f", -24, 12, 0, 0.1, " dB") +add(7, "gain_match", "Gain Match", "bool", 0, 1, 0) +add(8, "bypass", "Bypass", "bool", 0, 1, 0) +# crossover slope per split: 0 = 12, 1 = 24, 2 = 48, 3 = 96 dB/oct (slots 106-108) +add(106, "x1_slope", "X-Slope 1", "int", 0, 3, 1) +add(107, "x2_slope", "X-Slope 2", "int", 0, 3, 1) +add(108, "x3_slope", "X-Slope 3", "int", 0, 3, 1) +# sidechain: on, key gain / HP / LP (global, applied before the key is split into bands) and KEY MIX (slots 110-114) +add(110, "sc_on", "Sidechain", "bool", 0, 1, 0) +add(111, "sc_gain", "SC Gain", "f", -24, 24, 0, 0.1, " dB") +add(112, "sc_hp", "SC HP", "f", 20, 2000, 20, 1, " Hz") +add(113, "sc_lp", "SC LP", "f", 200, 20000, 20000, 1, " Hz") +add(114, "sc_mix", "Key Mix", "f", 0, 100, 100, 1, " %") + +BANDS = [("lo", "Lo"), ("mid", "ML"), ("mh", "MH"), ("hi", "Hi")] # ids: "mid" is the low-mid band (it was the 3-band middle one) +BAND_FIELDS = [ # offset, field, name, kind, min, max, default, step, unit + (0, "on", "On", "bool", 0, 1, 1), + (1, "solo", "Solo", "bool", 0, 1, 0), + (2, "delta", "Delta", "bool", 0, 1, 0), + (3, "shape", "Shape", "int", 0, 14, 0), + (4, "drive", "Drive", "f", 0, 100, 0, 0.1, " %"), + (5, "bias", "Bias", "f", -100, 100, 0, 0.1, " %"), + (6, "tone", "Tone", "f", 1000, 20000, 20000, 1, " Hz"), + (7, "sat_mix", "Sat Mix", "f", 0, 100, 100, 1, " %"), + (8, "sat_gain", "Sat Gain", "f", -24, 12, 0, 0.1, " dB"), + (9, "thresh", "Thresh", "f", -40, 0, 0, 0.1, " dB"), + (10, "ratio", "Ratio", "f", 1, 20, 4, 0.1), + (11, "attack", "Attack", "f", 0.05, 100, 10, 0.01, " ms"), + (12, "release", "Release", "f", 5, 2000, 150, 1, " ms"), + (13, "speed", "Speed", "f", 0, 100, 50, 1, " %"), + (14, "knee", "Knee", "f", 0, 24, 6, 0.1, " dB"), + (15, "knee_shape", "Knee Shape", "f", 0, 100, 0, 1, " %"), + (16, "detector", "Peak>RMS", "f", 0, 100, 30, 1, " %"), + (17, "ff_fb", "FF>FB", "f", 0, 100, 0, 1, " %"), + (18, "gr_dist", "GR Dist", "f", 0, 100, 0, 1, " %"), + (19, "comp_mix", "Comp Mix", "f", 0, 100, 100, 1, " %"), + (20, "comp_gain", "Comp Gain", "f", -12, 24, 0, 0.1, " dB"), + (21, "hp", "HP", "f", 20, 2000, 20, 1, " Hz"), + (22, "lp", "LP", "f", 200, 20000, 20000, 1, " Hz"), + (23, "up", "Comp Mode", "int", 0, 2, 0), # 0 downward, 1 upward (lift below the threshold), 2 both + (1160, "up_range", "Range", "f", 0, 24, 12, 0.1, " dB"), # offsets >= 1000 are absolute slots: 160 + band (160-163) +] +for b, (bid, bname) in enumerate(BANDS): + for fld in BAND_FIELDS: + off, f, name, kind, mn, mx, df = fld[:7] + st = fld[7] if len(fld) > 7 else None + u = fld[8] if len(fld) > 8 else "" + slot = 10 + 24 * b + off if off < 1000 else off - 1000 + b + add(slot, f"{bid}_{f}", f"{bname} {name}", kind, mn, mx, df, st, u) + +EQ_DEF_TYPE = [1, 2, 2, 2, 1] +EQ_DEF_FREQ = [80, 200, 1000, 5000, 10000] +EQ_DEF_ON = [1, 1, 0, 0, 1] +for i in range(5): + n = 120 + 5 * i + add(n, f"eq{i+1}_on", f"EQ{i+1} On", "bool", 0, 1, EQ_DEF_ON[i]) + add(n + 1, f"eq{i+1}_type", f"EQ{i+1} Type", "int", 0, 5, EQ_DEF_TYPE[i]) + add(n + 2, f"eq{i+1}_freq", f"EQ{i+1} Freq", "f", 20, 20000, EQ_DEF_FREQ[i], 1, " Hz") + add(n + 3, f"eq{i+1}_q", f"EQ{i+1} Q", "f", 0.1, 10, 0.71, 0.01) + add(n + 4, f"eq{i+1}_gain", f"EQ{i+1} Gain", "f", -18, 18, 0, 0.1, " dB") +add(145, "eq_tilt", "EQ Tilt", "f", -12, 12, 0, 0.1, " dB") +add(146, "eq_pivot", "EQ Pivot", "f", 20, 20000, 600, 1, " Hz") +add(147, "eq_mix", "EQ Mix", "f", 0, 100, 100, 1, " %") +add(148, "eq_gain", "EQ Gain", "f", -12, 12, 0, 0.1, " dB") +add(149, "eq_bypass", "EQ Bypass", "bool", 0, 1, 0) +add(150, "lim_on", "Limiter", "bool", 0, 1, 1) + +def f(x): + return repr(float(x)) + +o = [] +o.append("// GENERATED by tools/gen_xparams.py. Do not edit by hand.\n") +o.append("use nih_plug::prelude::*;\nuse nih_plug_egui::EguiState;\nuse satcomp_dsp::shapers::Curve;\nuse satxcomp_dsp::params::SHAPER_COUNT;\nuse satxcomp_dsp::{BandParams, EqBandParams, EqParams, XParams};\nuse std::sync::atomic::{AtomicBool, AtomicI32};\nuse std::sync::Arc;\n") +o.append("/// Highest UI slot number + 1.\npub const SLOTS: usize = 164;\n") +o.append("/// (slot number, id, min, max, default) for every parameter.") +o.append("pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[") +for n, i, name, k, mn, mx, df, st, u in P: + o.append(f' ({n}, "{i}", {f(mn)}, {f(mx)}, {f(df)}),') +o.append("];\n") +o.append("#[derive(Params)]\npub struct SatXCompParams {") +o.append(' #[persist = "editor-state"]\n pub editor_state: Arc,') +o.append(' /// Colour scheme index (see satcomp-ui palettes; >= 20 = user theme); UI-only.\n #[persist = "palette-v2"]\n pub palette_v2: Arc,') +o.append(' #[persist = "light-mode"]\n pub light: Arc,') +o.append(' /// Spectrum fill: true = solid UI-colour area under the output, false = outline; UI-only.\n #[persist = "fft-solid"]\n pub fft_solid: Arc,') +o.append(' /// UI font index; UI-only.\n #[persist = "ui-font"]\n pub font: Arc,') +o.append(' /// Active user colour theme (`name|` + 36 hex digits) so a project keeps its look on a machine without the themes file.\n #[persist = "custom-theme"]\n pub custom_theme: Arc>,') +o.append(' #[persist = "preset-name"]\n pub preset_name: Arc>,') +o.append(' /// Band shown on the main page (0 lo, 1 ml, 2 mh, 3 hi); UI-only.\n #[persist = "sel-band"]\n pub sel_band: Arc,') +for bid, _ in BANDS: + o.append(f' /// User-drawn waveshaper curve of the {bid} band (shaper 14); saved with the project and presets.\n #[persist = "custom-curve-{bid}"]\n pub curve_{bid}: Arc>>,') +for bid, _ in BANDS: + o.append(f' /// ASYM of the {bid} band, one value (0..100 %) per waveshaper; saved with the project and presets (absent = all 100 %).\n #[persist = "asym-{bid}"]\n pub asym_{bid}: Arc>>,') +o.append(' /// Packed waveform-scope view settings (see gui/ui/scope.rs); UI-only, saved with the project.\n #[persist = "scope-v3"]\n pub scope: Arc,') +o.append(' #[persist = "match-trim"]\n pub match_trim: Arc,') +for n, i, name, k, mn, mx, df, st, u in P: + o.append(f' #[id = "{i}"]\n pub {i}: {"IntParam" if k=="int" else "BoolParam" if k=="bool" else "FloatParam"},') +o.append("}\n") +o.append("impl Default for SatXCompParams {\n /// A new instance starts from the shared defaults file (the host then restores a saved project's own look over this).\n fn default() -> Self {\n Self::from_defaults(satcomp_ui::appearance::load_defaults_for(\"satxcomp\"))\n }\n}\n") +o.append("impl SatXCompParams {\n pub fn from_defaults(d: Option) -> Self {\n Self {") +o.append(" editor_state: {\n let (w, h) = d.as_ref().map(|d| d.size((664.0, 400.0))).unwrap_or((830, 500));\n EguiState::from_size(w, h)\n },") +o.append(" palette_v2: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.pal_index()).unwrap_or(0))),") +o.append(" light: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.light).unwrap_or(false))),") +o.append(" fft_solid: Arc::new(AtomicBool::new(d.as_ref().map(|d| d.fill_solid).unwrap_or(false))),") +o.append(" font: Arc::new(AtomicI32::new(d.as_ref().map(|d| d.face_index()).unwrap_or(0))),") +o.append(" custom_theme: Arc::new(parking_lot::Mutex::new(d.as_ref().map(|d| d.theme.clone()).unwrap_or_default())),") +o.append(" preset_name: Arc::new(parking_lot::Mutex::new(String::new())),") +o.append(" sel_band: Arc::new(AtomicI32::new(0)),") +for bid, _ in BANDS: + o.append(f" curve_{bid}: Arc::new(parking_lot::Mutex::new(vec![(-1.0, -1.0), (1.0, 1.0)])),") +for bid, _ in BANDS: + o.append(f" asym_{bid}: Arc::new(parking_lot::Mutex::new(Vec::new())),") +o.append(" scope: Arc::new(AtomicI32::new((5 << 4) | (2 << 8))),") +o.append(" match_trim: Arc::new(AtomicF32::new(0.0)),") +for n, i, name, k, mn, mx, df, st, u in P: + if k == "int": + o.append(f' {i}: IntParam::new("{name}", {int(df)}, IntRange::Linear {{ min: {int(mn)}, max: {int(mx)} }}),') + elif k == "bool": + o.append(f' {i}: BoolParam::new("{name}", {"true" if df else "false"}),') + else: + s = f' {i}: FloatParam::new("{name}", {f(df)}, FloatRange::Linear {{ min: {f(mn)}, max: {f(mx)} }})' + if u: s += f'.with_unit("{u}")' + if st: s += f'.with_step_size({f(st)})' + o.append(s + ",") +o.append(" }\n }\n}\n") +o.append("impl SatXCompParams {") +o.append(" /// Persisted custom curve of a band (0 lo, 1 ml, 2 mh, 3 hi), sanitised.\n pub fn curve_snapshot(&self, band: usize) -> Curve {\n let m = [&self.curve_lo, &self.curve_mid, &self.curve_mh, &self.curve_hi][band.min(3)];\n Curve::from_points(&m.lock())\n }\n") +o.append(" pub fn asym_cell(&self, band: usize) -> &Arc>> {\n [&self.asym_lo, &self.asym_mid, &self.asym_mh, &self.asym_hi][band.min(3)]\n }\n") +o.append(" /// ASYM per shaper of a band, sanitised (short / missing = 100 %).\n pub fn asym_snapshot(&self, band: usize) -> [f64; SHAPER_COUNT] {\n asym_from(&self.asym_cell(band).lock())\n }\n") +o.append(" /// Snapshot for the DSP engine (UI side: may wait briefly for the curve locks).\n pub fn to_dsp(&self) -> XParams {\n let a = [self.asym_snapshot(0), self.asym_snapshot(1), self.asym_snapshot(2), self.asym_snapshot(3)];\n self.to_dsp_with([self.curve_snapshot(0), self.curve_snapshot(1), self.curve_snapshot(2), self.curve_snapshot(3)], a)\n }\n") +o.append(" /// Audio-thread snapshot: never blocks on a curve lock (the previous curve is reused while the UI holds it).\n pub fn to_dsp_rt(&self, last: &mut [Curve; 4], last_asym: &mut [[f64; SHAPER_COUNT]; 4]) -> XParams {\n for b in 0..4 {\n if let Some(g) = self.asym_cell(b).try_lock() {\n last_asym[b] = asym_from(&g);\n }\n }\n for (b, m) in [&self.curve_lo, &self.curve_mid, &self.curve_mh, &self.curve_hi].into_iter().enumerate() {\n if let Some(g) = m.try_lock() {\n last[b] = Curve::from_points(&g);\n }\n }\n self.to_dsp_with(*last, *last_asym)\n }\n") +o.append(" fn to_dsp_with(&self, curves: [Curve; 4], asyms: [[f64; SHAPER_COUNT]; 4]) -> XParams {") +for b, (bid, _) in enumerate(BANDS): + fl = ", ".join( + {"bool": f"{fld[1]}: self.{bid}_{fld[1]}.value()", + "int": f"{fld[1]}: self.{bid}_{fld[1]}.value()", + "f": f"{fld[1]}: self.{bid}_{fld[1]}.value() as f64"}[fld[3]] + for fld in BAND_FIELDS if fld[1] != "curve") + o.append(f" let {bid} = BandParams {{ curve: curves[{b}], asym: asyms[{b}], {fl} }};") +eqb = ", ".join(f"EqBandParams {{ on: self.eq{i}_on.value(), ty: self.eq{i}_type.value(), freq: self.eq{i}_freq.value() as f64, q: self.eq{i}_q.value() as f64, gain: self.eq{i}_gain.value() as f64 }}" for i in range(1, 6)) +o.append(f" let eq = EqParams {{ bands: [{eqb}], tilt: self.eq_tilt.value() as f64, pivot: self.eq_pivot.value() as f64, mix: self.eq_mix.value() as f64, gain: self.eq_gain.value() as f64, bypass: self.eq_bypass.value() }};") +o.append(" XParams {\n x1: self.x1.value() as f64, x2: self.x2.value() as f64, x3: self.x3.value() as f64, x1_slope: self.x1_slope.value(), x2_slope: self.x2_slope.value(), x3_slope: self.x3_slope.value(), os: self.os.value(), lookahead_ms: self.lookahead.value() as f64,\n sc_on: self.sc_on.value(), sc_gain: self.sc_gain.value() as f64, sc_hp: self.sc_hp.value() as f64, sc_lp: self.sc_lp.value() as f64, key_mix: self.sc_mix.value() as f64,\n bands: [lo, mid, mh, hi], eq, mix: self.mix.value() as f64, out_gain: self.out_gain.value() as f64,\n gain_match: self.gain_match.value(), bypass: self.bypass.value(), lim_on: self.lim_on.value(),\n }\n }\n") +o.append(" /// Parameter by UI slot number.\n pub fn ptr(&self, n: usize) -> Option {\n Some(match n {") +for n, i, *_ in P: + o.append(f" {n} => self.{i}.as_ptr(),") +o.append(" _ => return None,\n })\n }\n}") +o.append("\n/// Persisted per-shaper ASYM values -> the DSP array (missing / non-finite entries = 100 %, clamped to 0..100).\npub fn asym_from(v: &[f32]) -> [f64; SHAPER_COUNT] {\n let mut a = [100.0; SHAPER_COUNT];\n for (d, s) in a.iter_mut().zip(v) {\n if s.is_finite() {\n *d = (*s as f64).clamp(0.0, 100.0);\n }\n }\n a\n}") +open("satxcomp-plugin/src/params.rs", "w").write("\n".join(o) + "\n") +print(len(P), "params") diff --git a/rust/tools/wavdiff.py b/rust/tools/wavdiff.py new file mode 100644 index 0000000..f9ea39b --- /dev/null +++ b/rust/tools/wavdiff.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Null-test two WAV renders (e.g. the same loop rendered through two plug-in versions). + + python3 tools/wavdiff.py a.wav b.wav + +Reads PCM 16/24/32-bit and 32/64-bit float, any channel count. Reports the length, the peak and RMS of the +difference (in dBFS) and the sample position of the largest difference. A bit-identical render prints "IDENTICAL". +Renders must start at the same project position and use the same sample rate / bit depth; shorter file is compared +over its length. No dependencies beyond the standard library. +""" +import math +import struct +import sys + + +def read_wav(path): + data = open(path, "rb").read() + if data[:4] != b"RIFF" or data[8:12] != b"WAVE": + sys.exit(f"{path}: not a RIFF/WAVE file") + pos, fmt, pcm = 12, None, None + while pos + 8 <= len(data): + cid, size = data[pos : pos + 4], struct.unpack("= 26: # WAVE_FORMAT_EXTENSIBLE: real tag is the first GUID word + tag = struct.unpack(" peak: + peak, at = d, i + ref = max((abs(x) for x in a[:n]), default=0.0) + rms = math.sqrt(sq / max(n, 1)) + print(f"{n // cha} frames, {cha} ch, {sra} Hz ({ba}-bit vs {bb}-bit), signal peak {db(ref):.1f} dBFS") + if peak == 0.0: + print("IDENTICAL") + else: + print(f"difference: peak {db(peak):.1f} dBFS, RMS {db(rms):.1f} dBFS, largest at frame {at // cha} (ch {at % cha + 1}), {peak:.3e}") + print("(below about -140 dBFS is f32 rounding noise; 24-bit renders quantise at about -138 dBFS)") + + +main() diff --git a/rust/vendor/nih_plug_egui/src/editor.rs b/rust/vendor/nih_plug_egui/src/editor.rs index 7b28d8d..049984d 100644 --- a/rust/vendor/nih_plug_egui/src/editor.rs +++ b/rust/vendor/nih_plug_egui/src/editor.rs @@ -73,6 +73,12 @@ where let (unscaled_width, unscaled_height) = self.egui_state.size(); let scaling_factor = self.scaling_factor.load(); + // SatComp patch (Linux frame pacing): the GL swap interval, on by default as upstream. Turning it off on Linux did not cure + // the stuttering meters on X11 (owner's test, 2026-11-14), so it stays on; `SATCOMP_VSYNC=0` / `=1` forces it for experiments. + let vsync = std::env::var("SATCOMP_VSYNC").map(|v| v != "0").unwrap_or(true); + // SatComp patch: `SATCOMP_FPS=1` prints the frame rate and the average / worst frame time to stderr once a second. + let fps_log = std::env::var_os("SATCOMP_FPS").is_some(); + let mut fps = (std::time::Instant::now(), std::time::Instant::now(), 0u32, 0f32); let window = EguiWindow::open_parented( &ParentWindowHandleAdapter(parent), WindowOpenOptions { @@ -97,7 +103,7 @@ where samples: None, srgb: true, double_buffer: true, - vsync: true, + vsync, ..Default::default() }), }, @@ -106,11 +112,33 @@ where move |egui_ctx, _queue, state| build(egui_ctx, &mut state.write()), move |egui_ctx, queue, state| { let setter = ParamSetter::new(context.as_ref()); + if fps_log { + let now = std::time::Instant::now(); + let dt = now.duration_since(fps.1).as_secs_f32() * 1000.0; + fps.1 = now; + fps.2 += 1; + fps.3 = fps.3.max(dt); + if now.duration_since(fps.0).as_secs_f32() >= 1.0 { + let secs = now.duration_since(fps.0).as_secs_f32(); + eprintln!("[satcomp] {:.0} frames/s, average {:.1} ms, worst {:.1} ms, vsync {}", fps.2 as f32 / secs, secs * 1000.0 / fps.2 as f32, fps.3, vsync); + fps = (now, now, 0, 0.0); + } + } // If the window was requested to resize - if let Some(new_size) = egui_state.requested_size.swap(None) { + // SatComp patch: keep `requested_size` set while asking the host. The host answers `request_resize()` + // by calling `Editor::size()`, which returns `requested_size` if set; clearing it first made the host + // read the previous size (REAPER's FX window lagged one step behind the content). + if let Some(new_size) = egui_state.requested_size.load() { // Ask the plugin host to resize to self.size() - if context.request_resize() { + let accepted = context.request_resize(); + if accepted { + // The new size becomes the stored one before the request is cleared, so `size()` never + // reports the old value to a late host query. + egui_state.size.store(new_size); + } + egui_state.requested_size.store(None); + if accepted { // Resize the content of egui window // SatComp patch: `queue.resize` wants physical pixels, `new_size` is logical (broken on HiDPI otherwise) let ppp = egui_ctx.pixels_per_point();