diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8655a4e..6875c88 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,7 +4,7 @@ on: push: branches: [main] # 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*"] + tags: ["v*", "satxcomp-v*", "satlim-v*", "sateq-v*", "satfilt-v*"] pull_request: workflow_dispatch: @@ -39,12 +39,14 @@ jobs: satxcomp-v*) list='["satxcomp"]' ;; satlim-v*) list='["satlim"]' ;; sateq-v*) list='["sateq"]' ;; + satfilt-v*) list='["satfilt"]' ;; *) list='["satcomp"' [ -d rust/satxcomp-plugin ] && list="$list,\"satxcomp\"" [ -d rust/satlim-plugin ] && list="$list,\"satlim\"" [ -d rust/satdiff-plugin ] && list="$list,\"satdiff\"" [ -d rust/sateq-plugin ] && list="$list,\"sateq\"" + [ -d rust/satfilt-plugin ] && list="$list,\"satfilt\"" list="$list]" ;; esac @@ -89,7 +91,7 @@ jobs: run: | # 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 ;; satdiff) disp=SatDiff ;; sateq) disp=SatEQ ;; esac + case "$plugin" in satcomp) disp=SatComp ;; satxcomp) disp=SatXComp ;; satlim) disp=SatLim ;; satdiff) disp=SatDiff ;; sateq) disp=SatEQ ;; satfilt) disp=SatFilt ;; 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 @@ -102,12 +104,35 @@ jobs: 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 [ "$os" = Windows ]; then + # double-click installer: install.cmd / uninstall.cmd run install.ps1 (CRLF kept: sed leaves the line ends alone) + sed -e "s/@NAME@/${disp}/g" -e "s/@VER@/v${ver}/g" docs/install/install-windows.ps1 > dist/install.ps1 + sed -e "s/@NAME@/${disp}/g" -e "s/@VER@/v${ver}/g" docs/install/install-windows.cmd > dist/install.cmd + sed -e "s/@NAME@/${disp}/g" -e "s/@VER@/v${ver}/g" docs/install/uninstall-windows.cmd > dist/uninstall.cmd + fi + manual="docs/manual/${disp}/${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" . + - name: Installer check (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + # the zip's own installer, run for real: per-user install, every file in place, then uninstall removes them + $plugin = '${{ matrix.plugin }}' + $u = Join-Path $env:LOCALAPPDATA 'Programs\Common' + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File dist\install.ps1 -User -NoPause + if ($LASTEXITCODE -ne 0) { throw "install.ps1 exited $LASTEXITCODE" } + foreach ($t in @("$u\VST3\$plugin.vst3\Contents\x86_64-win\$plugin.vst3", "$u\CLAP\$plugin.clap")) { + if (-not (Test-Path -LiteralPath $t)) { throw "not installed: $t" } + Write-Host "ok $t" + } + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File dist\install.ps1 -User -Uninstall -NoPause + if ($LASTEXITCODE -ne 0) { throw "uninstall exited $LASTEXITCODE" } + if ((Test-Path -LiteralPath "$u\VST3\$plugin.vst3") -or (Test-Path -LiteralPath "$u\CLAP\$plugin.clap")) { throw 'uninstall left files' } + Write-Host 'installer ok' - uses: actions/upload-artifact@v4 with: name: ${{ matrix.plugin }}-${{ matrix.name }} @@ -119,7 +144,7 @@ jobs: # the joint manual PDF on its own, and a macOS installer (.pkg, all users). Built from the per-plug-in zips of the bundle job by docs/install/make-suite.sh. suite: # every build except a single-plug-in tag, so the suite files can be checked from a branch / PR run before tagging - if: ${{ !startsWith(github.ref_name, 'satxcomp-v') && !startsWith(github.ref_name, 'satlim-v') && !startsWith(github.ref_name, 'sateq-v') }} + if: ${{ !startsWith(github.ref_name, 'satxcomp-v') && !startsWith(github.ref_name, 'satlim-v') && !startsWith(github.ref_name, 'sateq-v') && !startsWith(github.ref_name, 'satfilt-v') }} needs: bundle strategy: fail-fast: false diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml index b885880..f165b94 100644 --- a/.github/workflows/release-notes.yml +++ b/.github/workflows/release-notes.yml @@ -1,7 +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. +# Tags: vX.Y.Z (SatComp / the whole-suite bundle), satxcomp-vX.Y.Z, satlim-vX.Y.Z, sateq-vX.Y.Z, satfilt-vX.Y.Z. on: push: branches: [main] diff --git a/.gitignore b/.gitignore index 967490d..d6c9659 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ docs/crashlogs/ docs/internal/ /Presets/ !docs/screenshots/*.png +!docs/screenshots/*/*.png docs/manual/.build/ docs/feedbacknotes/ wavtest/ diff --git a/Fonts/DM_Sans/OFL.txt b/Fonts/DM_Sans/OFL.txt new file mode 100755 index 0000000..14e8d9a --- /dev/null +++ b/Fonts/DM_Sans/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts) + +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/Figtree/OFL.txt b/Fonts/Figtree/OFL.txt new file mode 100644 index 0000000..61ae430 --- /dev/null +++ b/Fonts/Figtree/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Figtree Project Authors (https://github.com/erikdkennedy/figtree) + +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/Fira_Sans/OFL.txt b/Fonts/Fira_Sans/OFL.txt new file mode 100755 index 0000000..fc506b8 --- /dev/null +++ b/Fonts/Fira_Sans/OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A. + +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/Hanken_Grotesk/OFL.txt b/Fonts/Hanken_Grotesk/OFL.txt new file mode 100755 index 0000000..445b6cc --- /dev/null +++ b/Fonts/Hanken_Grotesk/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Hanken Grotesk Project Authors (https://github.com/marcologous/hanken-grotesk) + +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/Lexend/OFL.txt b/Fonts/Lexend/OFL.txt new file mode 100755 index 0000000..e9296e8 --- /dev/null +++ b/Fonts/Lexend/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Lexend Project Authors (https://github.com/googlefonts/lexend), with Reserved Font Name “RevReading Lexend”. + +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/Overpass/OFL.txt b/Fonts/Overpass/OFL.txt new file mode 100755 index 0000000..40284ee --- /dev/null +++ b/Fonts/Overpass/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Overpass Project Authors (https://github.com/RedHatOfficial/Overpass) + +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/Questrial/OFL.txt b/Fonts/Questrial/OFL.txt new file mode 100755 index 0000000..b7eaafc --- /dev/null +++ b/Fonts/Questrial/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2011 The Questrial Project Authors (https://github.com/googlefonts/questrial) + +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/README.md b/README.md index eee5e94..2436f98 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,29 @@ # SatComp -A waveshaping saturator plug-ins suite: a compressor, a 4-band compressor, a clipper-limiter and a phase diffusor. Made with bricking intentions. +![SatComp suite: SatComp, SatXComp, SatLim, SatDiff, SatEQ and SatFilt](docs/screenshots/v054/hero-cover-054.png) + +A waveshaping saturator plug-ins suite: a compressor, a 4-band compressor, a clipper-limiter, a phase diffusor, an EQ and a filter. Made with bricking intentions. | Plug-in | Version | Features | |---|---|---| -| [**SatComp**](#satcomp) | 0.5.3 | A waveshaping saturator, compressor and a 2-stage 3-band EQ | -| [**SatXComp**](#satxcomp) | 0.1.1 | A 4-band multiband compressor with a saturator per band and a 5-band EQ | -| [**SatLim**](#satlim) | 0.1.1 | A clipper and a true-peak brickwall limiter with a saturator | -| [**SatDiff**](#satdiff) | 0.1.0 | A dual waveshaping saturator with phase coloration effects | +| [**SatComp**](#satcomp) | 0.5.4 | A waveshaping saturator, compressor and a 2-stage 3-band EQ | +| [**SatXComp**](#satxcomp) | 0.1.2 | A 4-band multiband compressor with a saturator per band and a 5-band EQ | +| [**SatLim**](#satlim) | 0.2.0 | A clipper and a true-peak brickwall limiter with a saturator | +| [**SatDiff**](#satdiff) | 0.1.1 | A dual waveshaping saturator with phase coloration effects | +| [**SatEQ**](#sateq) | 0.1.0 | A 7-band EQ with a saturator and dynamics in every band, SUM + SIDE | +| [**SatFilt**](#satfilt) | 0.1.0 | A creative filter with a saturator in the loop, two scenes, color effects and four modulators each | -VST3 and CLAP for macOS (Apple silicon and Intel), Windows and Linux (experimental: see Install). Free, GPL-3.0-or-later. +VST3 and CLAP for macOS (Apple silicon and Intel), Windows and Linux (experimental: see Install). Free, GPL-3.0-or-later. Every plug-in has a help mode (click **?** in the preset bar, then point at any control) and a PDF manual (OPEN MANUAL on the About page). ## SatComp A waveshaping saturator with a compressor and a 2-stage 3-band EQ. Give the compressor more spice to squash. -![SatComp](docs/screenshots/satcomp.png) +![SatComp](docs/screenshots/v054/satcomp.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. +- **Saturator:** 17 shapers including a **Custom** one you draw yourself (pencil icon) and Ratio 2:1 / 4:1, drive, bias, ASYM (how much of the lopsided, even-order colour from BIAS is kept, without dragging 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. +- **Compressor:** three modes, DWNWARD, UPWARD (lifts quiet parts below the threshold, up to RNGE) or UP/DWN (both); 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. - **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. @@ -31,24 +35,25 @@ A waveshaping saturator with a compressor and a 2-stage 3-band EQ. Give the comp 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/screenshots/satxcomp.png) +![SatXComp](docs/screenshots/v054/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 ODD and EVEN mirror tools, band-limited so it only adds harmonics inside the band), a compressor, SOLO and DELTA, and its own SAT GAIN auto-match. +- **Per band:** a saturator (same 17 shapers, custom curves with ODD and EVEN mirror tools, 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. +- **Output limiter** (true-peak, on by default), level and frequency guides on the main view, 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 +SatLim -- **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. +- **Chain:** saturator (x1 to x8 oversampling) into a clipper, then a true-peak brickwall limiter, then OUT GAIN. The output gain is after the limiter on purpose. +- **CLIP and LIMIT** switch each stage (either, both or neither). The clip point sits -6 to +6 dB against the ceiling, and **CLIP TYPE** picks HARD CLIP, SOFT CLIP, 2:1 or 4:1 with a **KNEE**. +- **THRESHOLD** is the input level that lands on the ceiling: lowering it chews the signal deeper. **RELEASE** (5 to 500 ms, or AUTO) 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. @@ -57,33 +62,68 @@ A 2-stage clipper/limiter with a waveshaping saturator. When you need to nuke it A dual waveshaping saturator with phase colouring effects. Dedicated to sweet saturated sounds. -SatDiff +SatDiff -- **Two saturators, A and B:** each scene has its own shaper, drawable curve (up to 30 points with bendable segments), tile, drive, bias, HPF / LPF, tone and ASYM. **MORPH** blends them: a static crossfade, or a compressor-style detector that moves the blend with the input level (shape A on silence, shape B on loud peaks). +- **Two saturators, A and B:** a scene row (A | B, A>B copy, INIT) picks the one you edit; each scene has its own shaper, drawable curve (up to 30 points with bendable segments), tile, drive, bias, HPF / LPF, tone and ASYM. **MORPH** blends them: a static crossfade, or a compressor-style detector that moves the blend with the input level (shape A on silence, shape B on loud peaks). - **TILE** folds or repeats the curve so BIAS walks through copies of it. - **PHASE** rotator and a colour slot, before or after the saturators: diffusor, phaser, flanger, ring mod or frequency shifter, with COLOR MIX. - **Output:** a 24 dB per octave HPF with mid / side switches (side only is a mono sub), IN and OUT gain, a true-peak limiter, level-match on the SAT readout, plain BYPASS and eight factory presets. +## SatEQ + +A 7-band EQ where every band can saturate and compress on its own, in two sets at once: SUM (or MID) and SIDE. + +![SatEQ](docs/screenshots/v054/sateq.png) + +- **Seven bands per set:** HPF / LPF with 6 to 48 dB/oct slopes, shelves, bells, notch, band-pass and all-pass (with a WET blend). Drag nodes for frequency and gain, brackets for Q. +- **A saturator per band** with four stages: DELTA-H, DELTA and RESID add only the harmonics the band makes, and EXCITE keeps what lies above twice the band. Drive, bias, ASYM and a Custom shaper you draw yourself. +- **Dynamic bands:** downward, upward or both, with threshold, ratio, attack, release and range; keyed from the signal or the host sidechain. GR DELTA lets you hear what the dynamics take away. +- **TILT** around a pivot, curve-derived **GAIN MATCH** (never pumps), **B.SOLO**, **A | B** scenes, presets and six factory presets. +- **Spectrum viewport** with the other set hatched underneath, gain-difference shading and RMS / SLOW / MED / FAST speeds (RMS is a slow master view). + +## SatFilt + +A creative filter with a saturator in the loop. Squelch responsibly. + +SatFilt + +- **Thirteen filter families:** LADDER, K35, SVF and WARP; DUAL and TRIPLE spreads; ALLPASS, COMB and a TANK reverb; RINGMOD and FSHIFT; CRUSH and FORMANT. Drag the node for cutoff and resonance, the brackets for slope and gain. +- **A saturator in or around the filter:** before, after, inside the feedback (**LOOP**: a resonance that growls and compresses) or on only what the filter changes. Drawable curve, drive, bias, ASYM, phase rotator, wrap modes, HP / LP and SAT MIX. +- **Two scenes, A and B,** alone, in series either way or in parallel, each with its own color effect (diffusor, phaser, flanger, ring mod, frequency shifter) and **four modulators**: LFO, MIDI notes or a sidechain; FREE, SYNC or ENVELOPE; nine targets; cycles you can edit or draw. +- **Pre / post EQ** around both scenes, a safety limiter, MIDI and sidechain inputs, presets and eight factory presets. + ## Shared - **30 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. +- **Help mode:** click **?** at the end of the preset bar, then point at any control for a short description of it. +- **Fonts:** 11 mono faces, or a sans-serif mode (FONT MONO | SANS) with 7 faces and its own face for the numbers. Shift + click on the logo rolls a random colour scheme and font. +- Resizable window (100% to 250%), and a STARTUP SCALE every new instance opens at. Double-click any slider to reset it. Click the title for an About page with the signal flow, the manual, Preferences and the changelog. + +## Command line (experimental) + +`satcomp` renders audio files through any chain of the six engines, offline and headless, sample for sample the same as the plug-ins: presets by name or file, values in real units, an optional sidechain file, WAV / FLAC / MP3 / AAC in, WAV or FLAC out, a JSON summary and a null-test `diff`. It is aimed at scripts and agents. In 0.5.4 it is built from source only (`cargo build --release -p satcomp-cli`, binary in `rust/target/release/`); packaging and MIDI input come later. See [`docs/CLI.md`](docs/CLI.md). + +```bash +satcomp -i drums.wav -fx satcomp:preset=Drums_Baked thresh=-18dB -fx satlim:ceiling=-1dB -o out.wav +``` ## Install -Download from the [Releases](../../releases) page: `SatComp-Suite--.zip` holds all four plug-ins and a joint manual (macOS also has a `.pkg` installer that puts them in place for all users; the joint manual is also attached on its own). Inside are `VST3/` and `CLAP/` folders that mirror the install locations, an `INSTALL.txt` and the manual (PDF; the per-plug-in manuals are also in `docs/manual/`). Copy the bundle (`satcomp`, `satxcomp`, `satlim` or `satdiff`) to: +Download from the [Releases](../../releases) page: `SatComp-Suite--.zip` holds all six plug-ins and a joint manual (macOS also has a `.pkg` installer that puts them in place for all users; the joint manual is also attached on its own). Inside are `VST3/` and `CLAP/` folders that mirror the install locations, an `INSTALL.txt` and the manual (PDF; the per-plug-in manuals are also in `docs/manual//`). Copy the bundle (`satcomp`, `satxcomp`, `satlim`, `satdiff`, `sateq` or `satfilt`) 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\` | +**Windows:** unzip and double-click `install.cmd` (it asks for administrator permission and copies both formats into `Common Files`; `install.cmd -User` installs for you only, without admin; `uninstall.cmd` removes them). The script is not signed, so Windows may ask before running it. + **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 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//Presets` (macOS) or `%APPDATA%\\Presets` (Windows). +User presets are saved to `~/Library/Application Support//Presets` (macOS) or `%APPDATA%\\Presets` (Windows). ## Build Requires [Rust](https://rustup.rs). @@ -91,16 +131,16 @@ Requires [Rust](https://rustup.rs). ```bash cd rust cargo test -cargo xtask bundle satcomp --release # or satxcomp, satlim; this machine's architecture +cargo xtask bundle satcomp --release # or satxcomp, satlim, satdiff, sateq, satfilt; 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`). A `v*` tag releases all the plug-ins together; `satxcomp-v*` and `satlim-v*` tags release one plug-in on its own. +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*`, `satlim-v*`, `sateq-v*` and `satfilt-v*` tags release one plug-in on its own. ## Repository -- `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/`. +- `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-*`, ...). Each DSP crate also holds its parameter layer (`src/spec.rs`, generated) and preset format (`src/preset.rs`), shared with the CLI; factory presets are in each `*-dsp/presets/`. `satcomp-cli`: the command line. - `SatComp.jsfx`: the original REAPER JSFX prototype. Archival, frozen at v0.3. -- `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/`. +- `docs/`: `FOUNDATION.md` (workflow and gotchas), `INVENTORY.md` (versions and milestones), `CLI.md`, `PARAMETERS.md` (parameter reference), `SATLIM.md`, `HANDOFF.md` (JSFX-era design decisions), `TEST_CHECKLIST.md`, the manuals in `docs/manual//` (sources, PDFs; `tools/build.py` builds them), screenshots per release in `docs/screenshots//`, 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, Doto, DM Mono, Victor Mono, Anonymous Pro, Inconsolata and Courier Prime; 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 (mono mode), Hanken Grotesk, Overpass, Questrial, DM Sans, Figtree, Lexend and Fira Sans (sans mode; Fira Sans also sets the help bubbles); licences are in `Fonts/`. diff --git a/docs/CLI.md b/docs/CLI.md new file mode 100644 index 0000000..6de6d10 --- /dev/null +++ b/docs/CLI.md @@ -0,0 +1,149 @@ +# satcomp CLI: spec (debut in 0.5.4) + +A command-line renderer for the whole family: SatComp, SatXComp, SatLim, SatDiff, SatEQ and SatFilt, alone or chained, offline, headless. It is written first for agents (and scripts) that cannot listen: every run is deterministic, non-interactive and reports what it did in a form a program can read. Its output for a given input, chain and settings matches what the plug-ins render in a host at the same block size. + +Status: **experimental in 0.5.4** (decided 2026-11-28). Steps 1-5 are built and the parity suite passes (17 / 17 bit-identical against the CLAP builds); it ships as source only. Deferred to a later release: CI builds and packaging (step 6), polish (choice names still index-only for a few parameters), MIDI input for SatFilt, signing. + +## Scope of the debut + +In: +- All six plug-ins, alone or as a series chain (the order given, like an FX chain on a REAPER track). +- Settings from preset files, factory or user presets by name, and `id=value` overrides in real units. +- An optional external sidechain file for the plug-ins that take one (SatComp, SatXComp, SatEQ, SatFilt). +- Input: WAV, FLAC, MP3, AAC (`.m4a` / `.aac`). Mono or stereo, any sample rate. +- Output: WAV or FLAC. Other formats are left to tools such as ffmpeg (pipe or a second step). +- Latency compensation, an optional tail, a JSON summary, a log file and verbose console output as opt-ins. +- Discovery commands (plug-ins, parameters, presets), a dry-run check, a null-test diff and saving the chain as preset files. + +Out (for now): real-time or streaming to an audio device, more than two channels, parameter automation during a render, lossy output, and the editor-only features (SAT GAIN match, the dice, scenes switched from the UI, drawing curves). Curves and scene values that are stored in a preset are data and are honoured. + +## Command line + +One binary, `satcomp`. The default command renders, in the style of ffmpeg: + +``` +satcomp -i in.wav \ + -fx sateq -p "Air.sateq" b7_gain=+2dB \ + -fx satcomp:preset=Drums_Baked thresh=-18dB ratio=4 -sc kick.wav \ + -fx satlim:ceiling=-1dB,os=x8 \ + -o out.flac +``` + +- `-i FILE` input (`-` = stdin). `-o FILE` output (`-` = stdout, WAV). The format comes from the extension; `--format wav|flac` overrides it. +- `-fx NAME[:k=v,...]` starts the next plug-in in the chain. `NAME` is the plug-in (`satcomp`, `satxcomp`, `satlim`, `satdiff`, `sateq`, `satfilt`). +- Settings for the current `-fx` can follow inline after `:` (comma-separated) or as separate `k=v` arguments until the next `-fx` or option. +- `preset=NAME` loads a factory preset, or a user preset from the plug-in's preset folder, by name. `-p FILE` loads a preset file (`.satcomp`, `.satlim`, ... or `.json`, the plug-ins' own format), so paths with commas or spaces need no escaping. The preset is applied first, then the overrides, whatever their order on the line. +- `-sc FILE` gives the current `-fx` an external sidechain (opt-in). SatComp's and SatXComp's sidechain switch (`sc_on`) is turned on; SatEQ has no global switch, each band picks its key with `sN_bM_dyn_ext`. A mono key feeds both sides, a key shorter than the input is padded with silence, and a sample-rate mismatch is an error. Without `-sc`, a plug-in's sidechain input gets silence, as a host feeds an unrouted sidechain port: a preset with the sidechain switched on then compresses against nothing, exactly as it would in a host. +- Settings left unset take the plug-in's defaults (its INIT). Parameters that presets never store (bypass, gain match, solo and the like) can still be set explicitly. + +Options: + +| option | default | | +|---|---|---| +| `--block N` | 512 | the processing block size (output matches a host render at the same size) | +| `--tail SECONDS` | 0 | render past the end of the input (reverb tails, releases); 0 = output length = input length | +| `--bits 16\|24\|32f` | WAV / FLAC input: same depth; lossy input: 24 | output bit depth (FLAC: 16 or 24) | +| `--no-dither` | off | 16-bit output is TPDF-dithered unless this is given | +| `--start T`, `--duration T` | whole file | render a part (seconds or `mm:ss.s`) | +| `--check` | | resolve the chain and every setting, print the result, render nothing | +| `--json` | off | the run summary as JSON on stdout (see below) | +| `--log FILE` | off | the same summary plus per-plug-in detail, appended as one JSON line per run | +| `-v`, `--verbose` | off | progress and the resolved chain on stderr | +| `--save-preset DIR` | | write each plug-in's resolved settings as a preset file the plug-in loads (`DIR/01-sateq.sateq`, ...) | +| `-y` | off | overwrite the output file (otherwise an existing output is an error) | + +Other commands: + +``` +satcomp list [--json] the plug-ins and their versions +satcomp params PLUGIN [--json] every parameter: id, name, unit, range, default, step, choices +satcomp presets PLUGIN [--json] factory and user presets +satcomp diff A B [--max DB] [--json] null test: identical, or the residual peak / RMS in dBFS and the worst sample; --max exits 4 above it +satcomp --version +``` + +Without `--json` or `-v` a successful render prints nothing. Errors go to stderr as one line each, naming the plug-in, the setting and the fix where one can be guessed ("satlim: unknown parameter 'treshold' (did you mean 'threshold'?)"). + +Exit codes: 0 done; 1 bad arguments or settings; 2 input / output error; 3 the render produced non-finite samples (the output is not written); 4 `diff --max` found a residual above the limit. + +## Values + +Values are given in the parameter's own unit, the way the plug-in displays it: + +- dB: `-1`, `-1dB`, `+3dB`. Hz: `2000`, `2k`, `2kHz`. Time: `80`, `80ms`, `0.08s`. Percent: `30`, `30%`. Ratios: `4`, `4:1`. +- Choices by name, case-insensitive (`os=x8`, `shape=tube`, `b1_type=lshelf`), or by index. +- Switches: `on` / `off`, `true` / `false`, `1` / `0`. +- A plain number is in the parameter's unit. Out-of-range values are an error, not clamped (so typos surface). + +`satcomp params PLUGIN` lists the ids, units and choices; the ids are the plug-ins' parameter ids (stable, the same ids host automation and presets use). + +## Audio + +- Every plug-in runs at the file's sample rate. All of the family is stereo: a mono input is processed as identical left and right channels (what a host does with a mono item on a stereo track) and written back as mono, the mean of the two (identical for every chain, since a mono input has no side signal). +- The chain's latency (the sum of each plug-in's reported latency) is trimmed, so the output lines up with the input sample for sample. +- Decoding: WAV (PCM 8-32, float) by the CLI's own reader; FLAC, MP3 and AAC by Symphonia. Encoder delay and padding are trimmed (gapless) where the file records them: MP3 (LAME / Xing header), AAC in `.m4a` / `.mp4` (the edit list ffmpeg writes, or Apple's `iTunSMPB` tag). Raw ADTS `.aac` cannot record them, so it decodes with the encoder's priming delay at the front (about 1024-2112 samples): use `.m4a` when the timing matters. An edit list stores the length on the movie's timescale, so an `.m4a` can come out a few samples longer than its source, as in any player. +- Encoding: WAV (16, 24, 32-bit float), FLAC (16, 24). Both go through one quantiser, so a 16-bit FLAC holds exactly the samples of the 16-bit WAV. FLAC from a float source without `--bits` is 24-bit; `--bits 32f` with FLAC is an error. +- The input is decoded to 32-bit float, processed in 32-bit float (the engines compute in double internally, as in the plug-ins) and only quantised at the end. + +## Parity with the plug-ins + +The CLI and the plug-ins share one parameter layer and the same engines, so for the same settings and block size the CLI's output equals the plug-in's render. A test renders each plug-in, and a chain, both through the CLAP build (`plugbench render`) and through the CLI, and requires them to match (null below -120 dBFS; the target is bit-identical). A mismatch means one side reads a setting differently, which is a bug in the shared layer. + +Block size matters: some engines update their settings once per block or after a few blocks of settling, so a render at a different block size can differ slightly. The default 512 is a common host size; `--block` matches another. + +## JSON summary + +```json +{ + "satcomp": "0.5.4", + "input": {"path": "in.wav", "sr": 44100, "channels": 2, "seconds": 12.5, "peak_dbfs": -3.1, "true_peak_dbtp": -2.9, "lufs_i": -18.2}, + "output": {"path": "out.flac", "format": "flac", "bits": 24, "seconds": 12.5, "peak_dbfs": -1.2, "true_peak_dbtp": -1.0, "lufs_i": -9.8, "clipped_samples": 0}, + "chain": [ + {"plugin": "sateq", "version": "0.1.0", "preset": "Air.sateq", "set": {"b7_gain": "+2.0 dB"}, "latency": 0}, + {"plugin": "satcomp", "version": "0.5.4", "preset": "Drums_Baked", "set": {"thresh": "-18.0 dB", "ratio": "4.0:1"}, "sidechain": "kick.wav", "latency": 64, "gr_max_db": 7.5}, + {"plugin": "satlim", "version": "0.2.0", "set": {"ceiling": "-1.0 dB", "os": "x8"}, "latency": 160, "gr_max_db": 4.2} + ], + "latency_trimmed": 224, + "block": 512, + "render_seconds": 0.21 +} +``` + +`set` lists only what differs from the plug-in's defaults after the preset and the overrides, with values as the plug-in displays them. Meter peaks over the render, in dB (positive): `comp_gr_db`, `upward_lift_db`, `limiter_gr_db` (SatComp); `lo_gr_db` .. `hi_gr_db`, `lo_lift_db` .. `hi_lift_db`, `limiter_gr_db` (SatXComp); `clipper_gr_db`, `limiter_gr_db` (SatLim); `limiter_gr_db` (SatDiff); `dynamics_cut_db`, `dynamics_lift_db` (SatEQ, its dynamic bands). Object keys print in alphabetical order. `--check --json` prints the `chain` part without reading any audio. True peak reads within about 0.1 dB of ffmpeg's `ebur128`, on the high side; loudness within 0.05 LU. + +## Architecture + +- **Parameter layer moves into the DSP crates** (first step, all six; done before any CLI code). Each `*-dsp` crate gains a generated `spec` module: the parameter table (slot, id, name, unit, range, default, step, choices), a plain `Values` struct and `to_dsp(&Values, curves) -> Params`. The preset format (read, write, factory bank, user folder, legacy migrations) moves too, with the factory preset files. The plug-in crates keep the nih-plug parameters, the persisted UI state and the file dialogs, and build their engine settings through the same `to_dsp`. Parameter ids, slots, the preset format and saved project state do not change. +- **`satcomp-cli` crate** in the workspace: depends on the six DSP crates and the decoding / encoding crates only (no nih-plug, no egui). The binary is `satcomp`. +- **Crates:** symphonia (decoding, MPL-2.0), hound (WAV writing), a FLAC encoder (pure Rust), serde_json. All are GPL-3 compatible and need no system libraries. + +## Release + +- Versioned with the family (0.5.4). `satcomp --version` also prints each plug-in's version. +- **0.5.4: experimental, built from source** (`cargo build --release -p satcomp-cli`); announced in `docs/releases/v0.5.4.md` and the README. +- Later: built by CI for macOS (universal), Windows and Linux and shipped in the release archive next to the plug-ins (`satcomp` / `satcomp.exe`), with a manual page. + +## Build order + +1. Parameter layer into the DSP crates, one plug-in at a time, each checked by the full test suite, the UI goldens and a bit-identical CLAP render before and after. +2. CLI core: WAV in / out, one plug-in, presets and overrides, latency trim, `params` / `presets` / `list`, `--check`, exit codes. +3. Chains, sidechain, tail, partial render. +4. FLAC / MP3 / AAC input, FLAC output, dither. +5. JSON summary, log, verbose, `diff`, `--save-preset`. +6. Parity tests (CLAP vs CLI for every plug-in and a chain), CI builds, packaging, manual and release notes. + +## Open + +- **Done (step 2, 2026-11-27):** the `satcomp-cli` crate: WAV in / out, chains, sidechain, presets and overrides, discovery commands, `--check`, `--tail`, `--tempo`, exit codes (f69fcb6). `tools/cli_parity.py` renders it against the CLAP builds: 13 / 13 cases bit-identical. Getting there fixed `plugbench`'s CLAP host (fcfb3e0): it never trimmed a CLAP plug-in's latency, and it sent settings after activation instead of before, so older `plugbench render` CLAP outputs are shifted by the plug-in's latency. +- **Done (step 3 and 4, 2026-11-27):** `--start` / `--duration` (a time selection: input and keys cut, SatFilt's transport counts from the selection) and the formats (FLAC / MP3 / AAC in, FLAC out, `--format`). Checked: our FLAC decodes in ffmpeg to the WAV's exact samples and length; ffmpeg's FLAC reads back exactly; MP3 and both AAC flavours (ffmpeg's edit list, Apple's tag) line up with the source at lag 0. +- **Done (step 5, 2026-11-27):** `--json`, `--log`, `--check --json`, `diff` with `--max`, `--save-preset` (a0472c8). The save / load round trip found SatEQ's Q default off its step grid (87fb15a, fixed; the table check now rejects that). +- **SatFilt with LFO SYNC** is not in the parity suite yet: the CLI gives it a playing transport at `--tempo` from beat 0, `plugbench` gives it none. `plugbench` needs a transport before that case can be compared. +- **Presets in the parity suite:** the CLI and the editors apply presets through the same `Preset::writes` / `drawn`, but no case renders a preset against a host yet (`plugbench` cannot load preset files). + +- **Done (step 1, 2026-11-27):** the parameter layer lives in each `*-dsp` crate (`spec.rs`, `preset.rs`; 070d904..120be7b). Every plug-in renders byte-identically before and after; `Values::set` matches what the plug-in holds bit for bit (tests in each plug-in's `shared_layer_tests`). +- **SatEQ's SUM | MID** is a persisted preference, not a parameter (presets never stored it): `sateq_dsp::spec::to_dsp` takes it as an argument, and the CLI offers it as `mid_side=on|off`. +- **Choice names** exist for the oversampling, shapes, slopes, stages, families, clip types and the like. Still index-only: SatXComp's EQ types (each band has its own list of kinds), SatComp's EQ band types, SatFilt's mode class, FB tap and scene route, SatDiff's FX type / shape and morph mode. They get names before the CLI's `params` command ships. +- **SatFilt's LFO division** runs 0..20 but there are 20 division names and the engine clamps to 19, so its top value (20) plays the same as 19, the last named division. To decide: shrink the range to 0..19 (changes a frozen id's range) or add the missing division. + +- macOS signing and notarisation of the binary (a downloaded unsigned CLI is quarantined by Gatekeeper; the plug-ins have the same question). +- The other five engines' first `set_params`: they must start from the target values with no ramp from the constructor's defaults, or the first block of a render differs from a host render that ran before playback. Checked in step 1. diff --git a/docs/FOUNDATION.md b/docs/FOUNDATION.md index 0d0bce7..8c451fe 100644 --- a/docs/FOUNDATION.md +++ b/docs/FOUNDATION.md @@ -59,7 +59,11 @@ scheme menu (right-click the icon). Not verified in REAPER (clicks go through th | `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/satdiff-dsp` / `rust/satdiff-plugin` | SatDiff (alpha, unreleased, on `feature/satdiff`): `DiffEngine` (sat -> out gain -> optional true-peak limiter; rotator and diffusor follow); shell + generated `params.rs` (`tools/gen_dparams.py`); presets `*.satdiff` | +| `rust/satdiff-dsp` / `rust/satdiff-plugin` | SatDiff (released with 0.5.3): `DiffEngine` (sat -> out gain -> optional true-peak limiter; rotator and diffusor follow); shell + generated `params.rs` (`tools/gen_dparams.py`); presets `*.satdiff` | +| `rust/sateq-dsp` / `rust/sateq-plugin` | SatEQ (0.5.4): SUM / SIDE sets of 7 bands with saturator and dynamics per band; shell + generated `params.rs` | +| `rust/satfilt-dsp` / `rust/satfilt-plugin` | SatFilt (0.5.4): filter families, saturator stages, scenes, colour fx, modulators (`lfo.rs`); shell + generated `params.rs` and `satfilt-dsp/src/spec.rs` (`tools/gen_fparams.py`); presets `*.satfilt` (format version 2: DRIVE in %) | +| `rust/satcomp-cli` | the `satcomp` command line (experimental in 0.5.4, `docs/CLI.md`); `tools/cli_parity.py` checks it against the CLAP builds | +| `docs/manual//`, `docs/manual/tools/` | manual sources and PDFs; `tools/build.py` (Fira Sans, figures from `figure_specs.py`, screenshots from `docs/screenshots//`) | | `rust/tools/gen_xparams.py` / `gen_lparams.py` / `gen_dparams.py` | generate the SatXComp / SatLim / SatDiff `params.rs` (note: `gen_lparams.py` is behind the committed SatLim `params.rs`, which gained `from_defaults` by hand) | | `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` | @@ -137,7 +141,7 @@ Install for REAPER: copy the bundles to `~/Library/Audio/Plug-Ins/VST3/` and `.. `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/screenshots/*.png`, bump the crate versions, push `main`, then push the annotated tag. + `CHANGELOG`, README, this file and `docs/screenshots//*.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` @@ -275,6 +279,6 @@ Linux builds are built on a laptop (or CI, ubuntu-22.04) from `rust/`: `cargo xt **the focus-regain click is unconfirmed**: retest, and if it persists look at the UI/host param traffic on focus. - Null test against JSFX renders (REAPER offline render of sweep / noise / drum loop at fixed settings, compare with `smoothing = false`). -- Owner supplies hand-tuned presets for `rust/satcomp-plugin/presets/`. +- Owner supplies hand-tuned presets for `rust/satcomp-dsp/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 (clap-wrapper) is shelved indefinitely (owner decision 2026-11-10, no demand). diff --git a/docs/INVENTORY.md b/docs/INVENTORY.md index 39a7595..7f98274 100644 --- a/docs/INVENTORY.md +++ b/docs/INVENTORY.md @@ -4,32 +4,32 @@ Internal record of what exists, at which version, and when it got there. Update ## Plug-ins -| | SatComp | SatXComp | SatLim | SatDiff | -|---|---|---|---|---| -| Version | 0.5.3 | 0.1.1 | 0.1.1 | 0.1.0 | -| Crates | `satcomp-dsp` (shared blocks), `satcomp-plugin` | `satxcomp-dsp`, `satxcomp-plugin` | `satlim-dsp`, `satlim-plugin` | `satdiff-dsp`, `satdiff-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 | in gain > phase > colour fx (pre) > scene A / B saturators (morph) > colour fx (post) > out HPF (M/S) > out gain > true-peak limiter | -| VST3 class id | `TrtSatCompPlugin` | `thomchantraSatXC` | `thomchantraSatLm` | `thomchantraSatDf` | -| CLAP id | `com.trirat.satcomp` | `com.thomchantra.satxcomp` | `com.thomchantra.satlim` | `com.thomchantra.satdiff` | -| Bundle names | `satcomp.vst3` / `.clap` | `satxcomp.vst3` / `.clap` | `satlim.vst3` / `.clap` | `satdiff.vst3` / `.clap` | -| Preset extension / folder | `.satcomp`, `SatComp/Presets` | `.satxcomp`, `SatXComp/Presets` | `.satlim`, `SatLim/Presets` | `.satdiff`, `SatDiff/Presets` | -| Factory presets | 6 (Drums_*) | 4 | 6 | 8 | -| Window (logical, base) | 560 x 336 | 664 x 400 | 340 x 496 | 316 x 556 | -| Latency | constant ~2.2 ms at 48 kHz, reported | constant, reported | saturator + clipper oversamplers + lookahead, reported; changes with x1-x8 and L.AHEAD | reported; follows the oversampling (a tile forces x4) | -| Docs | `PARAMETERS.md` (JSFX era), `FOUNDATION.md` | `FOUNDATION.md` | `SATLIM.md` | manual only | - -Shared: `satcomp-ui` (canvas, 30 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). +| | SatComp | SatXComp | SatLim | SatDiff | SatEQ | SatFilt | +|---|---|---|---|---|---|---| +| Version | 0.5.4 | 0.1.2 | 0.2.0 | 0.1.1 | 0.1.0 | 0.1.0 | +| Crates | `satcomp-dsp` (shared blocks), `satcomp-plugin` | `satxcomp-dsp`, `satxcomp-plugin` | `satlim-dsp`, `satlim-plugin` | `satdiff-dsp`, `satdiff-plugin` | `sateq-dsp`, `sateq-plugin` | `satfilt-dsp`, `satfilt-plugin` | +| Chain | saturator, compressor (down / up / both), 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 (CLIP switch, type, knee, level) > true-peak limiter (LIMIT switch) > out gain | in gain > phase > colour fx (pre) > scene A / B saturators (morph) > colour fx (post) > out HPF (M/S) > out gain > true-peak limiter | SUM / SIDE sets of 7 bands, each filter + saturator (4 stages) + dynamics, tilt, gain match, sidechain | pre EQ > scenes A / B (phase > colour pre > filter + saturator > colour post, 4 modulators each) routed > post EQ > mix > out gain > limiter; sidechain + MIDI in | +| VST3 class id | `TrtSatCompPlugin` | `thomchantraSatXC` | `thomchantraSatLm` | `thomchantraSatDf` | `thomchantraSatEQ` | `thomchantraSatFl` | +| CLAP id | `com.trirat.satcomp` | `com.thomchantra.satxcomp` | `com.thomchantra.satlim` | `com.thomchantra.satdiff` | `com.thomchantra.sateq` | `com.thomchantra.satfilt` | +| Bundle names | `satcomp.vst3` / `.clap` | `satxcomp.vst3` / `.clap` | `satlim.vst3` / `.clap` | `satdiff.vst3` / `.clap` | `sateq.vst3` / `.clap` | `satfilt.vst3` / `.clap` | +| Preset extension / folder | `.satcomp`, `SatComp/Presets` | `.satxcomp`, `SatXComp/Presets` | `.satlim`, `SatLim/Presets` | `.satdiff`, `SatDiff/Presets` | `.sateq`, `SatEQ/Presets` | `.satfilt`, `SatFilt/Presets` | +| Factory presets | 6 (Drums_*) | 4 | 6 | 8 | 6 | 8 | +| Window (logical, base) | 560 x 336 | 664 x 400 | 340 x 504 | 316 x 578 | 790 x 324 | 420 x 549 | +| Latency | constant ~2.2 ms at 48 kHz, reported | constant, reported | saturator + clipper oversamplers + lookahead, reported; changes with x1-x8 and L.AHEAD | reported; follows the oversampling (a tile forces x4) | reported; follows the oversampling | reported; follows the oversampling actually running (some families and the wrap modes raise it) | +| Docs | `PARAMETERS.md` (JSFX era), `FOUNDATION.md` | `FOUNDATION.md` | `SATLIM.md` | manual only | manual only | manual only; design spec in `docs/internal/` | + +Shared: `satcomp-ui` (canvas, 30 palettes, 18 embedded fonts (11 mono, 7 sans, Fira Sans also for the help bubbles), FFT, widget kit, help overlay, 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). -**Released with 0.5.3:** SatDiff 0.1.0 (A/B waveshaper saturator with morph, phase rotator, colour fx). The whole-suite release also attaches `SatComp-Suite--.zip` (and a macOS `.pkg`), built by `docs/install/make-suite.sh` in CI. +**Released with 0.5.4:** SatEQ 0.1.0 and SatFilt 0.1.0 join; the four older plug-ins gain the help overlay, sans font mode, startup scale, Ratio shapers and one ASYM. The whole-suite release also attaches `SatComp-Suite--.zip` (and a macOS `.pkg`), built by `docs/install/make-suite.sh` in CI. -**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). +**CLI (experimental in 0.5.4):** `satcomp-cli` (binary `satcomp`, `docs/CLI.md`) renders audio files through any chain of the six engines, bit-identical to the plug-ins. Built from source only; packaging, polish and MIDI input are deferred. 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. +- `v*` tag: bundle release of everything that changed (0.5.2 is the first bundle). `satxcomp-v*`, `satlim-v*`, `sateq-v*`, `satfilt-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. +- Manuals: `docs/manual//.md` is the source, `python3 docs/manual/tools/build.py` writes `/-Manual-v.pdf` (hero screenshots from `docs/screenshots//`, set in `tools/figure_specs.py`) (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`. @@ -45,26 +45,40 @@ Shared: `satcomp-ui` (canvas, 30 palettes, 11 embedded fonts, FFT, widget kit, A | 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.3 | 2026-11-17 | adjustable compressor plot, 20-point draw view + EVEN, hover on switches, header lockup, CPU work, Linux fixes | +| v0.5.4 | 2026-11-28 | compressor modes (DWNWARD / UPWARD / UP/DWN), Ratio 2:1 and 4:1 shapers, one global ASYM, help overlay, sans font mode, startup scale | | 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.2 | 2026-11-28 | 0.5.4: Ratio shapers, ASYM per band, main-view guides, help overlay | | 0.1.1 | 2026-11-17 | 0.5.3: 20-point draw view, UI pass, CPU 1.9 -> 0.6 % at defaults | | 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 | ### SatDiff | Version | Date | Milestone | |---|---|---| +| 0.1.1 | 2026-11-28 | 0.5.4: scene row (A \| B, copy, init, oversampling), Ratio shapers, ASYM per scene, scope fix, help overlay | | 0.1.0 | 2026-11-17 | debut with 0.5.3: A/B saturator scenes and MORPH, 30-point curves, TILE, phase rotator, five colour fx, out HPF (M/S), limiter, 8 factory presets, manual | ### SatLim | Version | Date | Milestone | |---|---|---| +| 0.2.0 | 2026-11-28 | 0.5.4: clipper / limiter section (CLIP and LIMIT switches, clip types with KNEE, clip level), release 5-500 ms + AUTO, Ratio shapers, ASYM; the old CLIP % is gone (presets fold it into THRESHOLD) | | 0.1.1 | 2026-11-17 | 0.5.3: 20-point draw view, UI pass | | 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 | +### SatEQ +| Version | Date | Milestone | +|---|---|---| +| 0.1.0 | 2026-11-28 | debut with 0.5.4: SUM + SIDE sets of 7 bands, saturator per band (DELTA-H / DELTA / RESID / EXCITE), dynamic bands with sidechain, tilt, curve-derived GAIN MATCH, B.SOLO, A \| B, 6 factory presets, manual | + +### SatFilt +| Version | Date | Milestone | +|---|---|---| +| 0.1.0 | 2026-11-28 | debut with 0.5.4: 13 filter families, saturator in or around the loop (6 stages), A / B scenes with routing, colour fx and 4 modulators per scene (LFO / MIDI / sidechain, drawable cycles), pre / post EQ, 8 factory presets, manual | + ## Key milestones (project timeline) | Date | Event | |---|---| @@ -74,6 +88,9 @@ Shared: `satcomp-ui` (canvas, 30 palettes, 11 embedded fonts, FFT, widget kit, A | 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 | +| 2026-11-17 | v0.5.3 released with SatDiff 0.1.0 | +| 2026-11-27 | parameter layer moved into the DSP crates; `satcomp` CLI renders bit-identical to the CLAP builds | +| 2026-11-28 | SatEQ and SatFilt complete; help overlay family-wide; manuals per plug-in with annotated v0.5.4 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. @@ -83,6 +100,6 @@ Shared: `satcomp-ui` (canvas, 30 palettes, 11 embedded fonts, FFT, widget kit, A ## 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. +3. About copy (`docs/abouttextcopy.md`) and README updated; screenshots re-shot into `docs/screenshots//` if the UI changed, `figure_specs.SHOTS` pointed at them and the manuals rebuilt. 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/MULTI_INSTANCE.md b/docs/MULTI_INSTANCE.md new file mode 100644 index 0000000..24eafc6 --- /dev/null +++ b/docs/MULTI_INSTANCE.md @@ -0,0 +1,92 @@ +# Multi-instance audit (0.5.4, 2026-11-27) + +How the six plug-ins behave when a session holds many of them: audio CPU as instances and threads grow, memory, creation and teardown, and the cost of open editors. Measured on feature/0.5.4 (after 39b30d0) on an Apple M4 (4 performance + 6 efficiency cores, 16 GB), CLAP release builds, 44.1 kHz, 512-sample blocks unless noted, a drum loop (`wavtest/cw_amen09_175.wav`). + +**Verdict: nothing blocks the release.** Instances share no mutable state, cost per instance does not grow with the count, nothing leaks. One real bug was found and fixed (SatFilt's editor recomputed its response curve on every frame, 3f61838). One startup cost is left as an option (SatEQ creation, below). + +## Shared state + +Every crate was searched for process-wide statics (`static`, `OnceLock`, `lazy_static`, `thread_local!`). The only one is SatFilt's read-only reference noise (`satfilt-dsp/src/core.rs`, built once, never written). Instances cannot affect each other, so the engines are safe to run on any number of threads at once. + +With the editor closed, SatComp, SatXComp, SatEQ and SatFilt stop feeding their analysis taps (300 ms after the last frame). SatLim and SatDiff publish a few meter scalars per block and SatLim one scope value per 2 ms: negligible. Closed editors cost nothing on the audio thread. + +## Audio CPU + +CPU per instance per block, median, as instances and threads grow (`x` = relative to one instance on one thread). Defaults and a heavy setting per plug-in. + +| plug-in | setting | 1 inst, 1 thread (us) | 64 inst, 1 thread | 64 inst, 4 threads | 64 inst, 8 threads | offline speed, one core | +|---|---|---|---|---|---|---| +| SatComp | defaults | 21 | x1.0 | x0.9 | x1.1 | 550x real time | +| SatComp | drive 30 %, x4 | 105 | x1.0 | x1.35 | x1.4 | 110x | +| SatXComp | defaults | 65 | x1.0 | x1.1 | x1.5 | 180x | +| SatXComp | 4 bands driven, x4 | 276 | x1.1 | x1.2 | x1.5 | 42x | +| SatLim | defaults | 110 | x1.0 | x1.0 | x1.4 | 105x | +| SatLim | drive 30 %, x8, limiting | 278 | x1.0 | x1.1 | x1.4 | 42x | +| SatDiff | defaults | 16 | x1.0 | x1.0 | x1.4 | 725x | +| SatDiff | drive 50 %, x8 | 128 | x1.0 | x1.1 | x1.5 | 91x | +| SatEQ | defaults (bands off) | 6 | x1.1 | x1.2 | x1.4 | 1900x | +| SatEQ | 14 bands saturating, 7 dynamic, x4 | 1530 | x1.0 | x1.16 | x1.5 | 7.6x | +| SatFilt | defaults | 69 | x1.0 | x1.0 | x1.4 | 170x | +| SatFilt | x8, drive 50 % | 337 | x1.0 | x1.25 | x1.7 | 34x | + +- **On one thread the cost stays flat** from 1 to 64 instances (x1.0-1.1): no cache cliff, no hidden shared work. +- **On 4 threads** it rises 0-35 %, most for the heavy oversampled settings. That is the performance cores sharing L2 and memory bandwidth, not contention in our code (there is nothing shared to contend on). +- **On 8 threads** it rises 40-70 %, because threads 5-8 land on efficiency cores. A REAPER session with more worker threads than performance cores sees the same. +- **What a session holds:** at 70 % of the block on 4 threads, roughly 18 heavy SatEQs (the worst case: every band saturating at x4 in both sets), 75 heavy SatFilts, 100 heavy SatXComps or SatLims, and hundreds of anything at defaults. One saturating SatEQ band costs about as much as one SatDiff, because each band oversamples on its own (per-band oversampling was parked in the SatEQ performance pass). +- **Small blocks:** at 64 samples the fixed cost per block is about 3 us (SatComp; SatEQ with all bands off, which rebuilds its 335-parameter snapshot each block). Everything else scales with block length. +- **Tail:** p99 is 3-4x the median for SatComp, SatLim and SatDiff at defaults, at every instance count, so it comes from the signal or periodic per-instance work, not from load. In absolute terms it is under 0.6 % of the block. Not chased. + +## Memory, creation, teardown + +| plug-in | heap per instance, no editor | create | create + destroy x200 | +|---|---|---|---| +| SatComp | 0.6-1.0 MiB | 0.3 ms | +0.0 MiB | +| SatXComp | 1.1-1.9 MiB | 0.6 ms | +0.1 MiB | +| SatLim | 0.5-0.8 MiB | 0.5 ms | +0.0 MiB | +| SatDiff | 0.7-1.3 MiB | 0.4 ms | +0.0 MiB | +| SatEQ | 1.4-2.4 MiB | **2.9 ms** | +0.0 MiB | +| SatFilt | 0.5-1.0 MiB | 0.3 ms | +0.0 MiB | + +No leaks. The RSS still held after a teardown is the allocator keeping freed pages: the next batch of instances reuses them (the later rows of each run grow by about 0) and the churn loop does not grow. + +**SatEQ creation (optional fix).** `Engine::new` takes 1.2 ms and the plug-in builds it twice (in `Default` at 48 kHz, again at the host rate in `initialize`). Nearly all of it is the 14 band saturators each filling a 4097-entry shaper table with `exp` (`ShaperLut::new`), twice: once for shape 0 in `Saturator::new`, again for the band's default shape in `Band::set`. 64 SatEQs add about 0.2 s to a project load; audio is unaffected. Fix if wanted: share the factory tables process-wide (read-only, built once per shape and tile, the way SatFilt's reference noise is), which also speeds up shape changes in every plug-in, or build the band saturators directly at their shape. + +## Open editors + +All open editors draw on the host's single UI thread, so the frame cost below times the number of open windows is what counts. Idle frame (UI pass + tessellation, CPU only; the GPU upload and draw are not included), and the memory one more open editor adds: + +| editor | frame (median) | p95 | MiB per open editor | editors in a 60 fps frame | +|---|---|---|---|---| +| SatComp | 0.14 ms | 0.21 | 1.5 | ~120 | +| SatXComp | 0.29 ms | 0.41 | 1.8 | ~57 | +| SatLim | 0.13 ms | 0.18 | 1.3 | ~130 | +| SatDiff | 0.35 ms | 0.46 | 1.9 | ~47 | +| SatEQ | 0.40 ms | 0.44 | 1.6 | ~42 | +| SatFilt | 0.30 ms (was 1.19) | 0.38 | 1.5 | ~55 (was ~14) | + +**Fixed: SatFilt** recomputed its viewport response (the filter run on an impulse, then an FFT) on every frame, because the sample rate in its cache key was never stored. 3f61838 stores it per scene; a test now fails if an idle frame recomputes the response. + +## For the CLI spec + +- **Engines run in parallel safely.** No globals, so a batch CLI can give each file (or each channel pair) its own engine on its own thread. Expect near-linear speed-up on performance cores and less on efficiency cores. +- **Throughput is high:** 34-1900x real time per core, depending on the plug-in and setting. Heavy SatEQ is the slowest at 7.6x. File I/O will dominate for most plug-ins. +- **Engines are cheap to make and small** (under 2.5 MiB, under 3 ms), so one engine per file is fine. No pooling needed. +- **The parameter tables and the parameter-to-engine mapping live in the plug-in crates** (`params.rs`: `TABLE`, `to_dsp`; `presets.rs`), next to nih-plug and egui. A CLI that reads presets or takes `id=value` arguments either depends on the plug-in crates (pulling in the GUI stack) or needs that layer moved into the DSP crates or a small shared crate. This is the main structural decision for the CLI. +- **Latency compensation:** the CLI must trim each engine's reported latency, as `plugbench render` already does. +- **Parameter smoothing:** an offline render must start from the target values, not ramp into them. SatEQ's engine snaps on its first `set_params` (`have_p`); check the other five engines before the CLI relies on it. + +## Not covered + +- A real REAPER session with many editors open (GPU, baseview's per-window timers). Recipe: one track, 16 instances of one plug-in, all windows open, playing; watch REAPER's Performance Meter (UI and audio) and Activity Monitor. Worth a spot check before the tag. +- VST3 wrapper overhead (CLAP was measured; the DSP is the same). +- 96 kHz and above (cost scales with the sample rate; the oversampled settings cost the most). + +## Rerunning + +``` +cd rust && cargo xtask bundle --release # one plug-in per call +cd tools/plugbench && cargo build --release +PLUGBENCH_N=1,8,32,64 PLUGBENCH_T=1,4,8 PLUGBENCH_CHURN=200 \ + ./target/release/plugbench multi ../../target/bundled/.clap ../../../wavtest/cw_amen09_175.wav 5 [Name=normalised ...] +cargo test -p editor_frame_cost --release -- --ignored --nocapture # from rust/ +``` diff --git a/docs/abouttextcopy.md b/docs/abouttextcopy.md index bb3385b..57245d8 100644 --- a/docs/abouttextcopy.md +++ b/docs/abouttextcopy.md @@ -1,77 +1,207 @@ -Misc control copy - repeat for all 3 plugins, common shared controls +About page copy, all six plug-ins (synced to the plug-ins 2026-11-27, draft for the owner's vetting) +=== +Formatting follows the help bubbles (docs/internal/helpcopy/README.md): brackets hold a gesture ([Click], [Double-click], +[Right-click], [Shift+Click], [Drag]) or text exactly as the UI prints it (controls and values in caps: [DRIVE], [UPWARD]; +shaper names as the dropdown prints them: [Tube], [Tri Fold]). Gesture lines sit on their own lines. US spelling. +Tone stays the owner's: second person, cheeky taglines. + +Shared Misc Controls block (every plug-in; its own meter lines follow it) === **== 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 +[Click] [?] at the end of the preset bar to toggle help, then point at any control to see what it does +[Double-click] a slider to reset it to its default value +[Click] the logo to cycle the color scheme +[Right-click] the logo for the color scheme list +[Double-click] the logo to switch between dark and light mode +[Shift+Click] the logo to roll a random color scheme and font +[Click] the title to open or close this page SatComp about copy === -A waveshaping saturator with compressor and 2-stage 3-band EQ. Made with bricking intentions (: +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. -[LMB] Top-right pencil icon enters custom draw mode. -[LMB] Lower-right SAT value triggers auto-gain match. +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 pre/post-compressor 3-band EQ, then dial in the desired gain in the output module. +Squash it [DWNWARD], lift the quiet bits [UPWARD], or have it both ways with [UP/DWN]. [RNGE] caps how far the lift goes. + +Refine tone with the [PRE-COMP] / [POST-COMP] 3-band EQ, then dial in the desired gain in the output module. +[Drag] a node in the EQ view for frequency and gain, the brackets of the node clicked last for Q **== Misc Controls ==** +(shared block, then:) +[Click] the GR meter to cycle its range +[Click] the output meter to reset its peak and clip readout *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 +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. +Set the crossover ranges with [XOV1] to [XOV3] (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. -[LMB] Top-right pencil icon enters custom draw mode. -[LMB] Lower-right SAT value triggers auto-gain match. +Use [SIDECHAIN] 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 is ideal for low freq, faster Attack and Release for high freq. +Slower [ATTACK] and [RELEASE] suit low frequencies, faster ones suit high frequencies. Each band can squash [DWNWARD], lift [UPWARD] or do both with [UP/DWN]. -Refine tone with post-compressor 5-band EQ, or sculpt with notch, bandpass and allpass with dry signal blending. +Refine tone with the post-compressor 5-band [EQ], or sculpt with notch, bandpass and allpass blended against the dry signal with [EQ MIX]. **== Spectrum Viewport ==** -[Accent] Gain Reduction vs Dry -[Inv Accent] Gain Increase vs Dry +Accent: gain reduction vs dry +Inverted 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 +**== Band Handles ==** +Top horizontal bar: in/out gain difference +Vertical bar above it: gain increase (upward compression) +Vertical bar below it: gain reduction **== Misc Controls ==** +(shared block, then:) +[Click] a band's GR meter to cycle its range +[Click] the output meter to reset its peak and clip readout *insert attributions / Fira Code here* thomchantra SatLim about copy === -A 2-stage clipper/limiter with waveshaping saturator +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. +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 + +[CLIP] and [LIMIT] switch each stage: the clipper alone, the limiter alone, or the clipper ahead of the limiter. -Turn on Lookahead for brickwall, true peak limiting. -Lowering Threshold chews the input signal deeper. -Clip exposes and bricks more transients in the mix. +With both on, the [CLIP] row sets the clip point against the ceiling: below 0 the clipper bricks more transients, above 0 the limiter takes them. [CLIP TYPE] picks the bite ([HARD CLIP], [SOFT CLIP], [2:1], [4:1]) and [KNEE] rounds the bend. -Balance between Threshold (limiter) and Clip (clipper) to dial in desired loudness and character. +Turn on [LOOKAHEAD] for brickwall, true peak limiting. Lowering [THRESH] chews the input signal deeper. -Shorter Release gives a denser, punchier compression whilst introducing distortion artifacts, longer Release gives a smoother result with lower distortions. +A shorter [RELEASE] gives a denser, punchier result while introducing distortion artifacts, a longer one is smoother with lower distortion. [AUTO] lets the material decide. -**== Transient/GR Meter ==** -[Solid] Limiter Gain Reduction -[Striped] Clipper Gain Reduction +**== Meters ==** +[SAT] / [GR] / [OUT]: saturator output, gain reduction, final output +On [GR]: solid = limiter gain reduction, hatched = clipper gain reduction **== Misc Controls ==** +(shared block, then:) +[Click] a meter to cycle its range *insert attributions / Fira Code here* thomchantra + +SatDiff about copy +=== +A waveshaper saturator with phase coloration effects. +Dedicated to sweet saturated sounds :> + +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 + +Draw up to 30 points and drag the hollow handles to bend a segment. Pick [LINEAR] or [CURVE], and mirror the curve with [ODD] or [EVEN] at the top right of the plot. [TILE] folds or repeats the curve so [BIAS] walks through copies of it. + +[A | B] holds two complete saturators, each with its own shape, drive, bias, filters and tone. [A>B] ([B>A]) copies the scene you are editing over the other one, [INIT A] ([INIT B]) resets it. + +[MORPH] blends them: [XFADE] is a static crossfade, the detect modes let the input level move it, and [SPEED] sets how fast it follows. + +[PHASE] rotates the signal before the saturator. The color slot adds a [DIFFUSOR], [PHASER], [FLANGER], [RINGMOD] or [FREQ SHIFT] before ([PRE-SAT]) or after ([POST-SAT]) the saturator, and [COLOR MIX] sets how much of it you hear. + +[LIMIT] is a true-peak output limiter, the box under it shows its gain reduction. The output [HPF] cleans up the low end, on the mid, the side or both. + +**== Meters ==** +[IN] hatched, [OUT] solid + +**== Misc Controls ==** +(shared block, then:) +[Click] a meter to cycle its range +[Right-click] the view under [MORPH] to switch between spectrum and scope + +*insert attributions / Fira Code here* +thomchantra + +SatEQ about copy +=== +A 7-band EQ, each with a saturator and dynamics module. +For mixing, mastering, or mashing to mush B) + +Pick a band along the bottom row or in the viewport. +[Drag] a node for frequency and gain, an HPF / LPF node up and down to step its slope +[Drag] the brackets for Q +[Double-click] a node to reset it + +[Right-click] on [SUM]/[MID] to switch EQ operating mode between summed stereo signal or isolated mid signal. + +[SATURATE] adds harmonics made from the band. +[DELTA-H], [DELTA] and [RESID] keep the EQ clean and add only what the shaper makes of it. +[EXCITE] keeps harmonics above twice the band's frequency. + +[Click] the hamburger icon for extended saturation/dynamics parameters: [ASYM], a custom drawn curve (pencil) and the stage + +[DYNAMIC] lets a bell or shelf follow the key level, [DOWNWARD], [UPWARD] or [UP+DOWN]. Key it from the signal ([INT]) or the host's sidechain ([EXT]). [GR DELTA] lets you hear the difference between compressed and dry signal. + +[TILT] shifts high or low frequencies balance. [PIVOT] sets the tilting point. [GAIN MATCH] compensates output loudness depending on the EQ curve. [B.SOLO] lets you isolate and preview a particular band. + +[A | B] holds two complete settings: [A>B] copies the one you edit over the other, [RESET A] goes back to the loaded preset. + +**== Viewport ==** +The spectrum of the output. +Accent: gain reduction +Inverted accent: gain lift +Hatched: the other set +[RMS] is a slow, smooth master view; [SLOW], [MED] and [FAST] set how fast the picture moves + +**== Misc Controls ==** +(shared block, then:) +[Right-click] the first set tab to flip [SUM] / [MID] +[Click] the output meter to reset its peak and clip readout + +*insert attributions / Fira Code here* +thomchantra + +SatFilt about copy +=== +A creative filter with a saturator in the loop. +Squelch responsibly ;) + +[LADDER], [K35], [SVF] and [WARP] cores, plus [DUAL] and [TRIPLE] spreads, [ALLPASS], [COMB], [RINGMOD], [FSHIFT], [CRUSH], [FORMANT] and a [TANK] reverb. + +Two scenes, [A] and [B], each with its own filter, drawn waveshaper, color effect and four modulators. Run them alone ([SINGLE]), in series either way ([SERIES]) or side by side ([PARALLEL]); each scene has its own filter wet. A three-band [EQ] wraps both, before and after the filter. + +Put the saturator in the [LOOP] for a resonance that growls and compresses, or before ([PRE]) or after ([POST]) the filter. The modulators move nine targets from an [LFO], [MIDI] notes or a sidechain ([SC INT], [SC EXT]): [FREE], locked to the host ([SYNC]) or once per hit ([ENVELOPE]), with cycles you can draw. +[Drag] the node for cutoff and resonance +[Drag] the side brackets for slope (closed = steep, open = broad) +[Drag] the top bracket for gain +[Click] the pencil on the saturator curve to open the draw view for a custom waveshape + +**== Misc Controls ==** +(shared block, then:) +[Click] a meter to cycle its range + +*insert attributions / Fira Code here* +thomchantra + +***========*** +Readme copy draft +***========*** + +old: +Three saturator-based dynamics plug-ins in one black-and-white (or any colour you like) monospace UI. Made with bricking intentions. + +new: +Saturator-infused plug-ins suite + + +old about: +3 saturator-based dynamics plug-ins suite (VST3/CLAP): a compressor, 4-band compressor, and a limiter + +new about: +Waveshaper saturation DSP plug-ins suite (VST3/CLAP): a compressor, 4-band compressor, and phase diffusor. diff --git a/docs/install/INSTALL-Windows.txt b/docs/install/INSTALL-Windows.txt index e306518..42c25ad 100644 --- a/docs/install/INSTALL-Windows.txt +++ b/docs/install/INSTALL-Windows.txt @@ -1,36 +1,48 @@ -@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 all the plug-ins) - -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. +@NAME@ @VER@ - installation (Windows) +===================================== + +This zip contains two plug-in formats, and a script that installs 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) + +Easiest: the installer script +----------------------------- +Unzip the download, then double-click install.cmd . Windows asks for administrator permission and the +plug-in is copied into C:\Program Files\Common Files\VST3 and \CLAP. Then rescan plug-ins in your host. + - Windows may first warn that the file came from the internet (the script is not signed): choose Run. + - No admin rights? Open a command prompt in the folder and run install.cmd -User + (installs into %LOCALAPPDATA%\Programs\Common\VST3 and \CLAP, for you only). + - Close your DAW first: Windows keeps loaded plug-ins locked. + - uninstall.cmd removes it again (uninstall.cmd -User for the per-user copy). + +By hand +------- +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 all the plug-ins) + +Uninstall: run uninstall.cmd, or 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/SUITE-INSTALL-Linux.txt b/docs/install/SUITE-INSTALL-Linux.txt index 659fecb..303a8dc 100644 --- a/docs/install/SUITE-INSTALL-Linux.txt +++ b/docs/install/SUITE-INSTALL-Linux.txt @@ -4,7 +4,7 @@ SatComp suite @VER@ - installation (Linux, experimental) This Linux build is new and lightly tested. Known issue: the meters and the scope can stutter on some systems. Feedback is very welcome (see "Got issues?" below). -This zip holds all four plug-ins (SatComp, SatXComp, SatLim, SatDiff) as VST3 and CLAP, plus one +This zip holds all six plug-ins (SatComp, SatXComp, SatLim, SatDiff, SatEQ, SatFilt) as VST3 and CLAP, plus one joint manual (PDF). The VST3s are FOLDERS, not single files. Easiest: the install script diff --git a/docs/install/SUITE-INSTALL-Windows.txt b/docs/install/SUITE-INSTALL-Windows.txt index cde61df..fb34762 100644 --- a/docs/install/SUITE-INSTALL-Windows.txt +++ b/docs/install/SUITE-INSTALL-Windows.txt @@ -1,13 +1,28 @@ SatComp suite @VER@ - installation (Windows) ============================================ -This zip holds all four plug-ins, as VST3 and CLAP, plus one joint manual (PDF): +This zip holds all six plug-ins, as VST3 and CLAP, plus one joint manual (PDF): SatComp compressor with a waveshaping saturator and EQ SatXComp 4-band compressor with a saturator per band SatLim saturator into a clipper and a true-peak limiter SatDiff A/B waveshaper saturator with morph and phase colouring - + SatEQ 7-band EQ with saturation and dynamics in every band + SatFilt creative filter with a saturator in the loop and modulators + +Easiest: the installer script +----------------------------- +Unzip the download, then double-click install.cmd . Windows asks for administrator permission and all six +plug-ins are copied into C:\Program Files\Common Files\VST3 and \CLAP. Then rescan plug-ins in your host. + - Windows may first warn that the file came from the internet (the script is not signed): choose Run. + - No admin rights? Open a command prompt in the folder and run install.cmd -User + (installs into %LOCALAPPDATA%\Programs\Common\VST3 and \CLAP, for you only). + - Close your DAW first: Windows keeps loaded plug-ins locked. + - Only some of them? From a prompt: install.cmd satcomp sateq (the bundle names). + - uninstall.cmd removes them again (uninstall.cmd -User for the per-user copy). + +By hand +------- 1. Unzip the download anywhere. 2. VST3: copy the folders in VST3\ (satcomp.vst3, satxcomp.vst3, ...) into C:\Program Files\Common Files\VST3\ @@ -24,7 +39,7 @@ Your settings and presets Presets: %APPDATA%\\Presets Themes: %APPDATA%\SatComp\themes.json (shared by all the plug-ins) -Uninstall: delete the folders and files you copied. +Uninstall: run uninstall.cmd, or delete the folders and files you copied. Got issues? ----------- diff --git a/docs/install/SUITE-INSTALL-macOS.txt b/docs/install/SUITE-INSTALL-macOS.txt index 46ac72c..199d341 100644 --- a/docs/install/SUITE-INSTALL-macOS.txt +++ b/docs/install/SUITE-INSTALL-macOS.txt @@ -1,12 +1,14 @@ SatComp suite @VER@ - installation (macOS) ========================================== -This zip holds all four plug-ins, as VST3 and CLAP, plus one joint manual (PDF): +This zip holds all six plug-ins, as VST3 and CLAP, plus one joint manual (PDF): SatComp compressor with a waveshaping saturator and EQ SatXComp 4-band compressor with a saturator per band SatLim saturator into a clipper and a true-peak limiter SatDiff A/B waveshaper saturator with morph and phase colouring + SatEQ 7-band EQ with saturation and dynamics in every band + SatFilt creative filter with a saturator in the loop and modulators The build is universal (Apple silicon and Intel). diff --git a/docs/install/install-windows.cmd b/docs/install/install-windows.cmd new file mode 100644 index 0000000..70def27 --- /dev/null +++ b/docs/install/install-windows.cmd @@ -0,0 +1,4 @@ +@echo off +rem @NAME@ @VER@: double-click to install the plug-ins in this folder for all users (Windows asks for administrator +rem permission). Options: install.cmd -User (only you, no admin), install.cmd satcomp sateq (only those plug-ins). +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1" %* diff --git a/docs/install/install-windows.ps1 b/docs/install/install-windows.ps1 new file mode 100644 index 0000000..3a743c7 --- /dev/null +++ b/docs/install/install-windows.ps1 @@ -0,0 +1,102 @@ +# @NAME@ @VER@ installer for Windows: copies the VST3 and CLAP plug-ins in this folder into your plug-in folders. +# Run it through install.cmd / uninstall.cmd (double-click), or from a prompt: +# install.cmd all users: C:\Program Files\Common Files\VST3 and \CLAP (asks for administrator permission) +# install.cmd -User only you, no admin: %LOCALAPPDATA%\Programs\Common\VST3 and \CLAP +# install.cmd satcomp sateq only the plug-ins named (bundle names, any case) +# uninstall.cmd [-User] remove what this script installed +# Windows PowerShell 5.1 (built into Windows 10 / 11); no other tools needed. +param( + [switch]$User, + [switch]$Uninstall, + [switch]$NoPause, + [Parameter(ValueFromRemainingArguments = $true)][string[]]$Only +) +$ErrorActionPreference = 'Stop' +$title = '@NAME@ @VER@' +$here = $PSScriptRoot + +function Finish([int]$code) { + if (-not $NoPause) { Write-Host ''; Read-Host 'Press Enter to close' | Out-Null } + exit $code +} + +# what this folder holds (VST3 bundles are folders, CLAP plug-ins single files), optionally narrowed to the names given +$vst3s = @(Get-ChildItem -LiteralPath (Join-Path $here 'VST3') -Filter '*.vst3' -Directory -ErrorAction SilentlyContinue) +$claps = @(Get-ChildItem -LiteralPath (Join-Path $here 'CLAP') -Filter '*.clap' -File -ErrorAction SilentlyContinue) +if ($Only -and $Only.Count -gt 0) { + $want = $Only | ForEach-Object { $_.ToLowerInvariant() -replace '\.(vst3|clap)$', '' } + $vst3s = @($vst3s | Where-Object { $want -contains $_.BaseName.ToLowerInvariant() }) + $claps = @($claps | Where-Object { $want -contains $_.BaseName.ToLowerInvariant() }) +} +if ($vst3s.Count -eq 0 -and $claps.Count -eq 0) { + Write-Host "Nothing to install. Run this from the unzipped folder (it needs the VST3 and CLAP folders next to it)." + if ($Only) { Write-Host "Plug-in names asked for: $($Only -join ', ')" } + Finish 1 +} + +# where to: all users (Program Files, 64-bit even from a 32-bit prompt) or this user only +if ($User) { + $base = Join-Path $env:LOCALAPPDATA 'Programs\Common' +} else { + $pf = if ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles } + $base = Join-Path $pf 'Common Files' + $id = [Security.Principal.WindowsIdentity]::GetCurrent() + $admin = (New-Object Security.Principal.WindowsPrincipal $id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + if (-not $admin) { + # run this script again as administrator, with the same choices; the elevated window shows the result + $a = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$PSCommandPath`"") + if ($Uninstall) { $a += '-Uninstall' } + if ($Only) { $a += $Only } + try { + Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $a + } catch { + Write-Host 'Administrator permission was not given, so nothing was changed.' + Write-Host 'To install for your user only (no admin), run: install.cmd -User' + Finish 1 + } + exit 0 + } +} +$vdir = Join-Path $base 'VST3' +$cdir = Join-Path $base 'CLAP' + +if ($Uninstall) { + Write-Host "Removing $title from $base" + foreach ($p in $vst3s) { + $t = Join-Path $vdir $p.Name + if (Test-Path -LiteralPath $t) { Remove-Item -LiteralPath $t -Recurse -Force; Write-Host " removed $t" } + } + foreach ($p in $claps) { + $t = Join-Path $cdir $p.Name + if (Test-Path -LiteralPath $t) { Remove-Item -LiteralPath $t -Force; Write-Host " removed $t" } + } + Write-Host 'Done. Presets and themes in %APPDATA% are kept.' + Finish 0 +} + +Write-Host "Installing $title" +try { + New-Item -ItemType Directory -Force -Path $vdir, $cdir | Out-Null + foreach ($p in $vst3s) { + $t = Join-Path $vdir $p.Name + if (Test-Path -LiteralPath $t) { Remove-Item -LiteralPath $t -Recurse -Force } + Copy-Item -LiteralPath $p.FullName -Destination $vdir -Recurse -Force + # drop the "downloaded from the internet" mark the zip left on the files + Get-ChildItem -LiteralPath $t -Recurse -File | Unblock-File + Write-Host " VST3 $t" + } + foreach ($p in $claps) { + $t = Join-Path $cdir $p.Name + Copy-Item -LiteralPath $p.FullName -Destination $cdir -Force + Unblock-File -LiteralPath $t + Write-Host " CLAP $t" + } +} catch { + Write-Host '' + Write-Host "Could not copy: $($_.Exception.Message)" + Write-Host 'If your DAW is open, close it (it keeps loaded plug-ins locked) and run this again.' + Finish 1 +} +Write-Host '' +Write-Host 'Done. Rescan plug-ins in your host (REAPER: Options > Preferences > Plug-ins > VST / CLAP > Re-scan).' +Finish 0 diff --git a/docs/install/make-suite.sh b/docs/install/make-suite.sh index 285555a..d11d632 100755 --- a/docs/install/make-suite.sh +++ b/docs/install/make-suite.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Builds the all-in-one release files from the per-plug-in zips the bundle job made. # make-suite.sh -# platform: macOS-universal | Windows-x64 | Linux-x64. Writes SatComp-Suite--.zip (all four VST3 / CLAP, one joint +# platform: macOS-universal | Windows-x64 | Linux-x64. Writes SatComp-Suite--.zip (all six VST3 / CLAP, one joint # manual, a suite INSTALL.txt, install.sh on Linux), SatComp-Suite-Manual-.pdf (the joint manual: the per-plug-in manuals # joined in suite order) and, on macOS, SatComp-Suite--macOS-universal.pkg (installs for all users). # Needs pdfunite (poppler) for the joint manual. @@ -17,10 +17,10 @@ for z in "$zips"/*-"$plat".zip; do unzip -q -o "$z" -d "$dist"; n=$((n + 1)) done [ "$n" -gt 0 ] || { echo "no per-plug-in zips for $plat in $zips"; exit 1; } -rm -f "$dist/INSTALL.txt" "$dist/install.sh" +rm -f "$dist/INSTALL.txt" "$dist/install.sh" "$dist/install.ps1" "$dist/install.cmd" "$dist/uninstall.cmd" # joint manual: the per-plug-in manuals (each zip carries its own) joined in suite order, replacing them in the suite zip manuals=() -for d in SatComp SatXComp SatLim SatDiff; do +for d in SatComp SatXComp SatLim SatDiff SatEQ SatFilt; do m=("$dist/$d"-Manual-v*.pdf) [ -f "${m[0]}" ] && manuals+=("${m[0]}") done @@ -36,6 +36,12 @@ if [ "$os" = Linux ]; then sed -e "s/@VER@/${tag}/g" "$here/install-suite-linux.sh" > "$dist/install.sh" chmod +x "$dist/install.sh" fi +if [ "$os" = Windows ]; then + # the same installer as the per-plug-in zips: it installs whatever VST3 / CLAP plug-ins sit next to it + for f in install-windows.ps1:install.ps1 install-windows.cmd:install.cmd uninstall-windows.cmd:uninstall.cmd; do + sed -e "s/@NAME@/SatComp suite/g" -e "s/@VER@/${tag}/g" "$here/${f%%:*}" > "$dist/${f##*:}" + done +fi zipf="$(cd "$out" && pwd)/SatComp-Suite-${tag}-${plat}.zip" rm -f "$zipf" (cd "$dist" && zip -qr "$zipf" .) diff --git a/docs/install/uninstall-windows.cmd b/docs/install/uninstall-windows.cmd new file mode 100644 index 0000000..d13f1c2 --- /dev/null +++ b/docs/install/uninstall-windows.cmd @@ -0,0 +1,4 @@ +@echo off +rem @NAME@ @VER@: double-click to remove the plug-ins in this folder from the all-users plug-in folders. +rem uninstall.cmd -User removes the copy installed for you only. +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1" -Uninstall %* diff --git a/docs/manual/SatComp-Manual-v0.5.2.pdf b/docs/manual/SatComp/SatComp-Manual-v0.5.2.pdf similarity index 100% rename from docs/manual/SatComp-Manual-v0.5.2.pdf rename to docs/manual/SatComp/SatComp-Manual-v0.5.2.pdf diff --git a/docs/manual/SatComp-Manual-v0.5.3.pdf b/docs/manual/SatComp/SatComp-Manual-v0.5.3.pdf similarity index 100% rename from docs/manual/SatComp-Manual-v0.5.3.pdf rename to docs/manual/SatComp/SatComp-Manual-v0.5.3.pdf diff --git a/docs/manual/SatComp/SatComp-Manual-v0.5.4.pdf b/docs/manual/SatComp/SatComp-Manual-v0.5.4.pdf new file mode 100644 index 0000000..7341e8f Binary files /dev/null and b/docs/manual/SatComp/SatComp-Manual-v0.5.4.pdf differ diff --git a/docs/manual/SatComp.md b/docs/manual/SatComp/SatComp.md similarity index 93% rename from docs/manual/SatComp.md rename to docs/manual/SatComp/SatComp.md index f432220..16624d9 100644 --- a/docs/manual/SatComp.md +++ b/docs/manual/SatComp/SatComp.md @@ -1,11 +1,11 @@ --- title: SatComp -version: 0.5.3 +version: 0.5.4 tagline: waveshaping saturator with compressor and 2-stage 3-band EQ -screenshot: ../screenshots/satcomp.png +screenshot: ../../screenshots/v054/satcomp.png --- -# SatComp 0.5.3 +# SatComp 0.5.4 A waveshaping saturator with a compressor and a 2-stage 3-band EQ. Give the compressor more spice to squash. Made with bricking intentions. @@ -72,6 +72,8 @@ Both axes show the same range in dB. **CEIL** (0 to +18 dB) and **FLOOR** (-12 t 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. +In the view, drag a node for its frequency and gain (a cut filter has no gain). The node you clicked last shows two **Q brackets**: drag one sideways to set the band's Q, closed for narrow, open for broad. The wheel sets the Q of the nearest node. Drag the dotted pivot line to move the tilt's pivot, and drag anywhere else to tilt. Double-click a node, the pivot or an empty spot to reset it. + ## 6. Output | Control | What it does | diff --git a/docs/manual/SatDiff-Manual-v0.1.0.pdf b/docs/manual/SatDiff/SatDiff-Manual-v0.1.0.pdf similarity index 100% rename from docs/manual/SatDiff-Manual-v0.1.0.pdf rename to docs/manual/SatDiff/SatDiff-Manual-v0.1.0.pdf diff --git a/docs/manual/SatDiff/SatDiff-Manual-v0.1.1.pdf b/docs/manual/SatDiff/SatDiff-Manual-v0.1.1.pdf new file mode 100644 index 0000000..c71cc47 Binary files /dev/null and b/docs/manual/SatDiff/SatDiff-Manual-v0.1.1.pdf differ diff --git a/docs/manual/SatDiff.md b/docs/manual/SatDiff/SatDiff.md similarity index 94% rename from docs/manual/SatDiff.md rename to docs/manual/SatDiff/SatDiff.md index 5585c49..b483786 100644 --- a/docs/manual/SatDiff.md +++ b/docs/manual/SatDiff/SatDiff.md @@ -1,11 +1,11 @@ --- title: SatDiff -version: 0.1.0 +version: 0.1.1 tagline: A/B waveshaper saturator with morph and phase colouring -screenshot: ../screenshots/satdiff.png +screenshot: ../../screenshots/v054/satdiff.png --- -# SatDiff 0.1.0 +# SatDiff 0.1.1 A waveshaper saturator with phase colouring effects. Dedicated to sweet saturated sounds :> @@ -30,7 +30,7 @@ Use Tube with low drive for warm saturation, Tri Fold for destruction, or a cust | Vertical meter | scope or spectrum of the output | | Saturator cells | DRIVE, ASYM, HPF, LPF, BIAS (with the tile buttons), TONE | | Colour effects | on / off, type, PRE-SAT / POST-SAT, the effect's own controls, PHASE | -| Output | COLOR MIX, SAT MIX, OUT HPF (M / S), IN and OUT meters, IN GAIN, OUT GAIN | +| Output | COLOR MIX, SAT MIX, OUT HPF (M / S), IN and OUT meters, I>O, IN GAIN, OUT GAIN | ## 3. Saturator scenes @@ -89,7 +89,7 @@ The LFOs run freely in Hz; there is no tempo sync. Changing the type fades betwe | 1x / 2x / 4x / 8x | oversampling of the saturators | | BYPASS | plain bypass at the plug-in's latency | -The **IN** and **OUT** meters carry clip lamps. The vertical meter beside the morph module is a scope; **left-click** it to cycle the timing windows and **right-click** to switch to the spectrum. +The **IN** and **OUT** meters carry clip lamps. **I>O** under them reads the output level against the input (slow, in dB), with a bar either side of the centre. The vertical meter beside the morph module is a scope; **left-click** it to cycle the timing windows and **right-click** to switch to the spectrum. ## 7. Recipes diff --git a/docs/manual/SatEQ/SatEQ-Manual-v0.1.0.pdf b/docs/manual/SatEQ/SatEQ-Manual-v0.1.0.pdf new file mode 100644 index 0000000..1888ac7 Binary files /dev/null and b/docs/manual/SatEQ/SatEQ-Manual-v0.1.0.pdf differ diff --git a/docs/manual/SatEQ/SatEQ.md b/docs/manual/SatEQ/SatEQ.md new file mode 100644 index 0000000..7175fe8 --- /dev/null +++ b/docs/manual/SatEQ/SatEQ.md @@ -0,0 +1,121 @@ +--- +title: SatEQ +version: 0.1.0 +tagline: 7-band EQ with saturation and dynamics in every band +--- + +# SatEQ 0.1.0 + +A 7-band EQ where every band can saturate and compress on its own, in two sets at once: SUM and SIDE. + + + +## 1. The idea + +SatEQ is an equaliser first. Each band is a filter you place and shape in the viewport; on top of it a band can **saturate** (add harmonics made from the part of the signal the band is working on) and **follow the level** (a dynamic bell or shelf). Both are optional, per band, and leave the EQ curve alone unless you ask otherwise. + +Two sets run side by side: **SUM** (the mono part, or **MID** if you prefer) and **SIDE**. Each has its own seven bands, its own TILT and its own gain, so you can brighten the sides and tighten the centre in one instance. + +## 2. Layout + +| Area | What it does | +|---|---| +| Header | logo (themes), preset bar, INIT, window scale, output meter. Second row: A / B scenes, viewport on / off and speed, oversampling, the SUM / SIDE tabs, B.SOLO and BYPASS. | +| Inspector (left) | the selected band: filter, DYNAMIC and SATURATE blocks. The hamburger icons open the full DYNAMIC and SATURATE pages. | +| Viewport | spectrum of the output, the response curve of the edited set and the band nodes | +| Band row | the seven bands: number = on / off, label = select, the glyph grid picks the filter kind | +| Right column | peak, RMS and crest readouts, latency, PIVOT, TILT, set gain, IN>OUT, GAIN MATCH, OUT MIX, OUT GAIN | + +## 3. The filter + +Drag a node for frequency and gain. Drag the brackets beside the selected node for Q (closed = high Q). Double-click a node to reset the band. Press on the curve away from any node to bring in the nearest unused band of 2 to 6: it switches on at the pointer and follows the drag. HPF and LPF nodes sit on their curve; drag them up and down to step the slope (6, 12, 24 or 48 dB/oct). + +| Kind | Controls | +|---|---| +| HPF, LPF | FREQ, Q, slope | +| Low shelf, high shelf, bell | FREQ, Q, gain (±18 dB) | +| All-pass, band-pass, notch | FREQ, Q, **WET**: how much of the filter is blended in | + +The selected band's node stays visible even when the band is off. A band that is off costs no CPU. + +## 4. Saturate + +The **SATURATE** block adds a waveshaper to the band. Choose a shape (14 built-in plus a drawn **Custom** curve), then set **DRIVE**, **BIAS** and **ASYM**. **OVRDRV** trims how much of the harmonic residue is added, and **SAT Q** sets the width of the band the shaper listens to. + +A new band starts on **RESID**, the most audible stage. + +| Stage | What the shaper hears and what you get | +|---|---| +| **DELTA-H** | the difference the band makes. Only the harmonics are added; the EQ stays exactly linear. | +| **DELTA** | the same, plus the shaper's change of gain inside the band | +| **RESID** | the band's own pass-band (low-pass for a low shelf or HPF, high-pass for a high shelf or LPF, band-pass otherwise), independent of the band gain | +| **EXCITE** | RESID, keeping only what lies above twice the band frequency (air and bite from a low or mid band) | + +The small window shows the transfer curve as it is heard. With audio playing, two dots ride the curve at the peak level reaching the shaper. Click the pencil in the full page to draw a **Custom** curve (up to 20 points, with ODD and EVEN symmetry tools). + +## 5. Dynamic + +Bells and shelves can be **DYNAMIC**. The band's gain moves when the key crosses **THRES**: + +| Mode | What it does | +|---|---| +| DOWNWARD | cuts the band gain above the threshold | +| UPWARD | lifts it below the threshold | +| UP+DOWN | both | + +**RATIO**, **ATK** and **REL** shape the detector. **RANGE** caps how far the gain may move from the static gain. The key is the band itself (the signal through the band's key filter). **SIDECHAIN SRC** switches a band's detector between the signal (**INT**) and the host's sidechain input (**EXT**; shown as `EXT -` when no bus is connected). The vertical meter and the GR / GL readouts show the live gain move; **GR DELTA** lets you hear what the dynamics change. + +## 6. Output and tools + +| Control | What it does | +|---|---| +| SUM / SIDE GAIN | gain of the whole set, ±24 dB | +| PIVOT, TILT | tilts the set's response around the pivot frequency, ±12 dB | +| GAIN MATCH | holds the output at the input level. It is derived from the EQ curve (a loudness-weighted average), not from the audio, so it never pumps. | +| IN>OUT | output level against input level, slow | +| OUT MIX | blend of the processed and the dry signal | +| OUT GAIN | final level, -24 to +12 dB | +| B.SOLO | plays the selected band alone with its gain, dynamics and saturation | +| x1 / x2 / x4 | oversampling of the saturators (more, less aliasing, more latency) | +| BYPASS | plain bypass at the plug-in's latency | + +## 7. Viewport + +The viewport shows the spectrum of the edited set. Accent = what the EQ took away, inverted accent = where the output is louder. The other set is hatched underneath. The three icons in the corner toggle that underlay, the gain-difference shading and the node tooltip. + +**OFF | SPEC** switches the analyser. **RMS | SLOW | MED | FAST** sets its speed: MED is the default, SLOW refreshes and falls more slowly, FAST follows transients, and RMS is a master view: a very slow power average smoothed over a third of an octave, for judging the tonal balance of a whole mix. + +## 8. Scenes and presets + +**A | B** hold two complete settings (every band, set gain, tilt, output). Click A or B to switch; **A>B** copies the one you are editing over the other, **RESET** puts the edited scene back to the loaded preset. Oversampling, bypass, solo and the viewport settings are not part of a scene. + +The preset bar has a save icon, the name (click for the list, load, save and INIT), and previous / next. A name in asterisks means the preset has been modified. **INIT** loads the factory defaults. + +## 9. Recipes + +**Tight low end, wide top.** SUM: HPF at 30 Hz, a low-shelf cut at 250 Hz. SIDE: HPF at 120 Hz, a high shelf lifted at 8 kHz with SATURATE on EXCITE. + +**De-harsh on demand.** A bell at 3.5 kHz, DYNAMIC DOWNWARD, THRES around -24 dB, RATIO 3:1, fast ATK. The band only cuts when the harshness is there; GR DELTA shows what it takes. + +**Air without hiss.** A high shelf at 10 kHz, +3 dB, SATURATE at DELTA-H with a Tube shape: the shaper adds harmonics from the shelf's contribution only. + +## 10. Good to know + +- **Latency** is reported to the host and follows the oversampling setting. +- **Presets** are saved to `SatEQ/Presets` in your application-support folder. +- **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. +- Right-click the first set tab to flip SUM and MID. +- 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 SatEQ. + +## Notes to check (delete before the PDF) + +- Plug-in version (0.1.0). Six factory presets ship (5k Tamer, Bass Hump, Beat Pump, Hammed Radio, Kick Sidechain, Mud Kontrol). +- Recipe values are suggestions, not yet tried by ear. +- The hero screenshot is built (v054); there is no signal-flow figure. diff --git a/docs/manual/SatFilt/SatFilt-Manual-v0.1.0.pdf b/docs/manual/SatFilt/SatFilt-Manual-v0.1.0.pdf new file mode 100644 index 0000000..a7b8d58 Binary files /dev/null and b/docs/manual/SatFilt/SatFilt-Manual-v0.1.0.pdf differ diff --git a/docs/manual/SatFilt/SatFilt.md b/docs/manual/SatFilt/SatFilt.md new file mode 100644 index 0000000..7db631a --- /dev/null +++ b/docs/manual/SatFilt/SatFilt.md @@ -0,0 +1,142 @@ +--- +title: SatFilt +version: 0.1.0 +tagline: Creative filter with a saturator in the loop, two scenes and four modulators each +--- + +# SatFilt 0.1.0 + +A creative filter with a saturator that can sit inside the filter's feedback. Thirteen filter families, two complete scenes, a color effect and four modulators per scene, wrapped in a pre / post EQ. + + + +## 1. The idea + +SatFilt is a filter first: pick a family, drag the node in the viewport for cutoff and resonance. The **saturator** can sit before the filter, after it, inside its feedback loop (**LOOP**, where the resonance growls and compresses) or on only what the filter changes. A **color effect** (diffusor, phaser, flanger, ring modulator, frequency shifter) colors the sound before or after the filter, and **four modulators** move any of nine targets from an LFO, MIDI notes or a sidechain. + +Everything except the EQ exists twice: scenes **A** and **B** each have their own filter, saturator, color effect and modulators, and run alone, in series or side by side. + + + +## 2. Layout + +| Area | What it does | +|---|---| +| Header | logo (themes), title (About, preferences, changelog), save icon, preset name with previous / next, `?` help mode | +| Second row | A / B scene tabs, A>B (copy), INIT, the family selector with arrows, the EQ tab, BYPASS | +| Viewport | the filter response over the spectrum (or the EQ curve in EQ view), with the node and its brackets | +| Filter rows | CUTOFF, RES, GAIN, the fourth control (SLOPE, FB TAP or a family control), then the family's shape group and cells | +| Tab row | SATURATE, MODULATE, COLOR: the label shows the tab, the square switches that module on or off for the edited scene | +| Right column | window scale, oversampling, routing, A / B wet, I>O, LIMIT and its gain reduction, IN / OUT meters, MIX, OUT GAIN | + +Turn on help mode with the `?` in the preset field: hovering any control then shows what it does. + +## 3. The filter + +Drag the **F** node for cutoff and resonance; the wheel sets resonance. The side brackets set the slope (closed = steep, open = broad) where the family has one, the top bracket sets **GAIN**, the level going into the filter (pushing it drives the filter and the saturator harder). Double-click the node to reset cutoff and resonance. + +| Group | Families | Character | +|---|---|---| +| CLASSIC | LADDER, K35, SVF, WARP | Moog-style ladder (with FB TAP), aggressive MS-20 style, clean and versatile, bent and unstable. MODE morphs lowpass through bandpass to highpass. | +| SPREAD | DUAL, TRIPLE | two or three filters side by side (PAIR / SET pick their responses, SPREAD fans them apart) | +| PHASE / DELAY | ALLPASS, COMB, TANK | phaser-like notches (STAGES, SPREAD), metallic tuned delay (POLARITY, DAMP), a small reverb (SIZE, DIFFUSION, WIDTH, HPF, LPF) | +| MODULATION | RINGMOD, FSHIFT | inharmonic, metallic tones (RING-AM, UP-DOWN, HPF / LPF on the effect) | +| TEXTURE | CRUSH, FORMANT | sample-rate and bit reduction (HOLD-DIFF-GLIDE, BITS, JITTER), vowels (VOWEL, VOICE) | + +The viewport's corner icons add the side channel as a hatched layer and shade the difference between input and output spectrum. + +## 4. Saturate + +The **SATURATE** tab holds the edited scene's saturator. Choose a **SHAPE** (the family's shaper list plus a drawn **Custom** curve: click the pencil on the curve view), then set **DRIVE**, **BIAS** and **ASYM** (how much of the lopsided, even color from BIAS is kept). **PHASE** rotates the signal going into the filter and saturator: peaks change shape, so the same drive clips differently. + +**STAGE** decides where the shaper sits: + +| Stage | What you get | +|---|---| +| **PRE** | distorts before the filter: the filter shapes the harmonics | +| **POST** | distorts the filtered sound | +| **LOOP** | inside the filter's feedback: the resonance growls and compresses. Families without feedback run it as POST. | +| **DELTA** | saturates only what the filter changes | +| **DELTA-H** | the same, harmonics only | +| **RESID** | the filter's cleaned residue, added back | + +The three glyphs on the BIAS row set what happens past the shaper's edge: plain clip, mirror fold or repeat (fold and repeat run at least 4x oversampled; shapers that already fold ignore them). **HP** and **LP** filter the saturated signal before **SAT MIX** blends it with the clean one; in LOOP they filter the filter's output. The view shows the transfer curve as it is heard, with the stretch the signal reaches lit in the accent color. + +## 5. Modulate + +Each scene has four modulators, **A** to **D**. The bar under each letter shows its live output. Right-click a letter to INIT it or copy it to another slot. + +| Control | What it does | +|---|---| +| MOD SRC | **LFO** runs on its own, **MIDI** restarts it at every note, **SC INT** / **SC EXT** listen to the scene's input / the sidechain input | +| MOD DEST | FILTER: CUTOFF, RES, GAIN, SHAPE (the family's morph). SATURATE: DRIVE, BIAS, MIX. COLOR: AMOUNT (the type's main control), MIX. **OFF** switches the slot off. | +| Shape | sine, triangle, square, saw, random, or the pencil (a cycle you draw) | +| MOD CYCLE | **FREE** (Hz), **SYNC** (a note value: locked to the playback, or restarted by MIDI / sidechain hits), **ENVELOPE** (plays once per note or hit, then rests) | +| RATE / DIVISION | speed in Hz, or the note value in SYNC | +| DEPTH + direction | how far the target moves, and which way: down only, both ways, up only. On cutoff, 100 % is four octaves each way. | +| PHASE, WIDTH, ROUND | start point, left / right offset, corner smoothing | +| THRES, RATIO, ATK, REL | the detector of a sidechain source, with its gain-reduction bar | + +With a sidechain source in **FREE**, the detector's level is the modulation (a ducker or follower). In the other cycles every hit over THRES restarts or fires the cycle (3 dB of hysteresis, never sooner than the attack time, so a held note fires once). Several slots on one target add up. Modulated sliders show their fill in the accent color with a mark at the live value. + +**The cycle editor.** The view draws one cycle with its playhead and a dotted start-phase line. Drag a point (the end points move up and down), drag an open handle to bend its segment, double-click a handle to straighten it. Editing a stock shape keeps the edit for that shape; double-click its tile to go back to the original. The pencil starts a **Custom** cycle from the one playing: click the plot to add a point, double-click a point to remove it. **CRV** toggles smooth and straight segments, **PINGPONG** runs the shape forward then back. Random shapes pick **STEP**, **SINE** (glides) or **DRIFT** in the same row; in SYNC the pattern repeats with the song. + +## 6. Color + +The **COLOR** tab adds SatDiff's color effect to the scene, **PRE-FILT** or **POST-FILT**: + +| Type | Controls | +|---|---| +| DIFFUSOR | FREQ, Q, STAGES, SPREAD: smears the phase for a softer, wider sound | +| PHASER | FREQ, RATE, DEPTH, STAGES, FDBK, WIDTH | +| FLANGER | DLY, RATE, DEPTH, FDBK, WIDTH | +| RINGMOD | FREQ, SHAPE, AMOUNT: metallic, bell-like tones | +| FREQ SHIFT | SHIFT, DLY, FDBK, WIDTH: detuned, inharmonic movement | + +**HP** and **LP** filter the effect signal for every type, before **COLOR MIX**. Stacking is intended: a color RINGMOD into the RINGMOD family is a feature. + +## 7. Scenes, routing and output + +| Control | What it does | +|---|---| +| A / B | which scene the tabs below edit. A>B copies the edited scene over the other one, INIT resets it. | +| Routing | **SINGLE** (A alone), **SERIES** A>B or AO | output level against input level | +| LIMIT | a safety limiter on the output, on by default; the box below shows its gain reduction | +| IN / OUT | meters (click to cycle the range) | +| MIX, OUT GAIN | dry / processed blend, final level | +| BYPASS | plain bypass at the plug-in's latency | + +## 8. Inputs + +SatFilt takes a stereo **sidechain** input (used by SC EXT) and **MIDI notes** (any channel; used by the MIDI source). In REAPER, route the key track to channels 3/4 for the sidechain, and send MIDI to the track the plug-in is on. + +## 9. Recipes + +**Squelchy bass.** LADDER, cutoff around 400 Hz, RES 60 %, STAGE LOOP with a Tube shape and DRIVE 40 %. Modulator A: MIDI, ENVELOPE, saw, CUTOFF, depth 50 % down. + +**Ducked filter.** Modulator A: SC EXT, FREE, CUTOFF, depth 60 % down, THRES -24, fast ATK. The kick on the sidechain closes the filter on every hit. + +**Wide shimmer.** TANK in scene B, PARALLEL with a clean SVF in A; COLOR DIFFUSOR POST-FILT on B, LFO on COLOR MIX with WIDTH 50 %. + +## 10. Good to know + +- **Latency** is reported to the host and follows the oversampling actually running (and the wrap modes, which force 4x). +- **Presets** are saved to `SatFilt/Presets` in your application-support folder. They carry drawn waveshapes and modulator cycles. A name in asterisks means the preset has been modified. +- **Themes:** click the logo for the next theme, double-click it for dark / light, right-click for the list. +- 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 SatFilt. + +## Notes to check (delete before the PDF) + +- Recipe values are suggestions, not yet tried by ear. +- Sidechain routing line (channels 3/4) assumes REAPER's default pin mapping for the aux input. diff --git a/docs/manual/SatLim-Manual-v0.1.0.pdf b/docs/manual/SatLim/SatLim-Manual-v0.1.0.pdf similarity index 100% rename from docs/manual/SatLim-Manual-v0.1.0.pdf rename to docs/manual/SatLim/SatLim-Manual-v0.1.0.pdf diff --git a/docs/manual/SatLim-Manual-v0.1.1.pdf b/docs/manual/SatLim/SatLim-Manual-v0.1.1.pdf similarity index 100% rename from docs/manual/SatLim-Manual-v0.1.1.pdf rename to docs/manual/SatLim/SatLim-Manual-v0.1.1.pdf diff --git a/docs/manual/SatLim/SatLim-Manual-v0.2.0.pdf b/docs/manual/SatLim/SatLim-Manual-v0.2.0.pdf new file mode 100644 index 0000000..8bdae61 Binary files /dev/null and b/docs/manual/SatLim/SatLim-Manual-v0.2.0.pdf differ diff --git a/docs/manual/SatLim.md b/docs/manual/SatLim/SatLim.md similarity index 98% rename from docs/manual/SatLim.md rename to docs/manual/SatLim/SatLim.md index 305bcf7..3e956c5 100644 --- a/docs/manual/SatLim.md +++ b/docs/manual/SatLim/SatLim.md @@ -1,11 +1,11 @@ --- title: SatLim -version: 0.1.1 +version: 0.2.0 tagline: 2-stage clipper / limiter with waveshaping saturator -screenshot: ../screenshots/satlim.png +screenshot: ../../screenshots/v054/satlim.png --- -# SatLim 0.1.1 +# SatLim 0.2.0 A 2-stage clipper and limiter with a waveshaping saturator. When you need to nuke it from orbit. diff --git a/docs/manual/SatXComp-Manual-v0.1.0.pdf b/docs/manual/SatXComp/SatXComp-Manual-v0.1.0.pdf similarity index 100% rename from docs/manual/SatXComp-Manual-v0.1.0.pdf rename to docs/manual/SatXComp/SatXComp-Manual-v0.1.0.pdf diff --git a/docs/manual/SatXComp-Manual-v0.1.1.pdf b/docs/manual/SatXComp/SatXComp-Manual-v0.1.1.pdf similarity index 100% rename from docs/manual/SatXComp-Manual-v0.1.1.pdf rename to docs/manual/SatXComp/SatXComp-Manual-v0.1.1.pdf diff --git a/docs/manual/SatXComp/SatXComp-Manual-v0.1.2.pdf b/docs/manual/SatXComp/SatXComp-Manual-v0.1.2.pdf new file mode 100644 index 0000000..907a677 Binary files /dev/null and b/docs/manual/SatXComp/SatXComp-Manual-v0.1.2.pdf differ diff --git a/docs/manual/SatXComp.md b/docs/manual/SatXComp/SatXComp.md similarity index 99% rename from docs/manual/SatXComp.md rename to docs/manual/SatXComp/SatXComp.md index 14a6987..378a693 100644 --- a/docs/manual/SatXComp.md +++ b/docs/manual/SatXComp/SatXComp.md @@ -1,11 +1,11 @@ --- title: SatXComp -version: 0.1.1 +version: 0.1.2 tagline: 4-band compressor with a waveshaping saturator on every band -screenshot: ../screenshots/satxcomp.png +screenshot: ../../screenshots/v054/satxcomp.png --- -# SatXComp 0.1.1 +# SatXComp 0.1.2 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. diff --git a/docs/manual/build.py b/docs/manual/tools/build.py similarity index 71% rename from docs/manual/build.py rename to docs/manual/tools/build.py index a7177df..672c006 100644 --- a/docs/manual/build.py +++ b/docs/manual/tools/build.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 -"""Build the manual PDFs: docs/manual/.md -> docs/manual/-Manual-v.pdf +"""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`; +A4, solid black pages, white Fira Sans (Fonts/Fira_Sans). 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. """ @@ -11,19 +11,20 @@ import figures from weasyprint import HTML -HERE = pathlib.Path(__file__).resolve().parent -FONTS = HERE.parent.parent / "Fonts" / "Fira_Code_v6.2" / "ttf" +HERE = pathlib.Path(__file__).resolve().parent # docs/manual/tools +MANUAL = HERE.parent # one folder per plug-in: /.md and its PDFs +FONTS = MANUAL.parent.parent / "Fonts" / "Fira_Sans" # the help bubbles' face: easier to read than the mono UI font in a document 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'); } +@font-face { font-family: 'Fira Sans'; font-weight: 400; src: url('%(f)s/FiraSans-Regular.ttf'); } +@font-face { font-family: 'Fira Sans'; font-weight: 700; src: url('%(f)s/FiraSans-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; } + @bottom-left { content: '%(title)s %(version)s'; font: 7.5pt 'Fira Sans'; color: #888; } + @bottom-right { content: counter(page); font: 7.5pt 'Fira Sans'; color: #888; } } @page :first { @bottom-left { content: ''; } @bottom-right { content: ''; } } -html { background: #000; color: #fff; font: 8.6pt/1.5 'Fira Code', monospace; } +html { background: #000; color: #fff; font: 9.4pt/1.5 'Fira Sans', sans-serif; } 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; } @@ -56,6 +57,8 @@ def split_front(text): def build(md_path): meta, body = split_front(md_path.read_text()) body = re.split(r"\n## Notes to check", body)[0] + # the heading always carries the front-matter version (the one the PDF is named after) + body = re.sub(r"^# %s [0-9.]+$" % re.escape(meta["title"]), "# %s %s" % (meta["title"], meta["version"]), body, count=1, flags=re.M) html = markdown.markdown(body, extensions=["tables", "fenced_code"]) html = figures.expand(html) # the tagline goes right under the first heading @@ -66,6 +69,6 @@ def build(md_path): print("wrote", out.name) if __name__ == "__main__": - names = sys.argv[1:] or ["SatComp", "SatXComp", "SatLim", "SatDiff"] + names = sys.argv[1:] or ["SatComp", "SatXComp", "SatLim", "SatDiff", "SatEQ", "SatFilt"] for n in names: - build(HERE / (n + ".md")) + build(MANUAL / n / (n + ".md")) diff --git a/docs/manual/figure_specs.py b/docs/manual/tools/figure_specs.py similarity index 53% rename from docs/manual/figure_specs.py rename to docs/manual/tools/figure_specs.py index 814e513..2e9aeca 100644 --- a/docs/manual/figure_specs.py +++ b/docs/manual/tools/figure_specs.py @@ -115,15 +115,59 @@ def _row(spec, names, x0, y, widths, gap, h=30, filled=(), dashed=()): sd["notes"].append((12, cy + 66, 190, "saturators (PRE-SAT / POST-SAT)", "l")) sd["notes"].append((12, H - 12, 760, "filled = shapes the sound | dashed = optional, can be switched off | SAT MIX blends clean and saturated", "l")) -FLOWS = {"satcomp": sc, "satxcomp": xc, "satlim": sl, "satdiff": sd} +# ---- SatFilt +H = 200 +sf = {"size": (920, H), "boxes": {}, "arrows": [], "notes": []} +cy = 98 +sf["boxes"]["in"] = (10, cy - 15, 40, 30, "IN", 0) +sf["boxes"]["peq"] = (68, cy - 15, 66, 30, "PRE EQ", 2) +sf["arrows"].append(([(50, cy), (68, cy)], False, "")) +# the two scenes, one row each: PHASE > COLOR (pre) > FILTER + SAT > COLOR (post) +sx, ra, rb = 172, cy - 44, cy + 16 +seq = [("PHASE", 54, 0), ("COLOR\nPRE", 58, 2), ("FILTER + SAT", 120, 1), ("COLOR\nPOST", 58, 2)] +for tag, ry in [("A", ra), ("B", rb)]: + x, last = sx, None + for nm, w, st in seq: + sf["boxes"][tag + nm] = (x, ry, w, 28, nm, st) + if last is not None: + sf["arrows"].append(([(last, ry + 14), (x, ry + 14)], False, "")) + last = x + w + x += w + 12 + sf["notes"].append((sx - 16, ry + (9 if tag == "A" else 27), 10, "SCENE " + tag, "r")) + send = last +xs1 = 150 +sf["arrows"].append(([(134, cy), (xs1, cy), (xs1, ra + 14), (sx, ra + 14)], False, "")) +sf["arrows"].append(([(xs1, cy), (xs1, rb + 14), (sx, rb + 14)], False, "")) +xm = send + 20 +sf["boxes"]["route"] = (xm, cy - 15, 60, 30, "ROUTE", 0) +sf["arrows"].append(([(send, ra + 14), (xm - 10, ra + 14), (xm - 10, cy), (xm, cy)], False, "")) +sf["arrows"].append(([(send, rb + 14), (xm - 10, rb + 14), (xm - 10, cy), (xm, cy)], False, "")) +x, last = xm + 60 + 14, xm + 60 +for nm, w, st in [("POST EQ", 64, 2), ("MIX", 40, 0), ("OUT GAIN", 72, 0), ("LIMIT", 50, 2), ("OUT", 36, 0)]: + sf["boxes"]["t" + nm] = (x, cy - 15, w, 30, nm, st) + sf["arrows"].append(([(last, cy), (x, cy)], False, "")) + last = x + w + x += w + 14 +# modulators: four per scene, each with its own source +mx = sx + 54 + 12 + 58 + 12 - 10 +sf["boxes"]["mod"] = (mx, 8, 140, 26, "MOD A-D (x2)", 2) +sf["arrows"].append(([(mx + 70, 34), (mx + 70, ra)], True, "")) +sf["notes"].append((mx + 150, 18, 300, "LFO / MIDI / SC INT / SC EXT", "l")) +sf["notes"].append((mx + 150, 30, 300, "-> 9 targets in filter, sat, color", "l")) +sf["notes"].append((xm - 4, rb + 44, 300, "SINGLE | SERIES A>B, A<B | PARALLEL", "l")) +sf["notes"].append((10, H - 8, 900, "filled = shapes the sound | dashed = optional, can be switched off | EQ shared, everything in a row is per scene", "l")) + +FLOWS = {"satcomp": sc, "satxcomp": xc, "satlim": sl, "satdiff": sd, "satfilt": sf} # =================================================================================================== exploded heroes -# Targets are SCREENSHOT pixels (what an image editor shows on docs/screenshots/*.png). The drop shadow around the window is +# Targets are SCREENSHOT pixels (what an image editor shows on docs/screenshots/v054/*.png). The drop shadow around the window is # cropped away. Labels: top(...) sits above the window (its line drops down), left(...) / right(...) sit in the side margins. import pathlib from PIL import Image -_SHOTS = pathlib.Path(__file__).resolve().parent.parent / "screenshots" +# the screenshots of the release the manuals describe (docs/screenshots//.png) +SHOTS = pathlib.Path(__file__).resolve().parents[2] / "screenshots" / "v054" +_SHOTS = SHOTS FS = 6.9 # label font, pt (figures.py) @@ -196,62 +240,113 @@ def spec(self): "canvas": (self.cw, self.ch), "leaders": self.leaders, "brackets": self.brackets, "notes": self.notes} -# ---- SatComp (screenshot 1904 x 1338; window x 112-1792, y 75-1190) -h = _H("satcomp.png", 250, 330, 230, 330) -h.left("waveshaper\nselector", 307, (146, 307), 200) -h.top("oversample", 747, 0, (747, 303), 220) -h.top("eq page", 1272, 0, (1272, 303), 160) -h.top("enter custom shaper\ndraw mode", 505, 1, (505, 372), 400) -h.top("toggle sidechain input\nfrom channel 3/4", 1040, 1, (1053, 303), 460) -h.right("viewport mode:\nscope / transient", 376, (1352, 376), 300) -h.left("shaper hpf/lpf\npre filter", 900, (146, 935), 250, elbow=935) -h.left("tone is another\nlow-pass filter", 1000, (440, 1005), 250, elbow=1024) -h.right("drag CEIL / FLOOR\nto rescale the plot", 760, (1262, 708), 330) -h.right("drag the curve:\nabove threshold = ratio\nbelow it = threshold", 480, (1250, 462), 330) -h.bracket("waveshaper module", 142, 532, 1215) -h.bracket("compressor module", 568, 1366, 1215) -h.bracket("output module", 1402, 1764, 1215) -h.note("k.shape = knee shape\nff>fb = feedforward / feedback\ngr dist = gain reduction distortion", 568, 1285, 800) +# ---- SatComp (v054: 1492 x 1038; window x 46-1446, y 32-978) +h = _H("satcomp.png", 250, 330, 200, 300) +h.left("waveshaper\nselector", 243, (72, 243), 200) +h.top("oversample", 575, 0, (575, 224), 220) +h.top("? = help mode:\npoint at any control", 940, 0, (950, 162), 300) +h.top("enter custom shaper\ndraw mode", 300, 1, (373, 286), 400) +h.top("toggle sidechain input\nfrom channel 3/4", 780, 1, (830, 224), 460) +h.top("eq page", 1100, 1, (1013, 224), 160) +h.right("viewport mode:\nscope / transient", 300, (1068, 270), 300, elbow=270) +h.right("drag the curve:\nabove threshold = ratio\nbelow it = threshold", 412, (806, 412), 330) +h.right("drag CEIL / FLOOR\nto rescale the plot", 560, (845, 612), 330, elbow=612) +h.left("shaper hp/lp\npre filter", 785, (72, 785), 250) +h.left("tone is another\nlow-pass filter", 880, (318, 838), 250, elbow=838) +h.bracket("waveshaper module", 72, 396, 1000) +h.bracket("compressor module", 427, 1090, 1000) +h.bracket("output module", 1122, 1420, 1000) +h.note("k.shape = knee shape\nff>fb = feedforward / feedback\ngr dist = gain reduction distortion", 427, 1070, 800) _sc = h.spec() -# ---- SatXComp (1108 x 765; window x 56-1052, y 38-690) -h = _H("satxcomp.png", 250, 280, 40, 250) -h.left("multiband tabs", 399, (74, 399), 220) -h.right("xov = crossover range\n24 dB = slope selector", 250, (1010, 267), 270, elbow=None) -h.right("oversample", 352, (950, 366), 270) -h.right("l.ahead = lookahead", 392, (950, 399), 270) -h.right("compression mode:\ndown, up, down/up", 450, (722, 433), 270) -h.bracket("waveshaper module", 72, 380, 700) -h.bracket("compressor module", 385, 846, 700) -h.bracket("output module", 857, 1040, 700) -h.note("3 compression modes\ndown: normal compression\nup: upward compression\ndown/up: both, OTT style", 385, 770, 560) +# ---- SatXComp (v054: 1752 x 1198; window x 46-1706, y 32-1138) +h = _H("satxcomp.png", 250, 290, 200, 260) +h.left("multiband tabs", 651, (72, 651), 220) +h.top("? = help mode:\npoint at any control", 780, 0, (900, 160), 300) +h.top("eq page", 1330, 0, (1310, 160), 160) +h.top("toggle sidechain input\nfrom channel 3/4", 1120, 1, (1145, 160), 460) +h.right("xov = crossover range\n24 dB = slope selector", 431, (1680, 431), 280) +h.right("oversample", 596, (1680, 596), 280) +h.right("l.ahead = lookahead", 651, (1680, 651), 280) +h.right("compression mode:\ndown, up, down/up", 740, (1063, 683), 280, elbow=683) +h.bracket("waveshaper module", 72, 585, 1160) +h.bracket("compressor module", 606, 1355, 1160) +h.bracket("output module", 1380, 1680, 1160) +h.note("3 compression modes\ndown: normal compression\nup: upward compression\ndown/up: both, OTT style", 606, 1230, 560) _xc = h.spec() -# ---- SatLim (622 x 921; window x 56-566, y 38-845) -h = _H("satlim.png", 260, 270, 30, 140) -h.right("oversample", 384, (480, 384), 250) -h.right("l.ahead = lookahead", 495, (478, 495), 250) -h.left("waveform scope:\ndrag it for the\nwindow and ceiling", 220, (200, 220), 230) -h.left("oversampled shaper\nmeter and clip meter", 560, (292, 600), 230) -h.bracket("waveshaper\nmodule", 72, 266, 852) -h.bracket("limiter / clipper\noutput module", 276, 551, 852) +# ---- SatLim (v054: 942 x 1458; window x 46-896, y 32-1398) +h = _H("satlim.png", 290, 330, 30, 150) +h.right("? = help mode", 237, (871, 237), 300) +h.right("oversample", 600, (871, 627), 300, elbow=627) +h.right("shaper meter and\nclip meter", 690, (500, 655), 300, elbow=655) +h.right("l.ahead = lookahead", 811, (871, 811), 300) +h.right("CLIP | LIMIT: switch\nthe clipper and limiter", 868, (871, 868), 300) +h.right("clip curve, with KNEE", 968, (871, 968), 300) +h.right("release: drag, or AUTO", 1180, (871, 1180), 300) +h.left("waveform scope:\ndrag it for the\nwindow and ceiling", 420, (72, 420), 260) +h.left("scope settings: source,\nwave, window, ceiling", 566, (72, 566), 260) +h.bracket("waveshaper\nmodule", 72, 396, 1420) +h.bracket("limiter / clipper\noutput module", 410, 871, 1420) _sl = h.spec() -# ---- SatDiff (586 x 999; window x 56-530, y 38-925) -h = _H("satdiff.png", 360, 480, 150, 80) +# ---- SatDiff (v054: 882 x 1644; window x 46-836, y 32-1584) +h = _H("satdiff.png", 360, 480, 110, 80) h.gapr = 64 -h.left("LMB: cycle color theme\ndouble-LMB: dark / light\nRMB: theme dropdown", 110, (86, 115), 330, elbow=None) -h.top("LMB plugin title:\nabout page", 150, 0, (150, 114), 300) -h.left("scene A / B toggle:\nwaveshaper config tab", 206, (88, 184), 330) -h.left("waveshaper module\nparameters", 575, (74, 580), 330) -h.left("bias tile: no tiling,\nmirror tile, repeat tile", 658, (110, 658), 330) -h.left("color effects module:\ndiffusor, phaser, flanger,\nringmod, frequency shifter", 730, (74, 700), 330) -h.left("output module: hpf mid/side\nfor cleaning up low end\nor a mono sub", 860, (74, 862), 330) -h.top("enter custom shaper\ndraw mode", 395, 1, (395, 222), 300) -h.right("A/B morph module\nLMB cycles the mode, RMB lists it\nXFADE: blends the 2 scenes\nMORPH: a detector drives the blend\n(A on silence, B on loud peaks)", 230, (500, 230), 400) -h.right("depth: interpolation\nintensity", 380, (500, 282), 400, xe=44) -h.right("speed: attack / release\nof the detector", 430, (500, 337), 400, xe=30) -h.right("vertical meter: LMB cycles\nthe timing windows,\nRMB the spectrum", 500, (500, 455), 400, xe=16) +h.left("LMB: cycle color theme\ndouble-LMB: dark / light\nRMB: theme dropdown", 178, (80, 178), 330) +h.top("LMB plugin title:\nabout page", 218, 0, (218, 160), 300) +h.top("? = help mode", 614, 0, (614, 222), 220) +h.left("scene A / B toggle:\nwaveshaper config tab", 294, (72, 294), 330) +h.left("enter custom shaper\ndraw mode", 470, (608, 410), 330) +h.left("waveshaper module\nparameters", 1010, (72, 1010), 330) +h.left("bias tile: no tiling,\nmirror tile, repeat tile", 1138, (72, 1138), 330) +h.left("color effects module:\ndiffusor, phaser, flanger,\nringmod, frequency shifter", 1240, (72, 1195), 330) +h.left("output module: hpf mid/side\nfor cleaning up low end\nor a mono sub", 1480, (545, 1449), 330, elbow=1449) +h.right("A/B morph module\nLMB cycles the mode, RMB lists it\nXFADE: blends the 2 scenes\nMORPH: a detector drives the blend\n(A on silence, B on loud peaks)", 428, (810, 428), 400) +h.right("depth: interpolation\nintensity", 600, (810, 522), 400, xe=44) +h.right("speed: attack / release\nof the detector", 680, (810, 615), 400, xe=30) +h.right("vertical meter: LMB cycles\nthe timing windows,\nRMB the spectrum", 810, (810, 810), 400) +h.right("I>O: output level\nagainst the input", 1290, (810, 1292), 400) _sd = h.spec() -HEROES = {"satcomp": _sc, "satxcomp": _xc, "satlim": _sl, "satdiff": _sd} +# ---- SatEQ (v054: 2068 x 1008; window x 46-2022, y 32-948) +h = _H("sateq.png", 330, 400, 250, 260) +h.top("A / B scenes", 124, 0, (124, 217), 220) +h.top("analyser: OFF | SPEC\nspeed: RMS SLOW MED FAST", 869, 0, (869, 217), 440) +h.top("SUM / SIDE sets\n(right-click: MID / SIDE)", 1700, 0, (1558, 217), 380) +h.top("oversample", 1130, 1, (1301, 217), 220) +h.top("? = help mode", 1490, 1, (1391, 160), 220) +h.left("band inspector:\nfilter of the\nselected band", 300, (72, 300), 280) +h.left("hamburger icon:\nopens the full DYNAMIC\nor SATURATE page", 470, (316, 440), 280, elbow=440) +h.left("band saturator:\nshape, drive, OD", 860, (72, 860), 280) +h.right("B.SOLO: the selected\nband alone", 236, (1996, 236), 360) +h.right("PIVOT / TILT: tilts\nthe whole set", 470, (1996, 470), 360) +h.right("GAIN MATCH: from the\nEQ curve, never pumps", 718, (1996, 718), 360) +h.bracket("inspector", 72, 340, 970) +h.bracket("band row", 362, 1686, 970) +h.bracket("output", 1706, 1996, 970) +h.note("band row: number = on / off, label = select, glyphs = filter kind\nviewport: drag a node for frequency and gain, the brackets for Q,\ndouble-click to reset; press the curve to add the next band", 362, 1040, 1300) +_se = h.spec() + +# ---- SatFilt (v054: 1142 x 1570; window x 46-1096, y 32-1510) +h = _H("satfilt.png", 380, 420, 170, 120) +h.top("filter family", 560, 0, (620, 212), 300) +h.top("? = help mode", 1000, 0, (1050, 157), 220) +h.top("LMB plugin title:\nabout page", 218, 1, (218, 160), 300) +h.top("pre / post EQ:\nlabel = view, square = on", 840, 1, (840, 212), 380) +h.left("LMB: cycle color theme\ndouble-LMB: dark / light\nRMB: theme dropdown", 150, (80, 178), 330) +h.left("scene A / B: what\nthe tabs below edit", 275, (72, 235), 330) +h.left("drag F: cutoff + res\nside brackets: slope\ntop bracket: gain", 450, (72, 450), 330) +h.left("filter rows: their\ncontrols follow the family", 780, (72, 780), 330) +h.left("tabs: label = view,\nsquare = on / off", 997, (72, 997), 330) +h.left("transfer view; the\npencil draws a curve", 1250, (72, 1250), 330) +h.right("oversampling\n(* = raised by the family)", 358, (1070, 358), 400) +h.right("routing: SINGLE,\nSERIES, PARALLEL", 455, (1070, 455), 400) +h.right("filter wet per scene", 565, (1070, 565), 400) +h.right("LIMIT: safety limiter", 752, (1070, 752), 400) +h.right("IN / OUT meters", 1060, (1070, 1060), 400) +h.bracket("saturate / modulate / color, per scene", 72, 895, 1530) +h.bracket("output", 916, 1070, 1530) +_sf = h.spec() + +HEROES = {"satcomp": _sc, "satxcomp": _xc, "satlim": _sl, "satdiff": _sd, "sateq": _se, "satfilt": _sf} diff --git a/docs/manual/figures.py b/docs/manual/tools/figures.py similarity index 94% rename from docs/manual/figures.py rename to docs/manual/tools/figures.py index afcad54..da47fa7 100644 --- a/docs/manual/figures.py +++ b/docs/manual/tools/figures.py @@ -12,9 +12,8 @@ from PIL import Image HERE = pathlib.Path(__file__).resolve().parent -SHOTS = HERE.parent / "screenshots" -ACC = "#b6ff3b" # annotation ink (the plug-ins' own white and red stay the UI's) -BUILD = HERE / ".build" # cropped screenshots (generated, git-ignored) +ACC = "#00ffff" # annotation ink, cyan (the plug-ins' own white and red stay the UI's) +BUILD = HERE.parent / ".build" # cropped screenshots (generated, git-ignored: docs/manual/.build) PAGE_W = 178.0 # mm, A4 less the margins # ---------------------------------------------------------------------------------------------------- hero @@ -104,13 +103,13 @@ def flow(spec): lines = lab.split("\n") for i, ln in enumerate(lines): ty = y + h / 2 + (i - (len(lines) - 1) / 2) * 12 + 4 - out.append(f'{ln}') + out.append(f'{ln}') for x, y, w, text, al in spec.get("notes", []): lines = text.split("\n") for i, ln in enumerate(lines): tx = x + (w / 2 if al == "c" else (w if al == "r" else 0)) anchor = {"l": "start", "c": "middle", "r": "end"}[al] - out.append(f'{ln}') + out.append(f'{ln}') return f'
{"".join(out)}
' @@ -128,7 +127,7 @@ def row(names, x0, y, widths, gap, h=30, styles=None): return boxes, arrows, xs -from figure_specs import FLOWS, HEROES # noqa: E402 +from figure_specs import FLOWS, HEROES, SHOTS # noqa: E402 def expand(html): diff --git a/docs/releases/v0.5.4.md b/docs/releases/v0.5.4.md new file mode 100644 index 0000000..48bc60f --- /dev/null +++ b/docs/releases/v0.5.4.md @@ -0,0 +1,60 @@ +SatEQ and SatFilt join the family, and every plug-in gets a help overlay, a sans-serif font mode and a startup scale. + +| Plug-in | Version | What | +|---|---|---| +| SatComp | 0.5.4 | upward / downward / both compression, Ratio shapers, one ASYM, help overlay | +| SatXComp | 0.1.2 | Ratio shapers, ASYM per band, main-view guides, help overlay | +| SatLim | 0.2.0 | clipper / limiter section (CLIP and LIMIT switches, clip point, clip curves with KNEE), release 5-500 ms + AUTO, Ratio shapers, ASYM, help overlay | +| SatDiff | 0.1.1 | scene row (A \| B, copy, init), Ratio shapers, ASYM per scene, help overlay | +| SatEQ | 0.1.0 | new: 7-band EQ with a saturator and dynamics in every band, SUM + SIDE | +| SatFilt | 0.1.0 | new: creative filter, 13 families, two scenes with routing, saturator in or around the loop, color effect, four modulators per scene, pre / post EQ | + +## Every plug-in +- **Help mode:** click **?** at the end of the preset bar, then point at any control for a short description of it. +- **Two new shapers,** Ratio 2:1 and Ratio 4:1 (17 in all), and **one ASYM** per saturator that evens out lopsided saturation (it replaces SatComp's per-shaper ASYM). +- **Preferences:** a sans-serif mode for the UI font (FONT MONO | SANS) with its own face for the numbers, and a **STARTUP SCALE** every new instance opens at. Shift + click on the logo rolls a random colour scheme and font. +- The draw view shows the stretch of the curve the signal reaches. Every plug-in opens its **manual** from the About page (OPEN MANUAL); the manuals are rewritten around annotated v0.5.4 screenshots. + +## SatComp 0.5.4 +- **Compressor modes:** DWNWARD as before, **UPWARD** lifts quiet parts below the threshold (up to RNGE), **UP/DWN** does both. The GR meter, the compressor plot and the scope follow the mode. + +## SatXComp 0.1.2 +- ASYM per band, and level and frequency guides on the main view. + +## SatLim 0.2.0 +- **A clipper / limiter section:** CLIP and LIMIT switch each stage (either, both or neither), the CLIP row sets the clip point -6 to +6 dB against the ceiling, and **CLIP TYPE** picks HARD CLIP, SOFT CLIP, 2:1 or 4:1 with a **KNEE**. +- **RELEASE** runs 5 to 500 ms, with **AUTO** in its corner (the slider locks while it is on). Oversampling now defaults to x4. +- Level guides on the scope. + +## SatDiff 0.1.1 +- **A scene row:** A | B, A>B (copies the edited scene over the other), INIT A / B and the oversampling dropdown, with LIMIT beside them. +- ASYM per scene, and an **I>O** readout under the meters. The vertical scope no longer stalls at the bottom on dense material. + +## New: SatEQ 0.1.0 +- **Two sets at once, SUM and SIDE** (or MID and SIDE: right-click the first tab), each with seven bands, its own TILT around a PIVOT and its own gain. +- **Filters:** HPF and LPF with 6, 12, 24 and 48 dB/oct slopes (drag the node up and down to step the slope), low and high shelves, bells, notch, band-pass and all-pass with a WET blend. Drag nodes for frequency and gain, the brackets for Q. +- **A saturator per band** with four stages: DELTA-H, DELTA and RESID add only the harmonics the band makes (the EQ stays clean), and EXCITE keeps what lies above twice the band. 16 shapers plus a **Custom** one you draw (20 points, ODD / EVEN tools), DRIVE, BIAS and ASYM. A live dot rides the shaper curve at the level that reaches it. +- **Dynamic bands:** downward, upward or both, THRES, RATIO, ATK, REL and RANGE, keyed from the signal or from the **host's sidechain input**. **GR DELTA** plays what the dynamics take away. +- **GAIN MATCH** is derived from the EQ curve, not from the audio, so it never pumps. **B.SOLO** plays one band on its own, with its dynamics and saturation. +- **Spectrum viewport** with the other set hatched underneath, gain-difference shading, a node tooltip, and speeds **RMS** (a slow, smooth master view), **SLOW**, **MED** and **FAST**. +- **A | B scenes**, presets (save, load, previous / next, a modified marker), RMS and crest readouts, the suite's 30 colour schemes, About / Preferences / Changelog and a manual. + +## New: SatFilt 0.1.0 +- **Thirteen filter families:** LADDER (with a selectable feedback tap), K35, SVF and WARP; DUAL and TRIPLE spreads; ALLPASS, COMB and a TANK reverb; RINGMOD and FSHIFT; CRUSH and FORMANT. Drag the node for cutoff and resonance, the brackets for slope and gain. +- **A saturator in or around the filter:** PRE, POST, inside the feedback (**LOOP**, a resonance that growls and compresses), or on only what the filter changes (DELTA, DELTA-H, RESID). The shaper list plus a drawn **Custom** curve, DRIVE, BIAS, ASYM, a phase rotator, three wrap modes, HP / LP on the saturated signal and SAT MIX. +- **Two scenes, A and B,** each with its own filter, saturator, color effect and modulators: alone, in series either way, or in parallel, each with its own wet. +- **Four modulators per scene,** each from an LFO, MIDI notes or a sidechain (the scene's input or the plug-in's sidechain input, with its own detector and GR meter), FREE, SYNC or ENVELOPE, on nine targets (cutoff, resonance, gain, the family's shape, drive, bias, sat mix, color amount, color mix). Shapes include three random kinds, and every cycle can be edited in the view or drawn from scratch. +- **Color effect** per scene, before or after the filter: SatDiff's diffusor, phaser, flanger, ring modulator and frequency shifter, with HP / LP and COLOR MIX. +- **Pre / post EQ** (three bands and tilt each, SatComp's), a safety limiter, presets that carry the drawn curves, help overlay and a manual. + +## Command line (experimental) +- **`satcomp`** renders audio files through any chain of the six plug-ins, offline and headless, sample for sample the same as the plug-ins: presets by name or file, values in real units, an optional sidechain file, WAV / FLAC / MP3 / AAC in, WAV or FLAC out, a JSON summary and a null-test `diff`. In this release it is built from source only (`cargo build --release -p satcomp-cli`); packaged binaries and MIDI input come later. See `docs/CLI.md`. + +## Notes +- SatEQ and SatFilt are new, so their parameter ids are fixed from this release on. They ship with factory presets (six for SatEQ, eight for SatFilt). +- SatComp, SatXComp and SatDiff only gain parameters (none removed or renamed): presets, projects and automation carry over. +- **SatComp:** ASYM is now one value instead of one per shaper. Preset files convert (the value of the preset's own shaper is kept); a project saved with 0.5.3 that lowered ASYM opens at 100 %. +- **SatLim:** the old CLIP % control is gone (replaced by the CLIP / LIMIT section). The factory presets were converted (the old clip gain folded into THRESHOLD); your own presets and projects from 0.1.x open with the clipper at its new defaults, so check them, and automation of the old CLIP has nothing to drive. +- **Windows installer script:** unzip, double-click `install.cmd` (all users, asks for admin; `install.cmd -User` for you only, `uninstall.cmd` to remove). Every platform now installs in one step: the macOS `.pkg`, `install.sh` on Linux, `install.cmd` on Windows. +- **SatEQ on Windows:** fixed before release, it failed to load (its engine ran out of stack while REAPER scanned it). +- The macOS and Windows builds are not signed or notarized (see INSTALL.txt). Windows and Linux builds of SatEQ and SatFilt are untested. diff --git a/docs/screenshots/satcomp.png b/docs/screenshots/v053/satcomp.png similarity index 100% rename from docs/screenshots/satcomp.png rename to docs/screenshots/v053/satcomp.png diff --git a/docs/screenshots/satdiff.png b/docs/screenshots/v053/satdiff.png similarity index 100% rename from docs/screenshots/satdiff.png rename to docs/screenshots/v053/satdiff.png diff --git a/docs/screenshots/satlim.png b/docs/screenshots/v053/satlim.png similarity index 100% rename from docs/screenshots/satlim.png rename to docs/screenshots/v053/satlim.png diff --git a/docs/screenshots/satxcomp.png b/docs/screenshots/v053/satxcomp.png similarity index 100% rename from docs/screenshots/satxcomp.png rename to docs/screenshots/v053/satxcomp.png diff --git a/docs/screenshots/v054/github-cover-054.png b/docs/screenshots/v054/github-cover-054.png new file mode 100644 index 0000000..b36a35c Binary files /dev/null and b/docs/screenshots/v054/github-cover-054.png differ diff --git a/docs/screenshots/v054/hero-cover-054.png b/docs/screenshots/v054/hero-cover-054.png new file mode 100644 index 0000000..c8552a1 Binary files /dev/null and b/docs/screenshots/v054/hero-cover-054.png differ diff --git a/docs/screenshots/v054/satcomp.png b/docs/screenshots/v054/satcomp.png new file mode 100644 index 0000000..4d279e1 Binary files /dev/null and b/docs/screenshots/v054/satcomp.png differ diff --git a/docs/screenshots/v054/satdiff.png b/docs/screenshots/v054/satdiff.png new file mode 100644 index 0000000..c313773 Binary files /dev/null and b/docs/screenshots/v054/satdiff.png differ diff --git a/docs/screenshots/v054/sateq.png b/docs/screenshots/v054/sateq.png new file mode 100644 index 0000000..9724dec Binary files /dev/null and b/docs/screenshots/v054/sateq.png differ diff --git a/docs/screenshots/v054/satfilt.png b/docs/screenshots/v054/satfilt.png new file mode 100644 index 0000000..2257a0c Binary files /dev/null and b/docs/screenshots/v054/satfilt.png differ diff --git a/docs/screenshots/v054/satlim.png b/docs/screenshots/v054/satlim.png new file mode 100644 index 0000000..db3eccb Binary files /dev/null and b/docs/screenshots/v054/satlim.png differ diff --git a/docs/screenshots/v054/satxcomp.png b/docs/screenshots/v054/satxcomp.png new file mode 100644 index 0000000..86ec452 Binary files /dev/null and b/docs/screenshots/v054/satxcomp.png differ diff --git a/rust/Cargo.lock b/rust/Cargo.lock index cb19fed..ed4d9d8 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -175,6 +175,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9" +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + [[package]] name = "as-raw-xcb-connection" version = "1.0.1" @@ -283,6 +289,15 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -301,6 +316,12 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "built" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b" + [[package]] name = "bumpalo" version = "3.20.3" @@ -327,6 +348,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -611,6 +638,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "coreaudio-rs" version = "0.11.3" @@ -674,6 +707,21 @@ dependencies = [ "windows 0.54.0", ] +[[package]] +name = "crc" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49fc9a695bca7f35f5f4c15cddc84415f66a74ea78eef08e90c5024f2b540e23" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccaeedb56da03b09f598226e25e80088cb4cd25f316e6e4df7d695f0feeb1403" + [[package]] name = "crossbeam" version = "0.8.5" @@ -730,6 +778,16 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -748,6 +806,16 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -854,6 +922,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "epaint" version = "0.31.1" @@ -865,18 +947,11 @@ dependencies = [ "bytemuck", "ecolor", "emath", - "epaint_default_fonts", "nohash-hasher", "parking_lot", "profiling", ] -[[package]] -name = "epaint_default_fonts" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7e7a64c02cf7a5b51e745a9e45f60660a286f151c238b9d397b3e923f5082f" - [[package]] name = "equivalent" version = "1.0.3" @@ -899,12 +974,36 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flacenc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb6da14d3c6605689b5c9ed5187a5218a6d3888e14b747bc18fd4e4bafd452bd" +dependencies = [ + "built", + "crc", + "crossbeam-channel", + "heapless", + "log", + "md-5", + "num-traits", + "rustversion", + "seq-macro", + "serde", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -971,6 +1070,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1038,12 +1147,32 @@ dependencies = [ "scroll", ] +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "serde", + "stable_deref_trait", +] + [[package]] name = "heck" version = "0.5.0" @@ -1354,6 +1483,16 @@ dependencies = [ "libc", ] +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -1415,6 +1554,12 @@ dependencies = [ "adler2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "ndk" version = "0.8.0" @@ -2276,26 +2421,43 @@ dependencies = [ [[package]] name = "satcomp" -version = "0.5.3" +version = "0.5.4" dependencies = [ - "include_dir", "nih_plug", "nih_plug_egui", "parking_lot", "rfd", "satcomp-dsp", "satcomp-ui", - "serde", +] + +[[package]] +name = "satcomp-cli" +version = "0.5.4" +dependencies = [ + "flacenc", + "satcomp-dsp", + "satdiff-dsp", + "sateq-dsp", + "satfilt-dsp", + "satlim-dsp", + "satxcomp-dsp", "serde_json", + "symphonia", ] [[package]] name = "satcomp-dsp" -version = "0.5.3" +version = "0.5.4" +dependencies = [ + "include_dir", + "serde", + "serde_json", +] [[package]] name = "satcomp-ui" -version = "0.5.3" +version = "0.5.4" dependencies = [ "nih_plug", "nih_plug_egui", @@ -2305,9 +2467,8 @@ dependencies = [ [[package]] name = "satdiff" -version = "0.1.0" +version = "0.1.1" dependencies = [ - "include_dir", "nih_plug", "nih_plug_egui", "parking_lot", @@ -2315,45 +2476,94 @@ dependencies = [ "satcomp-dsp", "satcomp-ui", "satdiff-dsp", +] + +[[package]] +name = "satdiff-dsp" +version = "0.1.1" +dependencies = [ + "include_dir", + "satcomp-dsp", "serde", "serde_json", ] [[package]] -name = "satdiff-dsp" +name = "sateq" version = "0.1.0" dependencies = [ + "nih_plug", + "nih_plug_egui", + "parking_lot", + "rfd", "satcomp-dsp", + "satcomp-ui", + "sateq-dsp", ] [[package]] -name = "satlim" -version = "0.1.1" +name = "sateq-dsp" +version = "0.1.0" dependencies = [ "include_dir", + "satcomp-dsp", + "serde", + "serde_json", +] + +[[package]] +name = "satfilt" +version = "0.1.0" +dependencies = [ "nih_plug", "nih_plug_egui", "parking_lot", "rfd", "satcomp-dsp", "satcomp-ui", - "satlim-dsp", + "satdiff-dsp", + "satfilt-dsp", +] + +[[package]] +name = "satfilt-dsp" +version = "0.1.0" +dependencies = [ + "include_dir", + "satcomp-dsp", + "satdiff-dsp", + "sateq-dsp", "serde", "serde_json", ] +[[package]] +name = "satlim" +version = "0.2.0" +dependencies = [ + "nih_plug", + "nih_plug_egui", + "parking_lot", + "rfd", + "satcomp-dsp", + "satcomp-ui", + "satlim-dsp", +] + [[package]] name = "satlim-dsp" -version = "0.1.1" +version = "0.2.0" dependencies = [ + "include_dir", "satcomp-dsp", + "serde", + "serde_json", ] [[package]] name = "satxcomp" -version = "0.1.1" +version = "0.1.2" dependencies = [ - "include_dir", "nih_plug", "nih_plug_egui", "parking_lot", @@ -2361,15 +2571,16 @@ dependencies = [ "satcomp-dsp", "satcomp-ui", "satxcomp-dsp", - "serde", - "serde_json", ] [[package]] name = "satxcomp-dsp" -version = "0.1.1" +version = "0.1.2" dependencies = [ + "include_dir", "satcomp-dsp", + "serde", + "serde_json", ] [[package]] @@ -2408,6 +2619,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -2518,12 +2735,140 @@ dependencies = [ "serde", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-pcm", + "symphonia-core", + "symphonia-format-isomp4", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-isomp4" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" +dependencies = [ + "encoding_rs", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "syn" version = "1.0.109" @@ -2743,6 +3088,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 103da18..384b3ea 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,10 +1,11 @@ [workspace] -members = ["satcomp-dsp", "satcomp-ui", "satcomp-plugin", "satxcomp-dsp", "satxcomp-plugin", "satlim-dsp", "satlim-plugin", "satdiff-dsp", "satdiff-plugin", "xtask"] +members = ["satcomp-dsp", "satcomp-ui", "satcomp-plugin", "satxcomp-dsp", "satxcomp-plugin", "satlim-dsp", "satlim-plugin", "satdiff-dsp", "satdiff-plugin", "sateq-dsp", "sateq-plugin", "satfilt-dsp", "satfilt-plugin", "satcomp-cli", "xtask"] exclude = ["vendor"] resolver = "2" [profile.release] -lto = "thin" +lto = "fat" +codegen-units = 1 strip = "symbols" [profile.profiling] diff --git a/rust/satcomp-cli/Cargo.toml b/rust/satcomp-cli/Cargo.toml new file mode 100644 index 0000000..67e9ee3 --- /dev/null +++ b/rust/satcomp-cli/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "satcomp-cli" +version = "0.5.4" +edition = "2021" +publish = false +description = "satcomp: the family's command-line renderer (docs/CLI.md)" + +[[bin]] +name = "satcomp" +path = "src/main.rs" + +[dependencies] +satcomp-dsp = { path = "../satcomp-dsp" } +satxcomp-dsp = { path = "../satxcomp-dsp" } +satlim-dsp = { path = "../satlim-dsp" } +satdiff-dsp = { path = "../satdiff-dsp" } +sateq-dsp = { path = "../sateq-dsp" } +satfilt-dsp = { path = "../satfilt-dsp" } +serde_json = "1" +# decoding: WAV, FLAC, MP3, AAC (in .m4a / .mp4 or raw ADTS .aac); MPL-2.0 +symphonia = { version = "0.5", default-features = false, features = ["wav", "pcm", "flac", "mp3", "aac", "isomp4"] } +# FLAC writing, pure Rust; Apache-2.0 +flacenc = "0.4" diff --git a/rust/satcomp-cli/src/analysis.rs b/rust/satcomp-cli/src/analysis.rs new file mode 100644 index 0000000..bae578f --- /dev/null +++ b/rust/satcomp-cli/src/analysis.rs @@ -0,0 +1,179 @@ +//! Measurements for the run summary: sample peak, RMS, true peak (ITU-R BS.1770-4 annex 2: oversampled to at least 192 kHz) +//! and integrated loudness (BS.1770-4: K-weighting, 400 ms blocks with 75 % overlap, absolute gate -70 LUFS, relative gate +//! -10 LU). Mono is one channel at weight 1, stereo two. + +fn db(x: f64) -> f64 { + if x > 0.0 { + 20.0 * x.log10() + } else { + f64::NEG_INFINITY + } +} + +/// Highest absolute sample, dBFS. +pub fn peak_dbfs(ch: &[&[f32]]) -> f64 { + db(ch.iter().flat_map(|c| c.iter()).fold(0.0f32, |m, v| m.max(v.abs())) as f64) +} + +/// RMS over every sample of every channel, dBFS. +pub fn rms_dbfs(ch: &[&[f32]]) -> f64 { + let n: usize = ch.iter().map(|c| c.len()).sum(); + if n == 0 { + return f64::NEG_INFINITY; + } + let s: f64 = ch.iter().flat_map(|c| c.iter()).map(|&v| v as f64 * v as f64).sum(); + db((s / n as f64).sqrt()) +} + +/// True peak, dBTP: the signal oversampled 4x (2x at 96 kHz and above 48 kHz, none from 192 kHz) by a windowed-sinc +/// interpolator, the highest absolute value of the original and interpolated samples. +pub fn true_peak_dbtp(ch: &[&[f32]], sr: u32) -> f64 { + let up = if sr <= 48_000 { + 4 + } else if sr <= 96_000 { + 2 + } else { + 1 + }; + if up == 1 { + return peak_dbfs(ch); + } + const PER_PHASE: usize = 24; + let taps = up * PER_PHASE; + let centre = (taps as f64 - 1.0) / 2.0; + // low-pass at the original Nyquist, Blackman window; phase p's taps interpolate at fraction p / up + let h: Vec = (0..taps) + .map(|n| { + let x = (n as f64 - centre) / up as f64; + let sinc = if x.abs() < 1e-12 { 1.0 } else { (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x) }; + let w = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * n as f64 / (taps - 1) as f64).cos() + 0.08 * (4.0 * std::f64::consts::PI * n as f64 / (taps - 1) as f64).cos(); + sinc * w + }) + .collect(); + let mut peak = 0.0f64; + for c in ch { + for &v in c.iter() { + peak = peak.max(v.abs() as f64); + } + for i in 0..c.len() + PER_PHASE { + for p in 0..up { + let mut acc = 0.0; + for k in 0..PER_PHASE { + let idx = i as isize - k as isize; + if idx >= 0 && (idx as usize) < c.len() { + acc += c[idx as usize] as f64 * h[p + k * up]; + } + } + peak = peak.max(acc.abs()); + } + } + } + db(peak) +} + +/// A biquad (direct form I) for the K-weighting. +struct Bq { + b: [f64; 3], + a: [f64; 3], + x: [f64; 2], + y: [f64; 2], +} + +impl Bq { + fn run(&mut self, x: f64) -> f64 { + let y = self.b[0] * x + self.b[1] * self.x[0] + self.b[2] * self.x[1] - self.a[1] * self.y[0] - self.a[2] * self.y[1]; + self.x = [x, self.x[0]]; + self.y = [y, self.y[0]]; + y + } +} + +/// The two K-weighting stages (high shelf, then high pass) for `sr`, from the analogue prototypes as libebur128 derives them. +fn k_weighting(sr: f64) -> [Bq; 2] { + let (f0, g, q) = (1681.974450955533, 3.999843853973347, 0.7071752369554196); + let k = (std::f64::consts::PI * f0 / sr).tan(); + let vh = 10f64.powf(g / 20.0); + let vb = vh.powf(0.4996667741545416); + let a0 = 1.0 + k / q + k * k; + let shelf = Bq { b: [(vh + vb * k / q + k * k) / a0, 2.0 * (k * k - vh) / a0, (vh - vb * k / q + k * k) / a0], a: [1.0, 2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0], x: [0.0; 2], y: [0.0; 2] }; + let (f0, q) = (38.13547087602444, 0.5003270373238773); + let k = (std::f64::consts::PI * f0 / sr).tan(); + let a0 = 1.0 + k / q + k * k; + let hp = Bq { b: [1.0, -2.0, 1.0], a: [1.0, 2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0], x: [0.0; 2], y: [0.0; 2] }; + [shelf, hp] +} + +/// Integrated loudness, LUFS; None when nothing passes the gates (silence, or shorter than one 400 ms block). +pub fn lufs_integrated(ch: &[&[f32]], sr: u32) -> Option { + let n = ch.first()?.len(); + let block = (0.4 * sr as f64).round() as usize; + let hop = block / 4; + if n < block || hop == 0 { + return None; + } + // K-weighted squares per channel, summed into 100 ms steps + let steps = n / hop; + let mut step_ms = vec![0.0f64; steps]; + for c in ch { + let mut f = k_weighting(sr as f64); + for (i, &v) in c.iter().enumerate().take(steps * hop) { + let s = f[0].run(v as f64); + let y = f[1].run(s); + step_ms[i / hop] += y * y; + } + } + let loud = |ms: f64| -0.691 + 10.0 * ms.log10(); + // each block: four steps (75 % overlap), mean square per channel summed over channels (weights 1) + let blocks: Vec = (0..=steps - 4).map(|b| step_ms[b..b + 4].iter().sum::() / block as f64).collect(); + let above_abs: Vec = blocks.iter().copied().filter(|&z| z > 0.0 && loud(z) > -70.0).collect(); + if above_abs.is_empty() { + return None; + } + let rel = loud(above_abs.iter().sum::() / above_abs.len() as f64) - 10.0; + let gated: Vec = above_abs.into_iter().filter(|&z| loud(z) > rel).collect(); + if gated.is_empty() { + return None; + } + Some(loud(gated.iter().sum::() / gated.len() as f64)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sine(f: f64, amp: f64, sr: u32, secs: f64, phase: f64) -> Vec { + (0..(sr as f64 * secs) as usize).map(|i| (amp * (2.0 * std::f64::consts::PI * f * i as f64 / sr as f64 + phase).sin()) as f32).collect() + } + + /// EBU Tech 3341 test 1: a stereo 1 kHz sine at -23 dBFS reads -23.0 LUFS (+-0.1); at another rate too. + #[test] + fn a_minus_23_dbfs_stereo_sine_reads_minus_23_lufs() { + for sr in [44100, 48000, 96000] { + let s = sine(1000.0, 10f64.powf(-23.0 / 20.0), sr, 10.0, 0.0); + let l = lufs_integrated(&[&s, &s], sr).unwrap(); + assert!((l - -23.0).abs() < 0.1, "{sr} Hz: {l}"); + } + assert!(lufs_integrated(&[&vec![0.0; 48000]], 48000).is_none(), "silence passes no gate"); + assert!(lufs_integrated(&[&vec![0.1; 1000]], 48000).is_none(), "shorter than a block"); + } + + /// A sine at a quarter of the rate, sampled 45 degrees off its peaks: every sample is at 0.707 of the peak, the true + /// peak is the full amplitude (+3 dB over the sample peak). + #[test] + fn the_true_peak_finds_what_falls_between_samples() { + let s = sine(12000.0, 0.5, 48000, 1.0, std::f64::consts::FRAC_PI_4); + let sp = peak_dbfs(&[&s]); + let tp = true_peak_dbtp(&[&s], 48000); + assert!((sp - db(0.5 * 0.7071)).abs() < 0.05, "sample peak {sp}"); + assert!((tp - db(0.5)).abs() < 0.15, "true peak {tp}"); + assert!(true_peak_dbtp(&[&s], 192000) == sp, "no oversampling from 192 kHz"); + } + + #[test] + fn peak_and_rms_of_known_signals() { + let s = sine(1000.0, 0.5, 48000, 1.0, 0.0); + assert!((peak_dbfs(&[&s]) - db(0.5)).abs() < 0.01); + assert!((rms_dbfs(&[&s]) - db(0.5 / 2f64.sqrt())).abs() < 0.01); + assert_eq!(peak_dbfs(&[&[0.0f32; 4]]), f64::NEG_INFINITY); + } +} diff --git a/rust/satcomp-cli/src/audio.rs b/rust/satcomp-cli/src/audio.rs new file mode 100644 index 0000000..e2b3f8d --- /dev/null +++ b/rust/satcomp-cli/src/audio.rs @@ -0,0 +1,502 @@ +//! Audio files, mono or stereo. In: WAV (PCM 8 / 16 / 24 / 32-bit, float 32 / 64, plain or extensible header) through the +//! reader here (exact, and the same scaling as the hosts' test tool), FLAC / MP3 / AAC (.m4a / .mp4 / ADTS .aac) through +//! Symphonia with gapless trimming. Out: WAV (16 / 24-bit PCM, 32-bit float) or FLAC (16 / 24-bit), one quantiser for both. + +/// Decoded audio: one or two channels of 32-bit float samples. +#[derive(Debug)] +pub struct Audio { + pub sr: u32, + pub ch: Vec>, + /// bits per sample of the source and whether it was float (picks the default output depth) + pub bits: u16, + pub float: bool, +} + +impl Audio { + pub fn frames(&self) -> usize { + self.ch.first().map(|c| c.len()).unwrap_or(0) + } +} + +fn u16le(b: &[u8], i: usize) -> u16 { + u16::from_le_bytes([b[i], b[i + 1]]) +} +fn u32le(b: &[u8], i: usize) -> u32 { + u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) +} + +/// Parse a WAV file's bytes. +pub fn read_wav(b: &[u8]) -> Result { + if b.len() < 12 || &b[0..4] != b"RIFF" || &b[8..12] != b"WAVE" { + return Err("not a WAV file (no RIFF / WAVE header)".into()); + } + let mut i = 12; + let mut fmt: Option<(u16, u16, u32, u16)> = None; // format tag, channels, rate, bits + let mut data: Option<&[u8]> = None; + while i + 8 <= b.len() { + let id = &b[i..i + 4]; + let len = u32le(b, i + 4) as usize; + let body = &b[i + 8..(i + 8 + len).min(b.len())]; + match id { + b"fmt " if body.len() >= 16 => { + let mut tag = u16le(body, 0); + if tag == 0xFFFE && body.len() >= 26 { + tag = u16le(body, 24); // WAVE_FORMAT_EXTENSIBLE: the sub-format GUID starts with the plain tag + } + fmt = Some((tag, u16le(body, 2), u32le(body, 4), u16le(body, 14))); + } + b"data" => data = Some(body), + _ => {} + } + i += 8 + len + (len & 1); + } + let (tag, chans, sr, bits) = fmt.ok_or("WAV file without a format chunk")?; + let data = data.ok_or("WAV file without a data chunk")?; + if chans == 0 || chans > 2 { + return Err(format!( + "{chans} channels: only mono and stereo are supported" + )); + } + let float = match (tag, bits) { + (1, 8 | 16 | 24 | 32) => false, + (3, 32 | 64) => true, + _ => { + return Err(format!( + "unsupported WAV encoding (format {tag}, {bits} bits)" + )) + } + }; + let bps = bits as usize / 8; + let frames = data.len() / (bps * chans as usize); + let mut ch = vec![Vec::with_capacity(frames); chans as usize]; + for f in 0..frames { + for (c, out) in ch.iter_mut().enumerate() { + let o = (f * chans as usize + c) * bps; + let s = &data[o..o + bps]; + let v = match (float, bits) { + (false, 8) => (s[0] as f32 - 128.0) / 128.0, + (false, 16) => i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0, + (false, 24) => { + (i32::from_le_bytes([0, s[0], s[1], s[2]]) >> 8) as f32 / 8_388_608.0 + } + (false, _) => i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32 / 2_147_483_648.0, + (true, 32) => f32::from_le_bytes([s[0], s[1], s[2], s[3]]), + (true, _) => { + f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]) as f32 + } + }; + out.push(v); + } + } + Ok(Audio { + sr, + ch, + bits, + float, + }) +} + +/// Output sample format. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Bits { + I16, + I24, + F32, +} + +impl Bits { + pub fn parse(s: &str) -> Option { + match s { + "16" => Some(Self::I16), + "24" => Some(Self::I24), + "32f" | "32" => Some(Self::F32), + _ => None, + } + } + pub fn name(self) -> &'static str { + match self { + Self::I16 => "16", + Self::I24 => "24", + Self::F32 => "32f", + } + } + /// The depth an output takes from its source when none is asked for (32-bit and 64-bit sources write float). + pub fn of_source(a: &Audio) -> Self { + match (a.float, a.bits) { + (false, 8 | 16) => Self::I16, + (false, 24) => Self::I24, + _ => Self::F32, + } + } +} + +/// Deterministic TPDF dither (same input, same bytes): a fixed-seed generator per run. +struct Tpdf(u64); +impl Tpdf { + fn uni(&mut self) -> f32 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 40) as f32 / (1u64 << 24) as f32 + } + /// triangular noise in -1..1 LSB + fn next(&mut self) -> f32 { + self.uni() - self.uni() + } +} + +/// WAV bytes for `ch` (one or two channels). Returns the bytes and the number of samples clipped at full scale. +pub fn write_wav(ch: &[Vec], sr: u32, bits: Bits, dither: bool) -> (Vec, usize) { + let n_ch = ch.len(); + let frames = ch.first().map(|c| c.len()).unwrap_or(0); + let (tag, bps): (u16, usize) = match bits { + Bits::I16 => (1, 2), + Bits::I24 => (1, 3), + Bits::F32 => (3, 4), + }; + let data_len = frames * n_ch * bps; + let mut o = Vec::with_capacity(44 + data_len); + o.extend_from_slice(b"RIFF"); + o.extend_from_slice(&((36 + data_len) as u32).to_le_bytes()); + o.extend_from_slice(b"WAVEfmt "); + o.extend_from_slice(&16u32.to_le_bytes()); + o.extend_from_slice(&tag.to_le_bytes()); + o.extend_from_slice(&(n_ch as u16).to_le_bytes()); + o.extend_from_slice(&sr.to_le_bytes()); + o.extend_from_slice(&((sr as usize * n_ch * bps) as u32).to_le_bytes()); + o.extend_from_slice(&((n_ch * bps) as u16).to_le_bytes()); + o.extend_from_slice(&((bps * 8) as u16).to_le_bytes()); + o.extend_from_slice(b"data"); + o.extend_from_slice(&(data_len as u32).to_le_bytes()); + if bits == Bits::F32 { + let mut clipped = 0; + for f in 0..frames { + for c in ch { + clipped += (c[f].abs() > 1.0) as usize; + o.extend_from_slice(&c[f].to_le_bytes()); + } + } + return (o, clipped); + } + let (q, clipped) = quantize(ch, bits, dither); + for v in q { + o.extend_from_slice(&v.to_le_bytes()[..bps]); + } + (o, clipped) +} + +/// Interleaved integer samples at 16 or 24 bits (16-bit optionally TPDF-dithered) and the number of samples past full +/// scale. WAV and FLAC both write these, so the two formats carry the same samples. +pub fn quantize(ch: &[Vec], bits: Bits, dither: bool) -> (Vec, usize) { + let frames = ch.first().map(|c| c.len()).unwrap_or(0); + let mut out = Vec::with_capacity(frames * ch.len()); + let mut clipped = 0; + let mut tp = Tpdf(0x9E37_79B9_7F4A_7C15); + for f in 0..frames { + for c in ch { + let x = c[f]; + clipped += (x.abs() > 1.0) as usize; + out.push(match bits { + Bits::I16 => { + let d = if dither { tp.next() } else { 0.0 }; + (x * 32768.0 + d).round().clamp(-32768.0, 32767.0) as i32 + } + _ => (x * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32, + }); + } + } + (out, clipped) +} + +/// FLAC bytes for `ch` at 16 or 24 bits. +pub fn write_flac(ch: &[Vec], sr: u32, bits: Bits, dither: bool) -> Result<(Vec, usize), String> { + use flacenc::component::BitRepr; + use flacenc::error::Verify; + let depth = match bits { + Bits::I16 => 16, + Bits::I24 => 24, + Bits::F32 => return Err("FLAC holds integer samples: --bits 16 or 24".into()), + }; + let (q, clipped) = quantize(ch, bits, dither); + let mut cfg = flacenc::config::Encoder::default(); + cfg.multithread = false; // one thread: the same bytes every run, whatever the machine + let cfg = cfg.into_verified().map_err(|e| format!("FLAC encoder setup: {e:?}"))?; + // the frames are driven here rather than by encode_with_fixed_block_size, which zero-pads the last frame to a full + // block (decoders that play whole frames then add up to a block of silence): the last frame holds what is left + use flacenc::source::{Context, Fill, FrameBuf}; + let fail = |e: &dyn std::fmt::Debug| format!("FLAC encoding failed: {e:?}"); + let (n_ch, bs) = (ch.len(), cfg.block_size); + // stream info first (the MD5 of every sample and the true length), then the frames + let mut ctx = Context::new(depth, n_ch, bs); + for chunk in q.chunks(bs * n_ch) { + ctx.fill_interleaved(chunk).map_err(|e| fail(&e))?; + } + let mut info = flacenc::component::Stream::new(sr as usize, n_ch, depth).map_err(|e| fail(&e))?.stream_info().clone(); + info.set_md5_digest(&ctx.md5_digest()); + info.set_total_samples(q.len() / n_ch.max(1)); + let mut stream = flacenc::component::Stream::with_stream_info(info); + let mut fb = FrameBuf::with_size(n_ch, bs).map_err(|e| fail(&e))?; + for (k, chunk) in q.chunks(bs * n_ch).enumerate() { + let len = chunk.len() / n_ch; + if len != fb.size() { + fb.resize(len); + } + fb.fill_interleaved(chunk).map_err(|e| fail(&e))?; + let frame = flacenc::encode_fixed_size_frame(&cfg, &fb, k, stream.stream_info()).map_err(|e| fail(&e))?; + stream.add_frame(frame); + } + let mut sink = flacenc::bitsink::ByteSink::new(); + stream.write(&mut sink).map_err(|e| format!("FLAC encoding failed: {e:?}"))?; + let mut out = sink.as_slice().to_vec(); + // STREAMINFO's minimum block size excludes the last block (FLAC spec); flacenc counts the short last frame in it, which + // strict decoders (Symphonia) reject. Bytes 8..10: after "fLaC" and the 4-byte metadata block header. + let frames = q.len() / n_ch.max(1); + if frames > bs && out.len() > 10 && &out[0..4] == b"fLaC" { + out[8..10].copy_from_slice(&(bs as u16).to_be_bytes()); + } + Ok((out, clipped)) +} + +/// Decode any supported file: WAV by the reader here, everything else by Symphonia (`ext` is a hint, the content decides). +pub fn read_any(b: Vec, ext: &str) -> Result { + if b.len() >= 12 && &b[0..4] == b"RIFF" && &b[8..12] == b"WAVE" { + return read_wav(&b); + } + decode(b, ext) +} + +/// MP4 boxes: (type, body) of each box in `b`. +fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> { + let mut v = Vec::new(); + let mut i = 0; + while i + 8 <= b.len() { + let size = u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as u64; + let ty = [b[i + 4], b[i + 5], b[i + 6], b[i + 7]]; + let (head, size) = match size { + 1 if i + 16 <= b.len() => (16, u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap())), + 0 => (8, (b.len() - i) as u64), + n => (8, n), + }; + if size < head as u64 || i as u64 + size > b.len() as u64 { + break; + } + v.push((ty, &b[i + head..i + size as usize])); + i += size as usize; + } + v +} + +fn child<'a>(b: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> { + boxes(b).into_iter().find(|(t, _)| t == ty).map(|(_, body)| body) +} + +/// The audio track's edit list as (samples to skip at the start, samples to keep), from an MP4 file: AAC encoders write +/// their priming delay and the true length there, which Symphonia 0.5 parses but does not apply. +fn mp4_edit(b: &[u8]) -> Option<(usize, usize)> { + let be32 = |x: &[u8], i: usize| u32::from_be_bytes([x[i], x[i + 1], x[i + 2], x[i + 3]]) as u64; + let be64 = |x: &[u8], i: usize| u64::from_be_bytes(x[i..i + 8].try_into().unwrap()); + let moov = child(b, b"moov")?; + let mvhd = child(moov, b"mvhd")?; + let movie_scale = if mvhd[0] == 1 { be32(mvhd, 20) } else { be32(mvhd, 12) }; + for (ty, trak) in boxes(moov) { + if &ty != b"trak" { + continue; + } + let mdia = child(trak, b"mdia")?; + let is_audio = child(mdia, b"hdlr").map(|h| h.len() >= 12 && &h[8..12] == b"soun").unwrap_or(false); + if !is_audio { + continue; + } + let mdhd = child(mdia, b"mdhd")?; + let media_scale = if mdhd[0] == 1 { be32(mdhd, 20) } else { be32(mdhd, 12) }; + let elst = child(child(trak, b"edts")?, b"elst")?; + let (ver, count) = (elst[0], be32(elst, 4)); + if count == 0 || movie_scale == 0 || media_scale == 0 { + return None; + } + // the first entry with a media time (an empty edit, media time -1, only delays playback: skipped here) + let mut i = 8; + for _ in 0..count { + let (dur, mt) = if ver == 1 { + (be64(elst, i), be64(elst, i + 8) as i64) + } else { + (be32(elst, i), be32(elst, i + 4) as u32 as i32 as i64) + }; + i += if ver == 1 { 20 } else { 12 }; + if mt >= 0 { + let keep = (dur as u128 * media_scale as u128 / movie_scale as u128) as usize; + return Some((mt as usize, keep)); + } + } + return None; + } + None +} + +/// Apple's gapless tag (`iTunSMPB`: " 00000000 ..." in hex), written by its AAC encoders +/// instead of an edit list: (samples to skip, samples to keep). +fn itunsmpb(b: &[u8]) -> Option<(usize, usize)> { + let at = b.windows(8).position(|w| w == b"iTunSMPB")?; + let rest = &b[at..(at + 400).min(b.len())]; + let d = rest.windows(4).position(|w| w == b"data")? + 12; // "data", type, locale + let text: String = rest[d..].iter().take_while(|c| c.is_ascii_hexdigit() || **c == b' ').map(|&c| c as char).collect(); + let f: Vec = text.split_whitespace().filter_map(|h| u64::from_str_radix(h, 16).ok()).collect(); + (f.len() >= 4 && f[3] > 0).then(|| (f[1] as usize, f[3] as usize)) +} + +fn decode(b: Vec, ext: &str) -> Result { + let edit = mp4_edit(&b).filter(|e| e.0 > 0).or_else(|| itunsmpb(&b)); + use symphonia::core::audio::SampleBuffer; + use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL}; + use symphonia::core::errors::Error; + use symphonia::core::formats::FormatOptions; + use symphonia::core::io::MediaSourceStream; + use symphonia::core::meta::MetadataOptions; + use symphonia::core::probe::Hint; + let mss = MediaSourceStream::new(Box::new(std::io::Cursor::new(b)), Default::default()); + let mut hint = Hint::new(); + if !ext.is_empty() { + hint.with_extension(ext); + } + // gapless: the encoder delay and padding of MP3 / AAC are trimmed, so a decoded file lines up with its source + let fmt_opts = FormatOptions { enable_gapless: true, ..Default::default() }; + let probed = symphonia::default::get_probe() + .format(&hint, mss, &fmt_opts, &MetadataOptions::default()) + .map_err(|_| "not a supported audio file (WAV, FLAC, MP3 or AAC)".to_string())?; + let mut format = probed.format; + let track = format.tracks().iter().find(|t| t.codec_params.codec != CODEC_TYPE_NULL).ok_or("no audio track")?.clone(); + // MP4 may leave the channel count to the first decoded frame: 0 = not known yet + let mut chans = track.codec_params.channels.map(|c| c.count()).unwrap_or(0); + if chans > 2 { + return Err(format!("{chans} channels: only mono and stereo are supported")); + } + let sr = track.codec_params.sample_rate.ok_or("unknown sample rate")?; + let bits = track.codec_params.bits_per_sample.unwrap_or(0) as u16; + let mut dec = symphonia::default::get_codecs() + .make(&track.codec_params, &DecoderOptions::default()) + .map_err(|e| format!("no decoder for this file: {e}"))?; + let mut ch: Vec> = vec![Vec::new(); chans]; + loop { + let packet = match format.next_packet() { + Ok(p) => p, + Err(Error::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => break, + Err(Error::ResetRequired) => break, + Err(e) => return Err(format!("reading failed: {e}")), + }; + if packet.track_id() != track.id { + continue; + } + let decoded = match dec.decode(&packet) { + Ok(d) => d, + Err(Error::DecodeError(_)) => continue, // a damaged frame: skipped, as players do + Err(e) => return Err(format!("decoding failed: {e}")), + }; + let n = decoded.spec().channels.count(); + if chans == 0 { + if n == 0 || n > 2 { + return Err(format!("{n} channels: only mono and stereo are supported")); + } + chans = n; + ch = vec![Vec::new(); n]; + } else if n != chans { + return Err(format!("the channel count changes inside the file ({chans} -> {n})")); + } + let mut buf = SampleBuffer::::new(decoded.capacity() as u64, *decoded.spec()); + buf.copy_interleaved_ref(decoded); + for (i, v) in buf.samples().iter().enumerate() { + ch[i % chans].push(*v); + } + } + if ch.is_empty() || ch[0].is_empty() { + return Err("no audio decoded".into()); + } + // MP4: apply the edit list or Apple's tag (the AAC priming delay off the front, the padding off the end) + if let Some((skip, keep)) = edit { + for c in ch.iter_mut() { + let s = skip.min(c.len()); + c.drain(..s); + if keep > 0 { + c.truncate(keep); + } + } + } + // lossless sources keep their depth for the output default; lossy ones (no depth) default to 24-bit + let (bits, float) = if bits == 0 { (24, false) } else { (bits, false) }; + Ok(Audio { sr, ch, bits, float }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_depth_round_trips() { + let sig: Vec = (0..64).map(|i| ((i as f32) * 0.37).sin() * 0.9).collect(); + for bits in [Bits::I16, Bits::I24, Bits::F32] { + let (b, clipped) = write_wav( + &[sig.clone(), sig.iter().map(|v| -v).collect()], + 48000, + bits, + false, + ); + assert_eq!(clipped, 0); + let a = read_wav(&b).unwrap(); + assert_eq!((a.sr, a.ch.len(), a.frames()), (48000, 2, 64)); + assert_eq!(Bits::of_source(&a), bits); + let tol = match bits { + Bits::I16 => 1.0 / 32768.0, + Bits::I24 => 1.0 / 8_388_608.0, + Bits::F32 => 0.0, + }; + for (x, y) in sig.iter().zip(&a.ch[0]) { + assert!((x - y).abs() <= tol, "{bits:?}: {x} vs {y}"); + } + } + } + + #[test] + fn dither_is_deterministic_and_small_and_clipping_is_counted() { + let sig = vec![0.25f32; 1000]; + let (a, _) = write_wav(&[sig.clone()], 44100, Bits::I16, true); + let (b, _) = write_wav(&[sig.clone()], 44100, Bits::I16, true); + assert_eq!(a, b, "same input, same bytes"); + let back = read_wav(&a).unwrap(); + assert!(back.ch[0].iter().all(|v| (v - 0.25).abs() <= 2.0 / 32768.0)); + let (_, clipped) = write_wav(&[vec![1.5, -0.5, -1.2]], 44100, Bits::F32, false); + assert_eq!(clipped, 2); + } + + #[test] + fn flac_round_trips_to_the_same_samples_as_wav_with_its_true_length() { + // an odd length: the last frame is short, not padded to a block + let l: Vec = (0..10_007).map(|i| ((i as f32) * 0.011).sin() * 0.7).collect(); + let r: Vec = l.iter().map(|v| v * -0.5).collect(); + for bits in [Bits::I16, Bits::I24] { + let (flac, _) = write_flac(&[l.clone(), r.clone()], 48000, bits, false).unwrap(); + let (wav, _) = write_wav(&[l.clone(), r.clone()], 48000, bits, false); + let a = read_any(flac, "flac").unwrap(); + let w = read_wav(&wav).unwrap(); + assert_eq!((a.sr, a.frames(), a.bits), (48000, 10_007, if bits == Bits::I16 { 16 } else { 24 })); + assert_eq!(a.ch, w.ch, "{bits:?}: FLAC and WAV carry the same samples"); + } + assert!(write_flac(&[l], 48000, Bits::F32, false).is_err(), "FLAC is integer only"); + } + + #[test] + fn apples_gapless_tag_gives_the_delay_and_the_length() { + let mut b = b"....----....meanxxxxcom.apple.iTunes....nameiTunSMPB".to_vec(); + b.extend_from_slice(b"\x00\x00\x00\x84data\x00\x00\x00\x01\x00\x00\x00\x00 00000000 00000840 00000340 000000000001D880 00000000"); + assert_eq!(itunsmpb(&b), Some((0x840, 0x1D880))); + assert_eq!(itunsmpb(b"no tag here"), None); + assert_eq!(mp4_edit(b"not an mp4"), None); + } + + #[test] + fn rejects_what_it_cannot_read() { + assert!(read_wav(b"nope").is_err()); + assert!(read_any(b"definitely not audio".to_vec(), "mp3").unwrap_err().contains("not a supported audio file")); + let (mut b, _) = write_wav(&[vec![0.0; 4], vec![0.0; 4]], 44100, Bits::I16, false); + b[22] = 6; // six channels + assert!(read_wav(&b).unwrap_err().contains("only mono and stereo")); + } +} diff --git a/rust/satcomp-cli/src/fx.rs b/rust/satcomp-cli/src/fx.rs new file mode 100644 index 0000000..c0fa8dd --- /dev/null +++ b/rust/satcomp-cli/src/fx.rs @@ -0,0 +1,592 @@ +//! The six plug-ins as chain units. Each one keeps its shared parameter values (`::spec::Values`) and drawn curves, +//! builds its engine the way the plug-in's `initialize` does and drives it the way its `process` does: the settings applied +//! every block, the sidechain port fed (silence when no key is given, as a host feeds an unrouted port), SatFilt given the +//! transport. + +use crate::value; +use satcomp_dsp::paramspec::ParamSpec; +use satcomp_dsp::shapers::Curve; +use std::path::Path; + +pub const NAMES: [&str; 6] = [ + "satcomp", "satxcomp", "satlim", "satdiff", "sateq", "satfilt", +]; + +/// The host transport a render provides: playing from the start of the file at `tempo`. +#[derive(Clone, Copy)] +pub struct Transport { + pub tempo: f64, + pub beats: f64, +} + +/// A preset source: a name (factory, then the user folder) or a file. +pub enum PresetRef<'a> { + Name(&'a str), + File(&'a Path), +} + +pub trait Unit { + fn id(&self) -> &'static str; + fn version(&self) -> &'static str; + fn specs(&self) -> &'static [ParamSpec]; + fn get(&self, slot: usize) -> Option; + /// store a plain value the way the plug-in holds a written one + fn set(&mut self, slot: usize, v: f32) -> bool; + /// apply a preset (its parameter writes and drawn curves); returns the preset's name + fn load_preset(&mut self, p: PresetRef) -> Result; + /// (name, "factory" | "user") of every preset this plug-in can load by name + fn presets(&self) -> Vec<(String, &'static str)>; + /// the id of the switch that turns the external key on, if the plug-in has one (SatEQ's bands choose EXT one by one) + fn sc_switch(&self) -> Option<&'static str> { + None + } + /// whether the plug-in has a sidechain input at all + fn has_sidechain(&self) -> bool { + false + } + /// settings that are not parameters (SatEQ's SUM | MID): Some(result) if `key` is one + fn set_extra(&mut self, _key: &str, _text: &str) -> Option> { + None + } + /// the extra settings and their values, for reports + fn extras(&self) -> Vec<(&'static str, String)> { + Vec::new() + } + /// build the engine at `sr` with the current settings (the plug-in's `initialize`) + fn start(&mut self, sr: f64); + /// latency in samples after `start` + fn latency(&self) -> u32; + /// one block in place (the plug-in's `process`) + fn process(&mut self, l: &mut [f32], r: &mut [f32], sc: Option<(&[f32], &[f32])>, t: Transport); + /// after a block: take the engine's meter peaks (gain reduction in dB, positive) into `m` (highest so far) and reset + /// them, as the plug-in's shell does after each block + fn take_meters(&mut self, _m: &mut Meters) {} + /// the current settings as a preset file of this plug-in (its JSON text and file extension) + fn capture(&self, name: &str) -> (String, &'static str); +} + +/// Meter peaks over a render, by name, in the order first seen. +#[derive(Default, Clone, Debug)] +pub struct Meters(pub Vec<(&'static str, f64)>); + +impl Meters { + pub fn max(&mut self, name: &'static str, v: f64) { + match self.0.iter_mut().find(|e| e.0 == name) { + Some(e) => e.1 = e.1.max(v), + None => self.0.push((name, v)), + } + } +} + +/// The curve every plug-in starts with: its persisted default points, sanitised. +fn plain() -> Curve { + Curve::from_points(&[(-1.0, -1.0), (1.0, 1.0)]) +} + +macro_rules! common { + ($dsp:ident, $id:literal) => { + fn id(&self) -> &'static str { + $id + } + fn version(&self) -> &'static str { + $dsp::VERSION + } + fn specs(&self) -> &'static [ParamSpec] { + $dsp::spec::SPECS + } + fn get(&self, slot: usize) -> Option { + self.v.get(slot) + } + fn set(&mut self, slot: usize, v: f32) -> bool { + self.v.set(slot, v) + } + fn load_preset(&mut self, r: PresetRef) -> Result { + use $dsp::preset; + let p = match r { + PresetRef::File(path) => preset::load_file(path).ok_or_else(|| { + format!("{}: {} is not a {} preset", $id, path.display(), $id) + })?, + PresetRef::Name(name) => { + let k = value::norm(name); + if let Some(p) = preset::factory() + .into_iter() + .find(|p| value::norm(&p.name) == k) + { + p + } else if let Some((_, path)) = preset::scan_user() + .into_iter() + .find(|(n, _)| value::norm(n) == k) + { + preset::load_file(&path).ok_or_else(|| { + format!("{}: {} is not a {} preset", $id, path.display(), $id) + })? + } else { + // factory names first; the user folder's are marked (a factory name wins when both exist) + let names: Vec = self + .presets() + .into_iter() + .map(|(n, src)| { + if src == "user" { + format!("{n} (user)") + } else { + n + } + }) + .collect(); + return Err(format!( + "{}: no preset named '{name}' (try: {})", + $id, + names.join(", ") + )); + } + } + }; + for (n, v) in p.writes() { + self.v.set(n, v); + } + self.curves = p.drawn(); + Ok(p.name.clone()) + } + fn capture(&self, name: &str) -> (String, &'static str) { + let p = $dsp::preset::Preset::capture(name, |n| self.v.get(n).unwrap_or(0.0), &self.curves); + (p.to_json(), $dsp::preset::EXT) + } + fn presets(&self) -> Vec<(String, &'static str)> { + let mut v: Vec<(String, &'static str)> = $dsp::preset::factory() + .into_iter() + .map(|p| (p.name, "factory")) + .collect(); + v.extend( + $dsp::preset::scan_user() + .into_iter() + .map(|(n, _)| (n, "user")), + ); + v + } + }; +} + +pub struct SatComp { + v: satcomp_dsp::spec::Values, + curves: Curve, + e: Option, +} +impl Unit for SatComp { + common!(satcomp_dsp, "satcomp"); + fn take_meters(&mut self, m: &mut Meters) { + let e = self.e.as_mut().expect("started"); + m.max("comp_gr_db", e.gr_pk); + m.max("upward_lift_db", e.gl_pk); + m.max("limiter_gr_db", e.lim_gr_pk); + (e.gr_pk, e.gl_pk, e.lim_gr_pk) = (0.0, 0.0, 0.0); + } + fn sc_switch(&self) -> Option<&'static str> { + Some("sc_on") + } + fn has_sidechain(&self) -> bool { + true + } + fn start(&mut self, sr: f64) { + let mut e = satcomp_dsp::Engine::new(sr); + e.match_trim = 0.0; // a fresh instance: no gain-match measurement yet + e.set_params(&satcomp_dsp::spec::to_dsp(&self.v, self.curves)); + self.e = Some(e); + } + fn latency(&self) -> u32 { + self.e.as_ref().map(|e| e.latency()).unwrap_or(0) + } + fn process( + &mut self, + l: &mut [f32], + r: &mut [f32], + sc: Option<(&[f32], &[f32])>, + _t: Transport, + ) { + let e = self.e.as_mut().expect("started"); + e.set_params(&satcomp_dsp::spec::to_dsp(&self.v, self.curves)); + e.process_sc(l, r, sc); + } +} + +pub struct SatXComp { + v: satxcomp_dsp::spec::Values, + curves: [Curve; satxcomp_dsp::NB], + e: Option, +} +impl Unit for SatXComp { + common!(satxcomp_dsp, "satxcomp"); + fn take_meters(&mut self, m: &mut Meters) { + const GR: [&str; 4] = ["lo_gr_db", "ml_gr_db", "mh_gr_db", "hi_gr_db"]; + const GL: [&str; 4] = ["lo_lift_db", "ml_lift_db", "mh_lift_db", "hi_lift_db"]; + let e = self.e.as_mut().expect("started"); + for b in 0..satxcomp_dsp::NB { + m.max(GR[b], e.gr_pk[b]); + m.max(GL[b], e.gl_pk[b]); + } + m.max("limiter_gr_db", e.lim_gr_pk); + (e.gr_pk, e.gl_pk, e.lim_gr_pk) = ([0.0; satxcomp_dsp::NB], [0.0; satxcomp_dsp::NB], 0.0); + } + fn sc_switch(&self) -> Option<&'static str> { + Some("sc_on") + } + fn has_sidechain(&self) -> bool { + true + } + fn start(&mut self, sr: f64) { + let mut e = satxcomp_dsp::XEngine::new(sr); + e.match_trim = 0.0; + e.set_params(&satxcomp_dsp::spec::to_dsp(&self.v, self.curves)); + self.e = Some(e); + } + fn latency(&self) -> u32 { + self.e.as_ref().map(|e| e.latency()).unwrap_or(0) + } + fn process( + &mut self, + l: &mut [f32], + r: &mut [f32], + sc: Option<(&[f32], &[f32])>, + _t: Transport, + ) { + let e = self.e.as_mut().expect("started"); + e.set_params(&satxcomp_dsp::spec::to_dsp(&self.v, self.curves)); + e.process_sc(l, r, sc); + } +} + +pub struct SatLim { + v: satlim_dsp::spec::Values, + curves: Curve, + e: Option, +} +impl Unit for SatLim { + common!(satlim_dsp, "satlim"); + fn take_meters(&mut self, m: &mut Meters) { + let e = self.e.as_mut().expect("started"); + m.max("clipper_gr_db", e.clip_gr_pk); + m.max("limiter_gr_db", e.gr_pk); + (e.clip_gr_pk, e.gr_pk) = (0.0, 0.0); + } + fn start(&mut self, sr: f64) { + let mut e = satlim_dsp::LimEngine::new(sr); + e.set_params(&satlim_dsp::spec::to_dsp(&self.v, self.curves)); + self.e = Some(e); + } + fn latency(&self) -> u32 { + self.e.as_ref().map(|e| e.latency()).unwrap_or(0) + } + fn process( + &mut self, + l: &mut [f32], + r: &mut [f32], + _sc: Option<(&[f32], &[f32])>, + _t: Transport, + ) { + let e = self.e.as_mut().expect("started"); + e.set_params(&satlim_dsp::spec::to_dsp(&self.v, self.curves)); + e.process(l, r); + } +} + +pub struct SatDiff { + v: satdiff_dsp::spec::Values, + curves: [Curve; 2], + e: Option, +} +impl Unit for SatDiff { + common!(satdiff_dsp, "satdiff"); + fn take_meters(&mut self, m: &mut Meters) { + let e = self.e.as_mut().expect("started"); + m.max("limiter_gr_db", e.gr_pk); + e.gr_pk = 0.0; + } + fn start(&mut self, sr: f64) { + let mut e = satdiff_dsp::DiffEngine::new(sr); + e.set_params(&satdiff_dsp::spec::to_dsp(&self.v, self.curves)); + self.e = Some(e); + } + fn latency(&self) -> u32 { + self.e.as_ref().map(|e| e.latency()).unwrap_or(0) + } + fn process( + &mut self, + l: &mut [f32], + r: &mut [f32], + _sc: Option<(&[f32], &[f32])>, + _t: Transport, + ) { + let e = self.e.as_mut().expect("started"); + e.set_params(&satdiff_dsp::spec::to_dsp(&self.v, self.curves)); + e.process(l, r); + } +} + +pub struct SatEq { + v: sateq_dsp::spec::Values, + curves: [Curve; 2 * sateq_dsp::NB], + mid_side: bool, + e: Option, +} +impl Unit for SatEq { + common!(sateq_dsp, "sateq"); + fn take_meters(&mut self, m: &mut Meters) { + // the dynamic bands' gain move at the end of each block: the deepest cut and the highest lift over the render + let e = self.e.as_ref().expect("started"); + let (cut, lift) = e.dyn_db.iter().flatten().fold((0.0f64, 0.0f64), |(c, l), &d| (c.max(-d as f64), l.max(d as f64))); + m.max("dynamics_cut_db", cut); + m.max("dynamics_lift_db", lift); + } + fn has_sidechain(&self) -> bool { + true + } + fn set_extra(&mut self, key: &str, text: &str) -> Option> { + if key != "mid_side" { + return None; + } + Some(match text.to_ascii_lowercase().as_str() { + "on" | "true" | "1" | "mid" => { + self.mid_side = true; + Ok(()) + } + "off" | "false" | "0" | "sum" => { + self.mid_side = false; + Ok(()) + } + _ => Err(format!( + "sateq: mid_side is on (MID + SIDE) or off (SUM + SIDE), not '{text}'" + )), + }) + } + fn extras(&self) -> Vec<(&'static str, String)> { + vec![( + "mid_side", + if self.mid_side { + "on".into() + } else { + "off".into() + }, + )] + } + fn start(&mut self, sr: f64) { + let mut e = sateq_dsp::Engine::new(sr); + e.set_params(&sateq_dsp::spec::to_dsp( + &self.v, + &self.curves, + self.mid_side, + )); + self.e = Some(e); + } + fn latency(&self) -> u32 { + self.e.as_ref().map(|e| e.latency()).unwrap_or(0) + } + fn process( + &mut self, + l: &mut [f32], + r: &mut [f32], + sc: Option<(&[f32], &[f32])>, + _t: Transport, + ) { + let e = self.e.as_mut().expect("started"); + e.set_params(&sateq_dsp::spec::to_dsp( + &self.v, + &self.curves, + self.mid_side, + )); + e.process_sc(l, r, sc); + } +} + +pub struct SatFilt { + v: satfilt_dsp::spec::Values, + /// the waveshapes and the modulator cycles + curves: satfilt_dsp::Drawn, + e: Option, +} +impl Unit for SatFilt { + common!(satfilt_dsp, "satfilt"); + /// the modulators' SC EXT key (no switch: a slot picks it as its source) + fn has_sidechain(&self) -> bool { + true + } + fn start(&mut self, sr: f64) { + self.e = Some(satfilt_dsp::Engine::new( + sr, + satfilt_dsp::spec::to_dsp(&self.v, self.curves), + )); + } + fn latency(&self) -> u32 { + self.e.as_ref().map(|e| e.latency()).unwrap_or(0) + } + fn process( + &mut self, + l: &mut [f32], + r: &mut [f32], + sc: Option<(&[f32], &[f32])>, + t: Transport, + ) { + let e = self.e.as_mut().expect("started"); + e.set_params(&satfilt_dsp::spec::to_dsp(&self.v, self.curves)); + e.set_transport(satfilt_dsp::Transport { + playing: true, + tempo: Some(t.tempo), + beats: Some(t.beats), + }); + e.process_sc(l, r, sc); + } +} + +/// A fresh unit of plug-in `name` at its defaults (its INIT). +pub fn make(name: &str) -> Option> { + Some(match name { + "satcomp" => Box::new(SatComp { + v: Default::default(), + curves: plain(), + e: None, + }), + "satxcomp" => Box::new(SatXComp { + v: Default::default(), + curves: [plain(); satxcomp_dsp::NB], + e: None, + }), + "satlim" => Box::new(SatLim { + v: Default::default(), + curves: plain(), + e: None, + }), + "satdiff" => Box::new(SatDiff { + v: Default::default(), + curves: [plain(); 2], + e: None, + }), + "sateq" => Box::new(SatEq { + v: Default::default(), + curves: [plain(); 2 * sateq_dsp::NB], + mid_side: false, + e: None, + }), + "satfilt" => Box::new(SatFilt { + v: Default::default(), + curves: satfilt_dsp::Drawn::plain(), + e: None, + }), + _ => return None, + }) +} + +/// The parameter `id` of `u`, or an error naming the closest ids. +pub fn find<'a>(u: &'a dyn Unit, id: &str) -> Result<&'a ParamSpec, String> { + if let Some(s) = satcomp_dsp::paramspec::find(u.specs(), id) { + return Ok(s); + } + let mut near: Vec<(usize, &str)> = u + .specs() + .iter() + .map(|s| (edit_distance(id, s.id), s.id)) + .collect(); + near.sort(); + let hint: Vec<&str> = near + .iter() + .take_while(|n| n.0 <= 3) + .take(3) + .map(|n| n.1) + .collect(); + Err(if hint.is_empty() { + format!( + "{}: unknown parameter '{id}' (satcomp params {} lists them)", + u.id(), + u.id() + ) + } else { + format!( + "{}: unknown parameter '{id}' (did you mean {}?)", + u.id(), + hint.iter() + .map(|h| format!("'{h}'")) + .collect::>() + .join(" or ") + ) + }) +} + +fn edit_distance(a: &str, b: &str) -> usize { + let b: Vec = b.chars().collect(); + let mut prev: Vec = (0..=b.len()).collect(); + for (i, ca) in a.chars().enumerate() { + let mut cur = vec![i + 1]; + for (j, cb) in b.iter().enumerate() { + cur.push( + (prev[j] + (ca != *cb) as usize) + .min(prev[j + 1] + 1) + .min(cur[j] + 1), + ); + } + prev = cur; + } + prev[b.len()] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_plug_in_starts_at_its_defaults_and_names_a_typo() { + for n in NAMES { + let u = make(n).unwrap(); + assert_eq!(u.id(), n); + for s in u.specs() { + assert_eq!(u.get(s.slot), Some(s.default), "{n}: {}", s.id); + } + } + let u = make("satlim").unwrap(); + assert!(find(&*u, "treshold") + .unwrap_err() + .contains("did you mean 'threshold'")); + assert!(find(&*u, "zzzzzzzzzz") + .unwrap_err() + .contains("satcomp params satlim")); + assert!(make("nope").is_none()); + } + + /// --save-preset then -p gives back exactly the same settings: every parameter of every plug-in, set off its default, is + /// saved and loaded into a fresh unit and must read back bit for bit. + #[test] + fn a_saved_preset_loads_back_to_the_same_settings() { + let dir = std::env::temp_dir().join(format!("satcomp-cli-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for n in NAMES { + let mut u = make(n).unwrap(); + for s in u.specs() { + let v = s.min + (s.max - s.min) * 0.37; + u.set(s.slot, v); + } + let (text, ext) = u.capture("roundtrip"); + let path = dir.join(format!("{n}.{ext}")); + std::fs::write(&path, &text).unwrap(); + let mut w = make(n).unwrap(); + w.load_preset(PresetRef::File(&path)).unwrap(); + for s in u.specs() { + let (a, b) = (u.get(s.slot).unwrap(), w.get(s.slot).unwrap()); + // parameters presets never store (performance switches) stay at the fresh unit's default + let stored = text.contains(&format!("\"{}\"", s.id)); + if stored { + assert_eq!(a.to_bits(), b.to_bits(), "{n}: {} saved {a}, loaded {b}", s.id); + } + } + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_factory_preset_loads_by_name_ignoring_case_and_punctuation() { + let mut u = make("satlim").unwrap(); + assert_eq!( + u.load_preset(PresetRef::Name("faulty_gate")).unwrap(), + "Faulty Gate" + ); + assert!(u + .load_preset(PresetRef::Name("no such preset")) + .unwrap_err() + .contains("try: INIT")); + } +} diff --git a/rust/satcomp-cli/src/main.rs b/rust/satcomp-cli/src/main.rs new file mode 100644 index 0000000..20a2dd8 --- /dev/null +++ b/rust/satcomp-cli/src/main.rs @@ -0,0 +1,808 @@ +//! satcomp: the family's command-line renderer (docs/CLI.md). Offline, headless, deterministic; written for agents and +//! scripts. Exit codes: 0 done, 1 bad arguments or settings, 2 input / output error, 3 non-finite render, 4 `diff --max` exceeded. + +mod analysis; +mod audio; +mod fx; +mod render; +mod value; + +use fx::{PresetRef, Unit}; +use satcomp_dsp::paramspec::Kind; +use serde_json::json; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +enum Fail { + Args(String), + Io(String), + NonFinite(String), + /// `diff --max`: the residual is above the limit + Diff(String), +} + +impl Fail { + fn code(&self) -> u8 { + match self { + Fail::Args(_) => 1, + Fail::Io(_) => 2, + Fail::NonFinite(_) => 3, + Fail::Diff(_) => 4, + } + } + fn msg(&self) -> &str { + match self { + Fail::Args(m) | Fail::Io(m) | Fail::NonFinite(m) | Fail::Diff(m) => m, + } + } +} + +const USAGE: &str = "usage: + satcomp -i IN.(wav|flac|mp3|m4a|aac) -fx PLUGIN[:id=value,...] [id=value ...] [-p PRESET_FILE] [-sc KEY.wav] [-fx ...] -o OUT.wav [options] + satcomp list [--json] + satcomp params PLUGIN [--json] + satcomp presets PLUGIN [--json] + satcomp diff A B [--max DB] [--json] + satcomp --version + +options: --block N (512) --tail SECONDS (0) --start T --duration T --format wav|flac --bits 16|24|32f --no-dither --tempo BPM (120) --check --json --log FILE --save-preset DIR -y -v +plug-ins: satcomp satxcomp satlim satdiff sateq satfilt (values in real units: -1dB 2k 80ms 30% 4:1 x8 on off) +see docs/CLI.md"; + +/// One `-fx` of the chain as given: the plug-in, its preset, its settings in order, its key. +struct FxArg { + name: String, + preset: Option<(String, bool)>, // (name or path, is a file) + sets: Vec<(String, String)>, + key: Option, +} + +struct Opts { + input: Option, + output: Option, + chain: Vec, + block: usize, + tail: f64, + bits: Option, + /// output format: from the extension, or --format (stdout: WAV unless --format flac) + format: Option, + dither: bool, + tempo: f64, + /// render only from `start` seconds, for `duration` seconds (a time selection) + start: f64, + duration: Option, + check: bool, + overwrite: bool, + verbose: bool, + /// the run summary as JSON on stdout + json: bool, + /// append the summary as one JSON line to this file + log: Option, + /// write each unit's resolved settings as a preset file into this folder + save_preset: Option, +} + +fn parse_args(a: &[String]) -> Result { + let mut o = Opts { + input: None, + output: None, + chain: Vec::new(), + block: 512, + tail: 0.0, + bits: None, + format: None, + dither: true, + tempo: 120.0, + start: 0.0, + duration: None, + check: false, + overwrite: false, + verbose: false, + json: false, + log: None, + save_preset: None, + }; + let mut i = 0; + let next = |i: &mut usize, flag: &str| -> Result { + *i += 1; + a.get(*i) + .cloned() + .ok_or_else(|| Fail::Args(format!("{flag} needs a value"))) + }; + let num = |s: String, flag: &str| -> Result { + s.parse::() + .ok() + .filter(|v| v.is_finite()) + .ok_or_else(|| Fail::Args(format!("{flag}: '{s}' is not a number"))) + }; + while i < a.len() { + let t = a[i].as_str(); + match t { + "-i" => o.input = Some(next(&mut i, t)?), + "-o" => o.output = Some(next(&mut i, t)?), + "-fx" => { + let spec = next(&mut i, t)?; + let (name, inline) = match spec.split_once(':') { + Some((n, rest)) => (n.to_string(), rest.to_string()), + None => (spec.clone(), String::new()), + }; + let mut f = FxArg { + name: name.to_ascii_lowercase(), + preset: None, + sets: Vec::new(), + key: None, + }; + for kv in inline.split(',').filter(|s| !s.trim().is_empty()) { + push_setting(&mut f, kv)?; + } + o.chain.push(f); + } + "-p" => { + let path = next(&mut i, t)?; + o.chain + .last_mut() + .ok_or_else(|| Fail::Args("-p must follow the -fx it belongs to".into()))? + .preset = Some((path, true)); + } + "-sc" => { + let path = next(&mut i, t)?; + o.chain + .last_mut() + .ok_or_else(|| Fail::Args("-sc must follow the -fx it belongs to".into()))? + .key = Some(PathBuf::from(path)); + } + "--block" => { + let v = num(next(&mut i, t)?, t)?; + if !(16.0..=65536.0).contains(&v) || v.fract() != 0.0 { + return Err(Fail::Args( + "--block takes a whole number of samples, 16 .. 65536".into(), + )); + } + o.block = v as usize; + } + "--tail" => { + o.tail = num(next(&mut i, t)?, t)?; + if !(0.0..=600.0).contains(&o.tail) { + return Err(Fail::Args("--tail takes 0 .. 600 seconds".into())); + } + } + "--tempo" => { + o.tempo = num(next(&mut i, t)?, t)?; + if !(20.0..=999.0).contains(&o.tempo) { + return Err(Fail::Args("--tempo takes 20 .. 999 BPM".into())); + } + } + "--start" => o.start = parse_time(&next(&mut i, t)?, t)?, + "--duration" => { + let d = parse_time(&next(&mut i, t)?, t)?; + if d <= 0.0 { + return Err(Fail::Args("--duration must be longer than 0".into())); + } + o.duration = Some(d); + } + "--bits" => { + let v = next(&mut i, t)?; + o.bits = + Some(audio::Bits::parse(&v).ok_or_else(|| { + Fail::Args(format!("--bits takes 16, 24 or 32f, not '{v}'")) + })?); + } + "--format" => { + let v = next(&mut i, t)?.to_ascii_lowercase(); + if v != "wav" && v != "flac" { + return Err(Fail::Args(format!("--format takes wav or flac, not '{v}' (convert to other formats with another tool)"))); + } + o.format = Some(v); + } + "--no-dither" => o.dither = false, + "--check" => o.check = true, + "-y" => o.overwrite = true, + "-v" | "--verbose" => o.verbose = true, + "--log" => o.log = Some(next(&mut i, t)?), + "--save-preset" => o.save_preset = Some(next(&mut i, t)?), + _ if t.contains('=') && !t.starts_with('-') => { + let f = o.chain.last_mut().ok_or_else(|| { + Fail::Args(format!( + "'{t}': a setting must follow the -fx it belongs to" + )) + })?; + push_setting(f, t)?; + } + _ => return Err(Fail::Args(format!("unknown argument '{t}'\n{USAGE}"))), + } + i += 1; + } + Ok(o) +} + +/// Seconds from `12.5`, `1:02.5` (m:ss) or `1:02:03.5` (h:mm:ss). +fn parse_time(s: &str, flag: &str) -> Result { + let bad = || Fail::Args(format!("{flag}: '{s}' is not a time (seconds, m:ss or h:mm:ss)")); + let mut secs = 0.0; + for part in s.split(':') { + let v: f64 = part.trim().parse().map_err(|_| bad())?; + if !v.is_finite() || v < 0.0 { + return Err(bad()); + } + secs = secs * 60.0 + v; + } + if s.split(':').count() > 3 { + return Err(bad()); + } + Ok(secs) +} + +fn push_setting(f: &mut FxArg, kv: &str) -> Result<(), Fail> { + let (k, v) = kv + .split_once('=') + .ok_or_else(|| Fail::Args(format!("{}: '{kv}' is not id=value", f.name)))?; + let (k, v) = (k.trim(), v.trim()); + if k == "preset" { + f.preset = Some((v.to_string(), false)); + } else { + f.sets.push((k.to_string(), v.to_string())); + } + Ok(()) +} + +/// Build the chain: each plug-in at its defaults, its preset applied, then its settings in order, its key switch turned on. +fn build_chain(o: &Opts) -> Result<(Vec>, Vec>), Fail> { + if o.chain.is_empty() { + return Err(Fail::Args(format!("no -fx given\n{USAGE}"))); + } + let mut units = Vec::new(); + let mut presets = Vec::new(); + for f in &o.chain { + let mut u = fx::make(&f.name).ok_or_else(|| { + Fail::Args(format!( + "unknown plug-in '{}' (one of: {})", + f.name, + fx::NAMES.join(", ") + )) + })?; + let mut pname = None; + if let Some((p, file)) = &f.preset { + let r = if *file { + PresetRef::File(Path::new(p)) + } else { + PresetRef::Name(p) + }; + pname = Some(u.load_preset(r).map_err(Fail::Args)?); + } + for (k, v) in &f.sets { + if let Some(res) = u.set_extra(k, v) { + res.map_err(Fail::Args)?; + continue; + } + let s = *fx::find(&*u, k).map_err(Fail::Args)?; + let x = value::parse(&s, v).map_err(|e| Fail::Args(format!("{}: {e}", f.name)))?; + u.set(s.slot, x); + } + if f.key.is_some() { + if !u.has_sidechain() { + return Err(Fail::Args(format!( + "{}: has no sidechain input (-sc is for satcomp, satxcomp and sateq)", + f.name + ))); + } + if let Some(sw) = u.sc_switch() { + let s = *fx::find(&*u, sw).map_err(Fail::Args)?; + u.set(s.slot, 1.0); + } + } + units.push(u); + presets.push(pname); + } + Ok((units, presets)) +} + +/// What differs from the plug-in's defaults, as (id, displayed value). +fn changed(u: &dyn Unit) -> Vec<(&'static str, String)> { + let mut v: Vec<(&'static str, String)> = u + .specs() + .iter() + .filter(|s| u.get(s.slot) != Some(s.default)) + .map(|s| (s.id, value::format(s, u.get(s.slot).unwrap()))) + .collect(); + v.extend(u.extras().into_iter().filter(|e| e.1 != "off")); + v +} + +fn read_input(path: &str) -> Result { + let bytes = if path == "-" { + let mut b = Vec::new(); + std::io::stdin() + .read_to_end(&mut b) + .map_err(|e| Fail::Io(format!("stdin: {e}")))?; + b + } else { + std::fs::read(path).map_err(|e| Fail::Io(format!("{path}: {e}")))? + }; + let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + audio::read_any(bytes, &ext).map_err(|e| Fail::Io(format!("{path}: {e}"))) +} + +/// The key for a unit: stereo (a mono key feeds both sides), at the input's rate. +fn read_key(path: &Path, sr: u32) -> Result<[Vec; 2], Fail> { + let a = read_input(&path.to_string_lossy())?; + if a.sr != sr { + return Err(Fail::Args(format!( + "{}: sidechain at {} Hz, the input is at {sr} Hz", + path.display(), + a.sr + ))); + } + let l = a.ch[0].clone(); + let r = a.ch.get(1).cloned().unwrap_or_else(|| l.clone()); + Ok([l, r]) +} + +fn run_render(o: Opts) -> Result<(), Fail> { + let (mut units, presets) = build_chain(&o)?; + let saved = match &o.save_preset { + Some(dir) => save_presets(dir, &units, o.overwrite)?, + None => Vec::new(), + }; + if o.check { + // resolve everything, read nothing but the settings: report and stop (no input needed) + if o.json { + let chain: Vec<_> = units.iter().zip(&presets).zip(&o.chain).map(|((u, p), f)| unit_json(&**u, p, f, None, None)).collect(); + println!("{}", serde_json::to_string_pretty(&json!({"satcomp": env!("CARGO_PKG_VERSION"), "chain": chain, "saved_presets": saved})).unwrap()); + return Ok(()); + } + for (u, p) in units.iter().zip(&presets) { + println!( + "{} {}{}", + u.id(), + u.version(), + p.as_ref() + .map(|p| format!(" preset: {p}")) + .unwrap_or_default() + ); + for (k, v) in changed(&**u) { + println!(" {k} = {v}"); + } + } + for path in &saved { + println!("saved {path}"); + } + return Ok(()); + } + let input = o.input.as_deref().ok_or_else(|| Fail::Args(format!("no -i given\n{USAGE}")))?; + let output = o + .output + .as_deref() + .ok_or_else(|| Fail::Args(format!("no -o given\n{USAGE}")))?; + let ext = Path::new(output).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let format = match (&o.format, output) { + (Some(f), _) => f.clone(), + (None, "-") => "wav".to_string(), + (None, _) if ext == "wav" || ext == "flac" => ext.clone(), + (None, _) => { + return Err(Fail::Args(format!( + "{output}: the output is WAV or FLAC (.wav / .flac, or --format); convert to other formats with another tool" + ))) + } + }; + if output == "-" && o.json { + return Err(Fail::Args("--json prints to stdout, which -o - already uses for the audio: write a file, or use --log".into())); + } + if format == "flac" && o.bits == Some(audio::Bits::F32) { + return Err(Fail::Args("FLAC holds integer samples: --bits 16 or 24".into())); + } + if output != "-" { + if Path::new(output).exists() && !o.overwrite { + return Err(Fail::Io(format!("{output} exists (-y overwrites it)"))); + } + } + let a = read_input(input)?; + // a time selection: the input and every key cut to it; the transport starts at its position + let s0 = (o.start * a.sr as f64).round() as usize; + if s0 >= a.frames() { + return Err(Fail::Args(format!( + "--start {} s is past the end of {input} ({:.2} s)", + o.start, + a.frames() as f64 / a.sr as f64 + ))); + } + let s1 = o + .duration + .map(|d| (s0 + (d * a.sr as f64).round() as usize).min(a.frames())) + .unwrap_or(a.frames()); + let cut = |c: &Vec| c[s0.min(c.len())..s1.min(c.len())].to_vec(); + let keys = o + .chain + .iter() + .map(|f| f.key.as_deref().map(|k| read_key(k, a.sr).map(|[l, r]| [cut(&l), cut(&r)])).transpose()) + .collect::, _>>()?; + let mono = a.ch.len() == 1; + let (l, r) = (cut(&a.ch[0]), cut(a.ch.get(1).unwrap_or(&a.ch[0]))); + if o.verbose { + eprintln!( + "satcomp: {input}: {} Hz, {}, {:.2} s", + a.sr, + if mono { "mono" } else { "stereo" }, + a.frames() as f64 / a.sr as f64 + ); + for (u, p) in units.iter().zip(&presets) { + let set: Vec = changed(&**u) + .into_iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + eprintln!( + "satcomp: {} {}{} {}", + u.id(), + u.version(), + p.as_ref().map(|p| format!(" [{p}]")).unwrap_or_default(), + set.join(" ") + ); + } + } + let t0 = std::time::Instant::now(); + let mut job = render::Job { + units: &mut units, + keys, + sr: a.sr, + block: o.block, + tail: (o.tail * a.sr as f64).round() as usize, + tempo: o.tempo, + pos0: s0, + }; + let done = render::render(&mut job, [&l, &r]).map_err(Fail::NonFinite)?; + let ch: Vec> = if mono { + vec![done.out[0] + .iter() + .zip(&done.out[1]) + .map(|(x, y)| 0.5 * (x + y)) + .collect()] + } else { + done.out.to_vec() + }; + let mut bits = o.bits.unwrap_or_else(|| audio::Bits::of_source(&a)); + if format == "flac" && bits == audio::Bits::F32 { + bits = audio::Bits::I24; // a float source written as FLAC without --bits: 24-bit + } + let dither = o.dither && bits == audio::Bits::I16; + let (bytes, clipped) = if format == "flac" { + audio::write_flac(&ch, a.sr, bits, dither).map_err(Fail::Io)? + } else { + audio::write_wav(&ch, a.sr, bits, dither) + }; + if output == "-" { + std::io::stdout() + .write_all(&bytes) + .map_err(|e| Fail::Io(format!("stdout: {e}")))?; + } else { + std::fs::write(output, &bytes).map_err(|e| Fail::Io(format!("{output}: {e}")))?; + } + let secs = t0.elapsed().as_secs_f64(); + if o.json || o.log.is_some() { + let src: Vec<&[f32]> = if mono { vec![&l[..]] } else { vec![&l[..], &r[..]] }; + let dst: Vec<&[f32]> = ch.iter().map(|c| &c[..]).collect(); + let chain: Vec<_> = units + .iter() + .zip(&presets) + .zip(&o.chain) + .zip(&done.meters) + .map(|(((u, p), f), m)| unit_json(&**u, p, f, Some(u.latency()), Some(m))) + .collect(); + let mut sum = json!({ + "satcomp": env!("CARGO_PKG_VERSION"), + "input": json!({"path": input, "sr": a.sr, "channels": src.len(), "seconds": l.len() as f64 / a.sr as f64, "start": o.start}).as_object().unwrap().clone().into_iter().chain(levels(&src, a.sr)).collect::>(), + "output": json!({"path": output, "format": format, "bits": bits.name(), "dither": dither, "seconds": ch[0].len() as f64 / a.sr as f64, "clipped_samples": clipped}).as_object().unwrap().clone().into_iter().chain(levels(&dst, a.sr)).collect::>(), + "chain": chain, + "latency_trimmed": done.latency, + "block": o.block, + "tail_seconds": o.tail, + "tempo": o.tempo, + "render_seconds": (secs * 1000.0).round() / 1000.0, + }); + if !saved.is_empty() { + sum["saved_presets"] = json!(saved); + } + if o.json { + println!("{}", serde_json::to_string_pretty(&sum).unwrap()); + } + if let Some(log) = &o.log { + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(log).map_err(|e| Fail::Io(format!("{log}: {e}")))?; + writeln!(f, "{}", serde_json::to_string(&sum).unwrap()).map_err(|e| Fail::Io(format!("{log}: {e}")))?; + } + } + if o.verbose { + eprintln!( + "satcomp: wrote {output} ({} {}-bit{}, latency {} trimmed, {} clipped samples) in {:.2} s", + format.to_uppercase(), + bits.name(), + if bits == audio::Bits::I16 && o.dither { + ", dithered" + } else { + "" + }, + done.latency, + clipped, + secs + ); + } + Ok(()) +} + +/// Levels of a signal for the summary: sample peak, true peak, RMS and integrated loudness (null where not measurable). +fn levels(ch: &[&[f32]], sr: u32) -> Vec<(String, serde_json::Value)> { + // rounded to 0.01 dB; `+ 0.0` turns a rounded -0.0 into 0.0 + let r = |v: f64| if v.is_finite() { json!((v * 100.0).round() / 100.0 + 0.0) } else { serde_json::Value::Null }; + vec![ + ("peak_dbfs".into(), r(analysis::peak_dbfs(ch))), + ("true_peak_dbtp".into(), r(analysis::true_peak_dbtp(ch, sr))), + ("rms_dbfs".into(), r(analysis::rms_dbfs(ch))), + ("lufs_i".into(), analysis::lufs_integrated(ch, sr).map(r).unwrap_or(serde_json::Value::Null)), + ] +} + +/// One chain unit for the summary: the plug-in, its preset, what differs from its defaults (as displayed), its key, latency +/// and meters. +fn unit_json(u: &dyn Unit, preset: &Option, f: &FxArg, latency: Option, meters: Option<&fx::Meters>) -> serde_json::Value { + let set: serde_json::Map = changed(u).into_iter().map(|(k, v)| (k.to_string(), json!(v))).collect(); + let mut v = json!({"plugin": u.id(), "version": u.version(), "preset": preset, "set": set}); + if let Some(k) = &f.key { + v["sidechain"] = json!(k.to_string_lossy()); + } + if let Some(l) = latency { + v["latency"] = json!(l); + } + if let Some(m) = meters { + for (name, val) in &m.0 { + v[*name] = json!((val * 100.0).round() / 100.0); + } + } + v +} + +/// Write each unit's settings as a preset file (`DIR/01-satcomp.satcomp`, ...) that the plug-in loads; returns the paths. +fn save_presets(dir: &str, units: &[Box], overwrite: bool) -> Result, Fail> { + std::fs::create_dir_all(dir).map_err(|e| Fail::Io(format!("{dir}: {e}")))?; + let mut out = Vec::new(); + for (i, u) in units.iter().enumerate() { + let stem = format!("{:02}-{}", i + 1, u.id()); + let (text, ext) = u.capture(&stem); + let path = Path::new(dir).join(format!("{stem}.{ext}")); + if path.exists() && !overwrite { + return Err(Fail::Io(format!("{} exists (-y overwrites it)", path.display()))); + } + std::fs::write(&path, text).map_err(|e| Fail::Io(format!("{}: {e}", path.display())))?; + out.push(path.to_string_lossy().into_owned()); + } + Ok(out) +} + +/// `satcomp diff A B [--max DB]`: the null test. Same rate and channel count required; the common length is compared. +fn cmd_diff(a: &[String], json_out: bool) -> Result<(), Fail> { + let (pa, pb) = match (a.get(1), a.get(2)) { + (Some(x), Some(y)) => (x.clone(), y.clone()), + _ => return Err(Fail::Args("usage: satcomp diff A B [--max DB] [--json]".into())), + }; + let max: Option = match a.iter().position(|x| x == "--max") { + Some(i) => Some(a.get(i + 1).and_then(|v| v.parse().ok()).ok_or_else(|| Fail::Args("--max takes a level in dBFS, e.g. --max -120".into()))?), + None => None, + }; + let (x, y) = (read_input(&pa)?, read_input(&pb)?); + if x.sr != y.sr { + return Err(Fail::Args(format!("{pa} is at {} Hz, {pb} at {} Hz", x.sr, y.sr))); + } + if x.ch.len() != y.ch.len() { + return Err(Fail::Args(format!("{pa} has {} channels, {pb} {}", x.ch.len(), y.ch.len()))); + } + let n = x.frames().min(y.frames()); + let (mut peak, mut sum, mut worst) = (0.0f64, 0.0f64, (0usize, 0usize)); + let mut identical = x.frames() == y.frames(); + for c in 0..x.ch.len() { + for i in 0..n { + let d = x.ch[c][i] as f64 - y.ch[c][i] as f64; + identical &= x.ch[c][i].to_bits() == y.ch[c][i].to_bits(); + sum += d * d; + if d.abs() > peak { + peak = d.abs(); + worst = (i, c); + } + } + } + let r = |v: f64| if v > 0.0 { json!((20.0 * v.log10() * 100.0).round() / 100.0) } else { serde_json::Value::Null }; + let rms = if n > 0 { (sum / (n * x.ch.len()) as f64).sqrt() } else { 0.0 }; + let over = max.map(|m| peak > 0.0 && 20.0 * peak.log10() > m).unwrap_or(false); + if json_out { + let v = json!({"a": pa, "b": pb, "identical": identical, "frames": [x.frames(), y.frames()], "compared": n, "sr": x.sr, + "residual_peak_dbfs": r(peak), "residual_rms_dbfs": r(rms), + "worst": if peak > 0.0 { json!({"frame": worst.0, "seconds": worst.0 as f64 / x.sr as f64, "channel": worst.1}) } else { serde_json::Value::Null }, + "max_dbfs": max, "over_max": over}); + println!("{}", serde_json::to_string_pretty(&v).unwrap()); + } else if identical { + println!("identical ({} frames)", n); + } else { + let len = if x.frames() != y.frames() { format!(", lengths {} / {} frames (compared {n})", x.frames(), y.frames()) } else { String::new() }; + if peak > 0.0 { + println!("residual peak {:.2} dBFS, RMS {:.2} dBFS, worst at {:.4} s (frame {}, channel {}){len}", 20.0 * peak.log10(), 20.0 * rms.log10(), worst.0 as f64 / x.sr as f64, worst.0, worst.1); + } else { + println!("the common {n} frames are identical{len}"); + } + } + if over { + return Err(Fail::Diff(format!("residual peak {:.2} dBFS is above --max {}", 20.0 * peak.log10(), max.unwrap()))); + } + Ok(()) +} + +fn spec_json(s: &satcomp_dsp::paramspec::ParamSpec) -> serde_json::Value { + let kind = match s.kind { + Kind::Float => "float", + Kind::Int => "int", + Kind::Bool => "switch", + }; + json!({"id": s.id, "name": s.name, "kind": kind, "min": s.min, "max": s.max, "default": s.default, "default_text": value::format(s, s.default), "step": s.step, "unit": s.unit, "choices": s.choices}) +} + +fn cmd_list(json_out: bool) { + let all: Vec<_> = fx::NAMES.iter().map(|n| fx::make(n).unwrap()).collect(); + if json_out { + let v: Vec<_> = all.iter().map(|u| json!({"plugin": u.id(), "version": u.version(), "parameters": u.specs().len(), "sidechain": u.has_sidechain()})).collect(); + println!("{}", serde_json::to_string_pretty(&v).unwrap()); + } else { + for u in &all { + println!( + "{:<9} {:<7} {:>3} parameters{}", + u.id(), + u.version(), + u.specs().len(), + if u.has_sidechain() { ", sidechain" } else { "" } + ); + } + } +} + +fn plugin_arg(a: &[String]) -> Result, Fail> { + let n = a + .get(1) + .ok_or_else(|| Fail::Args(format!("which plug-in? one of: {}", fx::NAMES.join(", "))))?; + fx::make(&n.to_ascii_lowercase()).ok_or_else(|| { + Fail::Args(format!( + "unknown plug-in '{n}' (one of: {})", + fx::NAMES.join(", ") + )) + }) +} + +fn cmd_params(a: &[String], json_out: bool) -> Result<(), Fail> { + let u = plugin_arg(a)?; + if json_out { + let mut v: Vec<_> = u.specs().iter().map(spec_json).collect(); + for (k, val) in u.extras() { + v.push(json!({"id": k, "kind": "setting", "default_text": val, "note": "not a parameter: a plug-in preference presets do not store"})); + } + println!( + "{}", + serde_json::to_string_pretty( + &json!({"plugin": u.id(), "version": u.version(), "parameters": v}) + ) + .unwrap() + ); + return Ok(()); + } + println!("{} {}", u.id(), u.version()); + for s in u.specs() { + let range = match s.kind { + Kind::Bool => "on | off".to_string(), + Kind::Int if !s.choices.is_empty() => s.choices.join(" | "), + _ => format!("{} .. {}", value::format(s, s.min), value::format(s, s.max)), + }; + println!( + " {:<16} {:<22} default {:<12} {}", + s.id, + s.name, + value::format(s, s.default), + range + ); + } + for (k, val) in u.extras() { + println!( + " {k:<16} {:<22} default {val:<12} on | off (a preference, not stored in presets)", + "(setting)" + ); + } + Ok(()) +} + +fn cmd_presets(a: &[String], json_out: bool) -> Result<(), Fail> { + let u = plugin_arg(a)?; + let p = u.presets(); + if json_out { + let v: Vec<_> = p + .iter() + .map(|(n, src)| json!({"name": n, "source": src})) + .collect(); + println!( + "{}", + serde_json::to_string_pretty(&json!({"plugin": u.id(), "presets": v})).unwrap() + ); + } else { + for (n, src) in p { + println!("{n:<28} {src}"); + } + } + Ok(()) +} + +fn run(a: Vec) -> Result<(), Fail> { + let json_out = a.iter().any(|x| x == "--json"); + let rest: Vec = a.iter().filter(|x| *x != "--json").cloned().collect(); + match rest.first().map(|s| s.as_str()) { + None | Some("-h") | Some("--help") | Some("help") => { + println!("{USAGE}"); + Ok(()) + } + Some("--version") | Some("-V") => { + println!("satcomp {}", env!("CARGO_PKG_VERSION")); + for n in fx::NAMES { + println!(" {n} {}", fx::make(n).unwrap().version()); + } + Ok(()) + } + Some("list") => { + cmd_list(json_out); + Ok(()) + } + Some("params") => cmd_params(&rest, json_out), + Some("presets") => cmd_presets(&rest, json_out), + Some("diff") => cmd_diff(&rest, json_out), + _ => { + let mut o = parse_args(&rest)?; + o.json = json_out; + run_render(o) + } + } +} + +/// Stack for the work thread: the engines are large structs built in place (several MB for SatEQ in a debug build). +pub const STACK: usize = 64 << 20; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let r = std::thread::Builder::new() + .stack_size(STACK) + .spawn(move || run(args)) + .expect("work thread") + .join() + .unwrap_or_else(|_| Err(Fail::Io("internal error (panic)".into()))); + match r { + Ok(()) => ExitCode::SUCCESS, + Err(f) => { + eprintln!("satcomp: {}", f.msg()); + ExitCode::from(f.code()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn times_in_seconds_minutes_or_hours() { + assert_eq!(parse_time("12.5", "--start").ok(), Some(12.5)); + assert_eq!(parse_time("1:02.5", "--start").ok(), Some(62.5)); + assert_eq!(parse_time("1:00:03", "--start").ok(), Some(3603.0)); + for bad in ["", "abc", "-1", "1:2:3:4", "1::2"] { + assert!(parse_time(bad, "--start").is_err(), "{bad}"); + } + } + + #[test] + fn a_setting_before_any_fx_and_an_unknown_flag_are_errors() { + let a = |v: &[&str]| parse_args(&v.iter().map(|s| s.to_string()).collect::>()); + assert!(matches!(a(&["thresh=1"]), Err(Fail::Args(_)))); + assert!(matches!(a(&["--nope"]), Err(Fail::Args(_)))); + let o = a(&["-i", "x.wav", "-fx", "satlim:ceiling=-1,preset=Baked", "os=x8", "-fx", "sateq", "-o", "y.wav", "--start", "1:00", "--duration", "5"]).ok().unwrap(); + assert_eq!(o.chain.len(), 2); + assert_eq!(o.chain[0].sets, vec![("ceiling".to_string(), "-1".to_string()), ("os".to_string(), "x8".to_string())]); + assert_eq!(o.chain[0].preset, Some(("Baked".to_string(), false))); + assert_eq!((o.start, o.duration), (60.0, Some(5.0))); + } +} diff --git a/rust/satcomp-cli/src/render.rs b/rust/satcomp-cli/src/render.rs new file mode 100644 index 0000000..1400d63 --- /dev/null +++ b/rust/satcomp-cli/src/render.rs @@ -0,0 +1,179 @@ +//! The offline render: the chain runs block by block like a host (full blocks from sample 0, the input zero-padded past its +//! end), every unit in place on the same buffer, and the chain's latency (the sum of each unit's) is trimmed off the front. + +use crate::fx::{Meters, Transport, Unit}; + +pub struct Job<'a> { + pub units: &'a mut [Box], + /// per unit: an external key (two channels), if one was given + pub keys: Vec; 2]>>, + pub sr: u32, + pub block: usize, + /// extra samples rendered past the input + pub tail: usize, + pub tempo: f64, + /// where the input starts in the source (a time selection): the transport counts from there + pub pos0: usize, +} + +pub struct Rendered { + pub out: [Vec; 2], + pub latency: u32, + /// per unit: its meter peaks over the render (gain reduction, dB) + pub meters: Vec, +} + +/// Render stereo `input` through the chain. Fails on non-finite output (the file is then not written). +pub fn render(job: &mut Job, input: [&[f32]; 2]) -> Result { + let sr = job.sr as f64; + for u in job.units.iter_mut() { + u.start(sr); + } + let latency: u32 = job.units.iter().map(|u| u.latency()).sum(); + let n = input[0].len(); + let want = n + job.tail; + let total = want + latency as usize; + let b = job.block; + let (mut l, mut r) = (vec![0.0f32; b], vec![0.0f32; b]); + let silent = vec![0.0f32; b]; + let mut key = [vec![0.0f32; b], vec![0.0f32; b]]; + let mut out = [Vec::with_capacity(total + b), Vec::with_capacity(total + b)]; + let mut pos = 0usize; + let mut meters = vec![Meters::default(); job.units.len()]; + while pos < total { + for i in 0..b { + l[i] = input[0].get(pos + i).copied().unwrap_or(0.0); + r[i] = input[1].get(pos + i).copied().unwrap_or(0.0); + } + let t = Transport { + tempo: job.tempo, + beats: (job.pos0 + pos) as f64 / sr * job.tempo / 60.0, + }; + for ((u, k), m) in job.units.iter_mut().zip(&job.keys).zip(meters.iter_mut()) { + let sc = if !u.has_sidechain() { + None + } else if let Some(kc) = k { + for c in 0..2 { + for i in 0..b { + key[c][i] = kc[c].get(pos + i).copied().unwrap_or(0.0); + } + } + Some((&key[0][..], &key[1][..])) + } else { + // a host feeds an unrouted sidechain port with silence: so does the CLI (parity) + Some((&silent[..], &silent[..])) + }; + u.process(&mut l, &mut r, sc, t); + u.take_meters(m); + } + out[0].extend_from_slice(&l); + out[1].extend_from_slice(&r); + pos += b; + } + let lat = latency as usize; + let out = [ + out[0][lat..lat + want].to_vec(), + out[1][lat..lat + want].to_vec(), + ]; + if out.iter().any(|c| c.iter().any(|v| !v.is_finite())) { + return Err( + "the render produced non-finite samples (NaN or infinity); nothing was written".into(), + ); + } + Ok(Rendered { out, latency, meters }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fx; + + fn chain(names: &[&str]) -> Vec> { + names.iter().map(|n| fx::make(n).unwrap()).collect() + } + + fn input() -> [Vec; 2] { + let l: Vec = (0..9000) + .map(|i| 0.5 * ((i as f32) * 0.03).sin() * if i % 2000 < 40 { 1.6 } else { 1.0 }) + .collect(); + let r: Vec = l.iter().map(|v| v * 0.8).collect(); + [l, r] + } + + /// the engines need the binary's work-thread stack, not a test thread's 2 MB + fn big(f: F) { + std::thread::Builder::new() + .stack_size(crate::STACK) + .spawn(f) + .unwrap() + .join() + .unwrap(); + } + + #[test] + fn a_chain_renders_the_input_length_deterministically_with_its_latency_trimmed() { + big(|| { + let x = input(); + let run = |names: &[&str], tail: usize| { + let mut u = chain(names); + let keys = vec![None; u.len()]; + let mut j = Job { + units: &mut u, + keys, + sr: 48000, + block: 512, + tail, + tempo: 120.0, + pos0: 0, + }; + render(&mut j, [&x[0], &x[1]]).unwrap() + }; + let a = run(&["sateq", "satcomp", "satlim"], 0); + let b = run(&["sateq", "satcomp", "satlim"], 0); + assert_eq!(a.out, b.out, "deterministic"); + assert_eq!(a.out[0].len(), x[0].len()); + assert!( + a.latency > 0, + "SatComp's lookahead and SatLim's limiter report latency" + ); + assert_eq!( + run(&["satlim"], 480).out[0].len(), + x[0].len() + 480, + "the tail is rendered past the input" + ); + // SatEQ at its defaults passes audio through untouched: the trimmed output lines up with the input sample for sample + let eq = run(&["sateq"], 0); + assert_eq!(eq.latency, 0); + assert_eq!(eq.out[0], x[0]); + }); + } + + #[test] + fn a_key_reaches_the_compressor_and_no_key_is_a_silent_one() { + big(|| { + let x = input(); + let render_with = |key: Option<[Vec; 2]>| { + let mut u = chain(&["satcomp"]); + let s = *fx::find(&*u[0], "sc_on").unwrap(); + u[0].set(s.slot, 1.0); + let t = *fx::find(&*u[0], "thresh").unwrap(); + u[0].set(t.slot, -30.0); + let mut j = Job { + units: &mut u, + keys: vec![key], + sr: 48000, + block: 512, + tail: 0, + tempo: 120.0, + pos0: 0, + }; + render(&mut j, [&x[0], &x[1]]).unwrap().out + }; + let silent_key = render_with(None); + let loud_key = + render_with(Some([x[0].iter().map(|v| v * 1.9).collect(), x[1].clone()])); + let rms = |c: &[f32]| (c.iter().map(|v| v * v).sum::() / c.len() as f32).sqrt(); + assert!(rms(&loud_key[0]) < rms(&silent_key[0]) * 0.9, "a loud key pulls the gain down; a silent one (no -sc, as a host's unrouted port) does not"); + }); + } +} diff --git a/rust/satcomp-cli/src/value.rs b/rust/satcomp-cli/src/value.rs new file mode 100644 index 0000000..550c2e3 --- /dev/null +++ b/rust/satcomp-cli/src/value.rs @@ -0,0 +1,247 @@ +//! Values on the command line: parsed in the parameter's own unit (`-1dB`, `2k`, `80ms`, `30%`, `4:1`, choice names, on / off) +//! and formatted back the way the plug-in displays them. + +use satcomp_dsp::paramspec::{Kind, ParamSpec}; + +/// A choice name or typed value reduced to lowercase letters, digits and `.` / `-` / `+` signs of numbers, so `L-SHF`, `l-shf` +/// and `lshf` compare equal (punctuation and spaces never matter in a name). +pub fn norm(s: &str) -> String { + s.chars() + .filter(|c| c.is_ascii_alphanumeric()) + .map(|c| c.to_ascii_lowercase()) + .collect() +} + +/// `text` as a plain value of `s` (in its unit). Out of range is an error, never clamped, so a typo cannot pass silently. +pub fn parse(s: &ParamSpec, text: &str) -> Result { + let t = text.trim(); + let v = match s.kind { + Kind::Bool => match t.to_ascii_lowercase().as_str() { + "on" | "true" | "yes" | "1" => 1.0, + "off" | "false" | "no" | "0" => 0.0, + _ => return Err(format!("{}: '{t}' is not a switch value (on / off)", s.id)), + }, + Kind::Int => { + let k = norm(t); + if let Some(i) = s.choices.iter().position(|c| norm(c) == k) { + s.min + i as f32 + } else { + match t.parse::() { + Ok(n) if n.fract() == 0.0 => n, + _ => return Err(format!("{}: '{t}' is not one of {}", s.id, choices_hint(s))), + } + } + } + Kind::Float => number_with_unit(s, t)?, + }; + if !(v >= s.min && v <= s.max) { + return Err(format!( + "{}: {t} is outside {} .. {}", + s.id, + format(s, s.min), + format(s, s.max) + )); + } + Ok(v) +} + +fn choices_hint(s: &ParamSpec) -> String { + if s.choices.is_empty() { + format!("{} .. {}", s.min, s.max) + } else { + s.choices.join(", ") + } +} + +/// A number with an optional unit suffix that fits the parameter's unit (`k` / `kHz` for Hz, `s` for ms, `:1` for a ratio). +fn number_with_unit(s: &ParamSpec, t: &str) -> Result { + let split = t + .char_indices() + .find(|&(i, c)| { + i > 0 + && !(c.is_ascii_digit() + || c == '.' + || ((c == 'e' || c == 'E') + && t[i + 1..] + .starts_with(|d: char| d.is_ascii_digit() || d == '-' || d == '+')) + || ((c == '-' || c == '+') && matches!(t.as_bytes()[i - 1], b'e' | b'E'))) + }) + .map(|(i, _)| i) + .unwrap_or(t.len()); + let (num, suffix) = t.split_at(split); + let n: f32 = num + .trim() + .parse() + .map_err(|_| format!("{}: '{t}' is not a number", s.id))?; + let suf = suffix.trim().to_ascii_lowercase(); + let unit = s.unit.to_ascii_lowercase(); + let scale = match (unit.as_str(), suf.as_str()) { + (_, "") => 1.0, + (u, x) if u == x => 1.0, + ("hz", "k") | ("hz", "khz") => 1000.0, + ("ms", "s") => 1000.0, + ("", ":1") => 1.0, + _ => { + let want = if s.unit.is_empty() { + "no unit".to_string() + } else { + s.unit.to_string() + }; + return Err(format!( + "{}: '{t}' has the wrong unit (this parameter takes {want})", + s.id + )); + } + }; + Ok(n * scale) +} + +/// The value as the plug-in shows it: a choice name, on / off, or the number at the parameter's resolution with its unit. +pub fn format(s: &ParamSpec, v: f32) -> String { + match s.kind { + Kind::Bool => (if v > 0.5 { "on" } else { "off" }).to_string(), + Kind::Int => { + let i = (v - s.min).round() as usize; + s.choices + .get(i) + .map(|c| c.to_string()) + .unwrap_or_else(|| format!("{}", v.round() as i64)) + } + Kind::Float => { + let dec = if s.step <= 0.0 { + 2 + } else { + ((-s.step.log10()).ceil().max(0.0)) as usize + }; + if s.unit.is_empty() { + format!("{v:.dec$}") + } else { + format!("{v:.dec$} {}", s.unit) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use satcomp_dsp::paramspec::Kind; + + const DB: ParamSpec = ParamSpec { + slot: 1, + id: "ceiling", + name: "Ceiling", + kind: Kind::Float, + min: -24.0, + max: 0.0, + default: -0.3, + step: 0.1, + unit: "dB", + choices: &[], + }; + const HZ: ParamSpec = ParamSpec { + slot: 2, + id: "freq", + name: "Freq", + kind: Kind::Float, + min: 20.0, + max: 20000.0, + default: 1000.0, + step: 1.0, + unit: "Hz", + choices: &[], + }; + const MS: ParamSpec = ParamSpec { + slot: 3, + id: "release", + name: "Release", + kind: Kind::Float, + min: 5.0, + max: 500.0, + default: 80.0, + step: 1.0, + unit: "ms", + choices: &[], + }; + const RATIO: ParamSpec = ParamSpec { + slot: 4, + id: "ratio", + name: "Ratio", + kind: Kind::Float, + min: 1.0, + max: 20.0, + default: 4.0, + step: 0.1, + unit: "", + choices: &[], + }; + const TYPE: ParamSpec = ParamSpec { + slot: 5, + id: "s1_b1_type", + name: "Type", + kind: Kind::Int, + min: 0.0, + max: 3.0, + default: 2.0, + step: 1.0, + unit: "", + choices: &["HPF", "LPF", "L-SHF", "H-SHF"], + }; + const ON: ParamSpec = ParamSpec { + slot: 6, + id: "lim_on", + name: "Limiter", + kind: Kind::Bool, + min: 0.0, + max: 1.0, + default: 1.0, + step: 1.0, + unit: "", + choices: &[], + }; + + #[test] + fn numbers_take_their_own_unit_and_its_spellings() { + assert_eq!(parse(&DB, "-1").unwrap(), -1.0); + assert_eq!(parse(&DB, "-1dB").unwrap(), -1.0); + assert_eq!(parse(&DB, "-1.5 db").unwrap(), -1.5); + assert_eq!(parse(&HZ, "2k").unwrap(), 2000.0); + assert_eq!(parse(&HZ, "2.5kHz").unwrap(), 2500.0); + assert_eq!(parse(&HZ, "1e3").unwrap(), 1000.0); + assert_eq!(parse(&MS, "0.08s").unwrap(), 80.0); + assert_eq!(parse(&RATIO, "4:1").unwrap(), 4.0); + assert!(parse(&DB, "2k").unwrap_err().contains("wrong unit")); + assert!(parse(&MS, "80Hz").unwrap_err().contains("takes ms")); + assert!(parse(&DB, "abc").unwrap_err().contains("not a number")); + } + + #[test] + fn out_of_range_is_an_error_not_a_clamp() { + assert!(parse(&DB, "+1dB") + .unwrap_err() + .contains("outside -24.0 dB .. 0.0 dB")); + assert!(parse(&HZ, "30k").is_err()); + } + + #[test] + fn choices_by_name_ignoring_case_and_punctuation_or_by_index() { + assert_eq!(parse(&TYPE, "l-shf").unwrap(), 2.0); + assert_eq!(parse(&TYPE, "LSHF").unwrap(), 2.0); + assert_eq!(parse(&TYPE, "1").unwrap(), 1.0); + assert!(parse(&TYPE, "bell") + .unwrap_err() + .contains("HPF, LPF, L-SHF, H-SHF")); + assert!(parse(&TYPE, "4").is_err()); + assert_eq!(parse(&ON, "off").unwrap(), 0.0); + assert!(parse(&ON, "maybe").is_err()); + } + + #[test] + fn formatting_follows_the_display() { + assert_eq!(format(&DB, -1.0), "-1.0 dB"); + assert_eq!(format(&HZ, 2000.0), "2000 Hz"); + assert_eq!(format(&RATIO, 4.0), "4.0"); + assert_eq!(format(&TYPE, 3.0), "H-SHF"); + assert_eq!(format(&ON, 0.0), "off"); + } +} diff --git a/rust/satcomp-dsp/Cargo.toml b/rust/satcomp-dsp/Cargo.toml index 0c81c4b..2d52953 100644 --- a/rust/satcomp-dsp/Cargo.toml +++ b/rust/satcomp-dsp/Cargo.toml @@ -1,10 +1,14 @@ [package] name = "satcomp-dsp" -version = "0.5.3" +version = "0.5.4" edition = "2021" publish = false [dependencies] +# the preset format (preset.rs), shared with the plug-in and the CLI +serde = { version = "1", features = ["derive"] } +serde_json = "1" +include_dir = "0.7" [features] # dev-only: environment-variable overrides of the limiter constants (offline sweeps) diff --git a/rust/satcomp-plugin/presets/Drums_Baked.json b/rust/satcomp-dsp/presets/Drums_Baked.json similarity index 100% rename from rust/satcomp-plugin/presets/Drums_Baked.json rename to rust/satcomp-dsp/presets/Drums_Baked.json diff --git a/rust/satcomp-plugin/presets/Drums_Bricked.json b/rust/satcomp-dsp/presets/Drums_Bricked.json similarity index 100% rename from rust/satcomp-plugin/presets/Drums_Bricked.json rename to rust/satcomp-dsp/presets/Drums_Bricked.json diff --git a/rust/satcomp-plugin/presets/Drums_Cooked.json b/rust/satcomp-dsp/presets/Drums_Cooked.json similarity index 100% rename from rust/satcomp-plugin/presets/Drums_Cooked.json rename to rust/satcomp-dsp/presets/Drums_Cooked.json diff --git a/rust/satcomp-plugin/presets/Drums_Cruncher.json b/rust/satcomp-dsp/presets/Drums_Cruncher.json similarity index 100% rename from rust/satcomp-plugin/presets/Drums_Cruncher.json rename to rust/satcomp-dsp/presets/Drums_Cruncher.json diff --git a/rust/satcomp-plugin/presets/Drums_Thicc.json b/rust/satcomp-dsp/presets/Drums_Thicc.json similarity index 100% rename from rust/satcomp-plugin/presets/Drums_Thicc.json rename to rust/satcomp-dsp/presets/Drums_Thicc.json diff --git a/rust/satcomp-plugin/presets/Drums_Tubed.json b/rust/satcomp-dsp/presets/Drums_Tubed.json similarity index 100% rename from rust/satcomp-plugin/presets/Drums_Tubed.json rename to rust/satcomp-dsp/presets/Drums_Tubed.json diff --git a/rust/satcomp-plugin/presets/README.md b/rust/satcomp-dsp/presets/README.md similarity index 100% rename from rust/satcomp-plugin/presets/README.md rename to rust/satcomp-dsp/presets/README.md diff --git a/rust/satcomp-dsp/src/engine.rs b/rust/satcomp-dsp/src/engine.rs index baaf65b..5f773af 100644 --- a/rust/satcomp-dsp/src/engine.rs +++ b/rust/satcomp-dsp/src/engine.rs @@ -233,6 +233,8 @@ pub struct Engine { mn_bk: f64, sc_o: f64, sc_p: f64, + /// scope bucket: output peak with the upward compressor's lift taken back off (equals `sc_o` when nothing lifts) + sc_m: f64, sc_n: u32, sc_len: u32, @@ -241,6 +243,9 @@ pub struct Engine { pub clip_f: bool, pub gr_blk: f64, pub gr_pk: f64, + /// upward compressor lift (dB, positive): block peak and the peak since the shell last took it, like `gr_blk` / `gr_pk` + pub gl_blk: f64, + pub gl_pk: f64, /// Peak limiter gain reduction (dB, positive) since the shell last took it. pub lim_gr_pk: f64, pub vz_blk: f64, @@ -320,12 +325,15 @@ impl Engine { mn_bk: 0.0, sc_o: 0.0, sc_p: 0.0, + sc_m: 0.0, sc_n: 0, sc_len: 96, opk: [0.0; 2], clip_f: false, gr_blk: 0.0, gr_pk: 0.0, + gl_blk: 0.0, + gl_pk: 0.0, lim_gr_pk: 0.0, vz_blk: 0.0, vz_lv: 0.0, @@ -494,6 +502,8 @@ impl Engine { 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.gl_pk = self.gl_pk.max(self.gl_blk); + self.gl_blk = 0.0; 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; @@ -584,7 +594,7 @@ impl Engine { let co = self.comp.tick(cc, cd, if sc_act { Some(scv) } else { None }); self.vz_blk = self.vz_blk.max(co.level); self.vz_bk = self.vz_bk.max(co.level); - let (y, g) = (co.y, co.g); + let (y, g, lift) = (co.y, co.g, co.lift); // ------------------------------------------------ OUT let mut o = [0.0f64; 2]; @@ -635,13 +645,16 @@ impl Engine { self.fms += ((out[0] * out[0] + out[1] * out[1]) * 0.5 + DENORM - self.fms) * self.fms_c; let gm = g[0].max(g[1]); self.gr_blk = self.gr_blk.max(gm); - // scope bucket: output peak, and the same with the gain reduction added back + let lm = lift[0].max(lift[1]); + self.gl_blk = self.gl_blk.max(lm); + // scope bucket: output peak, the same with the upward lift taken off, and with the gain reduction added back let ao = out[0].abs().max(out[1].abs()); self.sc_o = self.sc_o.max(ao); + self.sc_m = self.sc_m.max(ao * (-lm * LN10_20).exp()); self.sc_p = self.sc_p.max(ao * (gm * 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.scope.push3(self.sc_o as f32, self.sc_m as f32, self.sc_p as f32); // the animation values of this bucket (audio time): peaks are maxima, the difference is the state at the end let diff = DB_POW * (self.pms.max(1e-12) / self.ims.max(1e-12)).ln(); self.meter.push([self.sat.bk as f32, self.vz_bk as f32, self.mn_bk as f32, diff as f32, 0.0, 0.0]); @@ -650,6 +663,7 @@ impl Engine { self.mn_bk = 0.0; self.sc_o = 0.0; self.sc_p = 0.0; + self.sc_m = 0.0; self.sc_n = 0; } (out[0], out[1]) @@ -941,6 +955,31 @@ mod tests { 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.01 && pre > o * 1.5, "out {o} pre {pre}"); + let (_, mid, _) = e.scope.get3(n - 20); + assert_eq!(mid, o, "downward: nothing lifted, the lift-free peak is the output"); + assert_eq!(e.gl_pk, 0.0); + } + + #[test] + fn upward_mode_reports_its_lift_to_the_meter_and_the_scope() { + let mut p = Params::default(); + p.drive = 0.0; + p.bias = 0.0; + p.thresh = -20.0; + p.ratio = 2.0; + p.comp_mode = 1; + p.up_range = 12.0; + let mut e = Engine::new(SR); + e.set_params(&p); + // -40 dBFS: 20 dB under the threshold, ratio 2 lifts 10 dB + let x = sine(48000, 200.0, 0.01); + let _ = run(&mut e, &x, 256); + assert!((e.gl_pk - 10.0).abs() < 1.5, "lift {}", e.gl_pk); + let n = e.scope.head(); + let (o, mid, pre) = e.scope.get3(n - 20); + let lift_db = 20.0 * (o / mid).log10(); + assert!((lift_db - 10.0).abs() < 1.5, "scope lift {lift_db} dB (out {o}, without lift {mid})"); + assert!((pre - o).abs() < 1e-6, "nothing reduced in UPWARD: {pre} vs {o}"); } #[test] diff --git a/rust/satcomp-dsp/src/halfband.rs b/rust/satcomp-dsp/src/halfband.rs index 324d0c0..1ab3d1b 100644 --- a/rust/satcomp-dsp/src/halfband.rs +++ b/rust/satcomp-dsp/src/halfband.rs @@ -246,6 +246,70 @@ impl Oversampler { } } } + + /// As `process_fe`, plus a second even part taken about the operating point `bias` instead of about 0, through its own + /// down filters `eb1`. `x` already carries the bias (x = drive * u + bias), so its mirror about the operating point is + /// `2 bias - x`: e1(x) = (f(x) + f(2 bias - x)) / 2. That is the even part of the curve as the signal actually sees it + /// (an odd curve with a bias has one), the part that lopsides the output. Returns (f, e0, e1). + #[inline] + pub fn process_fe2(&mut self, taps: &Taps, lut: &ShaperLut, os: i32, x: f64, bias: f64, eb0: &mut Oversampler, eb1: &mut Oversampler) -> (f64, f64, f64) { + let b2 = 2.0 * bias; + // f(v), e0(v), e1(v) from one pass over the oversampled points + let fe = |v: f64| { + let f = lut.eval(v); + (f, 0.5 * (f + lut.eval(-v)), 0.5 * (f + lut.eval(b2 - v))) + }; + match os { + 0 => fe(x), + 1 => { + let (a0, a1) = self.a.up(&taps.ha, x); + let (p, q) = (fe(a0), fe(a1)); + (self.a.down(&taps.ha, p.0, q.0), eb0.a.down(&taps.ha, p.1, q.1), eb1.a.down(&taps.ha, p.2, q.2)) + } + 2 => { + let (a0, a1) = self.a.up(&taps.ha, x); + let (b0, b1) = self.b.up(&taps.hb, a0); + let (b2_, b3) = self.b.up(&taps.hb, a1); + let (p0, p1, p2, p3) = (fe(b0), fe(b1), fe(b2_), fe(b3)); + let c0 = self.b.down(&taps.hb, p0.0, p1.0); + let c1 = self.b.down(&taps.hb, p2.0, p3.0); + let d0 = eb0.b.down(&taps.hb, p0.1, p1.1); + let d1 = eb0.b.down(&taps.hb, p2.1, p3.1); + let g0 = eb1.b.down(&taps.hb, p0.2, p1.2); + let g1 = eb1.b.down(&taps.hb, p2.2, p3.2); + (self.a.down(&taps.ha, c0, c1), eb0.a.down(&taps.ha, d0, d1), eb1.a.down(&taps.ha, g0, g1)) + } + _ => { + let (a0, a1) = self.a.up(&taps.ha, x); + let (b0, b1) = self.b.up(&taps.hb, a0); + let (b2_, b3) = self.b.up(&taps.hb, 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.hb, *v); + c[2 * i] = p; + c[2 * i + 1] = q; + } + let mut d = [0.0f64; 4]; + let mut d0 = [0.0f64; 4]; + let mut d1 = [0.0f64; 4]; + for i in 0..4 { + let (p, q) = (fe(c[2 * i]), fe(c[2 * i + 1])); + d[i] = self.c.down(&taps.hb, p.0, q.0); + d0[i] = eb0.c.down(&taps.hb, p.1, q.1); + d1[i] = eb1.c.down(&taps.hb, p.2, q.2); + } + let e0 = self.b.down(&taps.hb, d[0], d[1]); + let e1 = self.b.down(&taps.hb, d[2], d[3]); + let f = self.a.down(&taps.ha, e0, e1); + let g0 = eb0.b.down(&taps.hb, d0[0], d0[1]); + let g1 = eb0.b.down(&taps.hb, d0[2], d0[3]); + let h0 = eb1.b.down(&taps.hb, d1[0], d1[1]); + let h1 = eb1.b.down(&taps.hb, d1[2], d1[3]); + (f, eb0.a.down(&taps.ha, g0, g1), eb1.a.down(&taps.ha, h0, h1)) + } + } + } } #[cfg(test)] diff --git a/rust/satcomp-dsp/src/lib.rs b/rust/satcomp-dsp/src/lib.rs index d468dbc..fcd5020 100644 --- a/rust/satcomp-dsp/src/lib.rs +++ b/rust/satcomp-dsp/src/lib.rs @@ -12,8 +12,11 @@ pub mod keyinput; pub mod level; pub mod limiter; pub mod params; +pub mod preset; +pub mod paramspec; pub mod saturator; pub mod shapers; +pub mod spec; pub use compressor::{CompParams, Compressor, GainComputer}; pub use engine::{Engine, MeterRing, ScopeRing, TapRing}; @@ -28,3 +31,6 @@ pub fn db_to_gain(db: f64) -> f64 { /// Tiny offset the JSFX adds to recursive stages to avoid denormals. pub const DENORM: f64 = 1e-30; + +/// This crate's version, the same as the plug-in's (reported by the CLI). +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/rust/satcomp-dsp/src/limiter.rs b/rust/satcomp-dsp/src/limiter.rs index 7c1ab26..8364d27 100644 --- a/rust/satcomp-dsp/src/limiter.rs +++ b/rust/satcomp-dsp/src/limiter.rs @@ -277,8 +277,14 @@ impl Limiter { /// 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.set_release(ms, true); + } + + /// Release in ms. `auto` = program dependent (`ms` is the slow end, the fast end stays at 15 ms or below it, as + /// `set_release_ms`); otherwise a fixed time constant of `ms`. + pub fn set_release(&mut self, ms: f64, auto: bool) { self.tau1 = (ms * 0.001).max(0.001); - self.tau0 = self.tau1.min(TAU_MIN); + self.tau0 = if auto { self.tau1.min(TAU_MIN) } else { self.tau1 }; } /// Double the detector's oversampling (8x at 48 kHz-class rates, 4x at 96 kHz-class, 2x above, where the latency diff --git a/rust/satcomp-dsp/src/params.rs b/rust/satcomp-dsp/src/params.rs index 04e8f80..5fd6491 100644 --- a/rust/satcomp-dsp/src/params.rs +++ b/rust/satcomp-dsp/src/params.rs @@ -2,7 +2,7 @@ use crate::compressor::CompParams; use crate::saturator::SatParams; -use crate::shapers::{Curve, SHAPER_COUNT}; +use crate::shapers::Curve; #[derive(Clone, Copy, PartialEq, Debug)] pub struct EqBandParams { @@ -31,10 +31,11 @@ impl Default for EqStageParams { #[derive(Clone, Copy, PartialEq, Debug)] pub struct Params { // SAT - pub shape: i32, // 1 0..14 (14 = custom curve, Rust only) + pub shape: i32, // 1 0..16 (14 = custom curve, 15 / 16 = ratio 2:1 / 4:1; Rust only past 13) 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], + /// ASYM, 0..100 %, one value for every shaper: how much of the even part about the operating point is kept (100 = the + /// curve as drawn; below 25 % the polarity balancer fades in; see `Saturator`) + pub asym: f64, pub drive: f64, // 2 0..100 % pub bias: f64, // 3 -100..100 % pub sat_hp: f64, // 4 20..2000 Hz (<=20.5 = off) @@ -49,6 +50,10 @@ pub struct Params { pub speed: f64, // 12 0..100 % pub knee: f64, // 13 dB pub knee_shape: f64, // 14 0..100 % + /// 70 compressor mode: 0 downward, 1 upward (lifts below the threshold, up to `up_range`), 2 both (as SatXComp) + pub comp_mode: i32, + /// 71 dB: the most the upward mode lifts + pub up_range: f64, pub detector: f64, // 15 0..100 % (peak > rms) pub det_hp: f64, // 16 0..400 Hz (<=15 = off) pub ff_fb: f64, // 18 0..100 % @@ -91,7 +96,7 @@ impl Params { 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)]), + asym: Some(self.asym.clamp(0.0, 100.0)), steep: false, } } @@ -111,9 +116,9 @@ impl Params { ff_fb: self.ff_fb, gr_dist: self.gr_dist, key_mix: self.sc_mix, - up: false, - down: true, - up_range: 12.0, + up: self.comp_mode >= 1, + down: self.comp_mode != 1, + up_range: self.up_range, } } } @@ -123,7 +128,7 @@ impl Default for Params { Self { shape: 0, curve: Curve::linear(), - asym: [100.0; SHAPER_COUNT], + asym: 100.0, drive: 0.0, bias: 0.0, sat_hp: 20.0, @@ -137,6 +142,8 @@ impl Default for Params { speed: 50.0, knee: 6.0, knee_shape: 0.0, + comp_mode: 0, + up_range: 12.0, detector: 30.0, det_hp: 0.0, ff_fb: 0.0, @@ -162,3 +169,17 @@ impl Default for Params { } } } + +#[cfg(test)] +mod comp_mode_tests { + use super::*; + + #[test] + fn comp_mode_maps_onto_the_compressors_down_up_switches() { + for (mode, up, down) in [(0, false, true), (1, true, false), (2, true, true)] { + let c = Params { comp_mode: mode, up_range: 9.0, ..Params::default() }.comp(); + assert_eq!((c.up, c.down, c.up_range), (up, down, 9.0), "mode {mode}"); + } + assert_eq!(Params::default().comp_mode, 0, "downward by default, as before"); + } +} diff --git a/rust/satcomp-dsp/src/paramspec.rs b/rust/satcomp-dsp/src/paramspec.rs new file mode 100644 index 0000000..df79522 --- /dev/null +++ b/rust/satcomp-dsp/src/paramspec.rs @@ -0,0 +1,109 @@ +//! Parameter metadata shared by the family's generated `spec` modules (`-dsp/src/spec.rs`, written by the +//! tools/gen_*params.py generators). The plug-ins and the CLI read the same tables: id, range, default, unit and choices, plus +//! a plain `Values` struct per plug-in and the one `to_dsp` that turns it into the engine's settings. + +/// How a parameter's value is stored and read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Float, + /// stored as a whole number in `min..=max` (choices, counts) + Int, + /// 0 = off, 1 = on + Bool, +} + +/// One parameter. Values are plain (in the parameter's unit), never normalised. +#[derive(Clone, Copy, Debug)] +pub struct ParamSpec { + /// the UI's slot number (also the index into `Values::get` / `set`) + pub slot: usize, + /// permanent id: host automation, presets and the CLI all address the parameter by it + pub id: &'static str, + /// display name (the host's parameter name) + pub name: &'static str, + pub kind: Kind, + pub min: f32, + pub max: f32, + pub default: f32, + /// display / entry resolution (0 = none) + pub step: f32, + /// unit as displayed, without the leading space (`dB`, `Hz`, `ms`, `%`; empty = none) + pub unit: &'static str, + /// names of an `Int` parameter's values from `min` up (empty = addressed by number only) + pub choices: &'static [&'static str], +} + +/// The parameter with `id` in a plug-in's table. +pub fn find<'a>(specs: &'a [ParamSpec], id: &str) -> Option<&'a ParamSpec> { + specs.iter().find(|s| s.id == id) +} + +/// The parameter at UI slot `slot`. +pub fn at_slot(specs: &[ParamSpec], slot: usize) -> Option<&ParamSpec> { + specs.iter().find(|s| s.slot == slot) +} + +/// Consistency of a plug-in's table (each generated `spec` module tests itself with it): ids and slots unique, ranges and +/// defaults sane, switches 0..1, and a choice list names every value of its range, no more, no less. +pub fn check(specs: &[ParamSpec]) -> Result<(), String> { + for (i, s) in specs.iter().enumerate() { + if specs[..i].iter().any(|o| o.id == s.id) { + return Err(format!("{}: id used twice", s.id)); + } + if specs[..i].iter().any(|o| o.slot == s.slot) { + return Err(format!("{}: slot {} used twice", s.id, s.slot)); + } + if !(s.min < s.max && s.default >= s.min && s.default <= s.max) { + return Err(format!("{}: range {}..{} / default {}", s.id, s.min, s.max, s.default)); + } + // a default off the step grid is not what a preset load or the editor gives back (both snap to the step), so a fresh + // instance and INIT would differ (SatEQ's Q 0.707 at a 0.01 step was such a case) + if s.kind == Kind::Float && s.step > 0.0 { + let q = s.default / s.step; + if (q - q.round()).abs() > 1e-3 { + return Err(format!("{}: default {} is off its step {}", s.id, s.default, s.step)); + } + } + if s.kind == Kind::Bool && (s.min, s.max) != (0.0, 1.0) { + return Err(format!("{}: a switch must be 0..1", s.id)); + } + if !s.choices.is_empty() { + let n = (s.max - s.min) as usize + 1; + if s.kind != Kind::Int || s.choices.len() != n { + return Err(format!("{}: {} choice names for {} values", s.id, s.choices.len(), n)); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const T: &[ParamSpec] = &[ + ParamSpec { slot: 3, id: "drive", name: "Drive", kind: Kind::Float, min: 0.0, max: 100.0, default: 20.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 7, id: "os", name: "Oversampling", kind: Kind::Int, min: 0.0, max: 3.0, default: 2.0, step: 1.0, unit: "", choices: &["x1", "x2", "x4", "x8"] }, + ]; + + #[test] + fn lookups_by_id_and_slot() { + assert_eq!(find(T, "os").unwrap().slot, 7); + assert_eq!(at_slot(T, 3).unwrap().id, "drive"); + assert!(find(T, "nope").is_none() && at_slot(T, 4).is_none()); + } + + #[test] + fn check_catches_a_choice_list_that_does_not_cover_its_range() { + assert!(check(T).is_ok()); + let mut bad = T.to_vec(); + bad[1].max = 4.0; // five values, four names: the old SatFilt LFO division + assert!(check(&bad).unwrap_err().contains("4 choice names for 5 values")); + bad[1].max = 3.0; + bad[0].default = 20.05; // off the 0.1 step + assert!(check(&bad).unwrap_err().contains("off its step")); + bad[0].default = 20.0; + bad[1].slot = 3; + assert!(check(&bad).unwrap_err().contains("slot 3")); + } +} diff --git a/rust/satcomp-dsp/src/preset.rs b/rust/satcomp-dsp/src/preset.rs new file mode 100644 index 0000000..a304af7 --- /dev/null +++ b/rust/satcomp-dsp/src/preset.rs @@ -0,0 +1,208 @@ +//! SatComp presets (the plug-in's and the CLI's shared format): JSON files of parameter values keyed by parameter id. +//! Factory bank = every `presets/*.json` embedded at build time (+ built-in INIT). User presets = `*.satcomp` files in +//! `user_dir()`: the plug-in lists them, the CLI loads them by name. + +use crate::spec::TABLE; +use crate::shapers::Curve; +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 = "satcomp"; +/// Never stored in a preset: Bypass is a performance switch, Gain Match is a level-dependent measurement. +pub const EXCLUDED: [&str; 3] = ["bypass", "gain_match", "sc_on"]; + +#[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)>, + /// Legacy (0.5.3 and older): ASYM per waveshaper. Read only: `from_json` moves the preset shaper's value into the `asym` + /// parameter. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asym: Vec, +} + +impl Preset { + /// A preset of the current settings (the editor's SAVE, the CLI's --save-preset): every parameter presets keep, read + /// through `get(slot)`, and the drawn curves when any is not the plain line. + pub fn capture(name: &str, get: impl Fn(usize) -> f32, curve: &Curve) -> Self { + let params = TABLE.iter().filter(|e| !EXCLUDED.contains(&e.1)).map(|e| (e.1.to_string(), get(e.0))).collect(); + let mut p = Self::new(name, params); + if *curve != Curve::linear() { + p.curve = curve.pts().to_vec(); + } + p + } + + /// What loading this preset writes, as (slot, plain value) per parameter it sets (clamped to the range; a parameter it + /// leaves alone is absent). The editor sends each one like a click; the CLI stores them with `spec::Values::set`. + pub fn writes(&self) -> Vec<(usize, f32)> { + TABLE + .iter() + .filter(|e| !EXCLUDED.contains(&e.1)) + .map(|&(n, id, mn, mx, df)| (n, self.params.get(id).copied().unwrap_or(df).clamp(mn, mx))) + .collect() + } + + /// The drawn curves a load stores (the editor keeps their points; the engine gets these). + pub fn drawn(&self) -> Curve { + // absent curve = linear (a load never keeps the previous preset's curve) + Curve::from_points(&self.curve) + } + + pub fn new(name: &str, params: BTreeMap) -> Self { + Self { format: "satcomp-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 mut p: Preset = serde_json::from_str(s).ok()?; + if p.format != "satcomp-preset" { + return None; + } + // ASYM used to be one value per shaper: the value of the preset's own shaper becomes the single ASYM parameter + if !p.asym.is_empty() { + if !p.params.contains_key("asym") { + let shape = p.params.get("shape").copied().unwrap_or(0.0).round().max(0.0) as usize; + if let Some(v) = p.asym.get(shape).filter(|v| v.is_finite()) { + p.params.insert("asym".into(), v.clamp(0.0, 100.0)); + } + } + p.asym.clear(); + } + 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/SatComp/Presets (macOS), %APPDATA%\SatComp\Presets (Windows), ~/.config/SatComp/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("SatComp").join("Presets")) +} + +/// (display name, path) of the user presets, sorted case-insensitively. +pub fn scan_user() -> Vec<(String, PathBuf)> { + let mut v = Vec::new(); + 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(test)] +mod tests { + use super::*; + + #[test] + 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"], 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 a_legacy_asym_list_becomes_the_asym_parameter() { + assert_eq!(Preset::init().params["asym"], 100.0); + let old = r#"{"format":"satcomp-preset","version":1,"name":"x","params":{"shape":1.0},"asym":[100.0,35.0]}"#; + let o = Preset::from_json(old).unwrap(); + assert_eq!(o.params["asym"], 35.0); + assert!(o.asym.is_empty() && !o.to_json().contains("[100")); + let both = r#"{"format":"satcomp-preset","version":1,"name":"x","params":{"asym":60.0},"asym":[10.0]}"#; + assert_eq!(Preset::from_json(both).unwrap().params["asym"], 60.0); + let none = r#"{"format":"satcomp-preset","version":1,"name":"x","params":{}}"#; + assert!(!Preset::from_json(none).unwrap().params.contains_key("asym")); + } + + #[test] + fn curve_roundtrips_and_old_presets_load_without_it() { + let mut p = Preset::init(); + assert!(!p.to_json().contains("curve")); // not written when unused + 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.curve, p.curve); + let old = r#"{"format":"satcomp-preset","version":1,"name":"x","params":{}}"#; + assert!(Preset::from_json(old).unwrap().curve.is_empty()); + } + + #[test] + fn factory_bank_has_the_drum_presets() { + let f = factory(); + for n in ["Drums_Baked", "Drums_Bricked", "Drums_Cooked", "Drums_Cruncher", "Drums_Thicc", "Drums_Tubed"] { + assert!(f.iter().any(|p| p.name == n), "missing factory preset {n}"); + } + // Cruncher uses the Custom shaper and ships its curve + let c = f.iter().find(|p| p.name == "Drums_Cruncher").unwrap(); + assert!(c.curve.len() >= 2); + } + + #[test] + fn factory_starts_with_init() { + assert_eq!(factory()[0].name, "INIT"); + } +} diff --git a/rust/satcomp-dsp/src/saturator.rs b/rust/satcomp-dsp/src/saturator.rs index 5b1a4b5..1c2c7b5 100644 --- a/rust/satcomp-dsp/src/saturator.rs +++ b/rust/satcomp-dsp/src/saturator.rs @@ -45,6 +45,13 @@ const BUTTER8_Q: [f64; 4] = [0.509_795_579_104_159_3, 0.601_344_886_935_045_2, 0 /// Corner of the high-pass on the even part of the shaper (2nd order), Hz. pub const EVEN_HP_HZ: f64 = 25.0; +/// ASYM (as 0..1) below which the polarity balancer fades in: full at ASYM 0. Above it ASYM only scales the even part. +pub const BAL_FROM: f64 = 0.25; +/// Release of the balancer's half-wave peak followers, s. +pub const BAL_RELEASE_S: f64 = 0.3; +/// Corner of the DC blocker after the balancer, Hz (lower than the stage blocker: a higher one tilts flat-topped waves). +pub const BAL_DC_HZ: f64 = 2.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 } @@ -61,6 +68,13 @@ pub struct Saturator { asym_k: Option, evc: Coef, evs: [[f64; 2]; 2], + /// The bias-centred even part (`Oversampler::process_fe2`): its down filters, its high-pass state and DC offset. Only + /// runs while ASYM is below 100 % and BIAS is not 0 (with no bias it equals the even part about 0). + ove1: [Oversampler; 2], + evs1: [[f64; 2]; 2], + ev1_adj: [f64; 2], + /// whether the bias-centred chain ran on the previous sample (re-settled when it starts again) + e1_on: bool, pre: f64, pre_t: f64, bias: f64, @@ -118,6 +132,20 @@ pub struct Saturator { ms_c: f64, /// Smoothed mean-square level of the stage output before SAT OUT (reference for the sat level-match). pub ms: f64, + /// Polarity balancer, the bottom quarter of ASYM (see `balance`): target / smoothed amount 0..1, peak followers of the + /// positive and negative half-waves (stereo-linked), their gains, the follower release and gain glide coefficients, and the + /// DC blocker after it (scaling the two halves differently makes DC). + bal_t: f64, + bal: f64, + bal_ep: f64, + bal_en: f64, + bal_gp: f64, + bal_gn: f64, + bal_rel: f64, + bal_gc: f64, + bal_x: [f64; 2], + bal_y: [f64; 2], + bal_r: f64, /// Peak of the shaped band since the owner last cleared it (UI meter). pub blk: f64, /// as `blk`, but reset by the engine once per meter bucket (2 ms) instead of once per host block @@ -150,6 +178,10 @@ impl Saturator { asym_k: None, evc: biquad::IDENTITY, evs: [[0.0; 2]; 2], + ove1: [Oversampler::default(), Oversampler::default()], + evs1: [[0.0; 2]; 2], + ev1_adj: [0.0; 2], + e1_on: false, pre: 1.0, pre_t: 1.0, bias: 0.0, @@ -199,6 +231,17 @@ impl Saturator { gain_c: 0.0, ms_c: 0.0, ms: 1e-9, + bal_t: 0.0, + bal: 0.0, + bal_ep: 1e-9, + bal_en: 1e-9, + bal_gp: 1.0, + bal_gn: 1.0, + bal_rel: 0.0, + bal_gc: 0.0, + bal_x: [0.0; 2], + bal_y: [0.0; 2], + bal_r: 1.0, blk: 0.0, bk: 0.0, } @@ -220,8 +263,9 @@ impl Saturator { /// DC of the blocker input and of the even part over the recent input, for table `t` at the given drive and bias. /// Hann-weighted, oldest sample first. Only differences of it are used, so its leakage from loud low tones cancels. - fn shaper_dc(&self, t: &[f64], periodic: bool, pre: f64, bias: f64, c: usize) -> (f64, f64) { - let (mut f_sum, mut e_sum, mut odd_sum, mut wsum) = (0.0, 0.0, 0.0, 0.0); + /// The third value is the DC of the even part about the operating point (the high-pass input of the bias-centred chain). + fn shaper_dc(&self, t: &[f64], periodic: bool, pre: f64, bias: f64, c: usize) -> (f64, f64, f64) { + let (mut f_sum, mut e_sum, mut e1_sum, mut odd_sum, mut wsum) = (0.0, 0.0, 0.0, 0.0, 0.0); for k in (0..HIST_LEN).step_by(DC_STRIDE) { let x = self.hist[c][(self.hist_i + k) % HIST_LEN] * pre + bias; let w = self.hann[k]; @@ -229,13 +273,16 @@ impl Saturator { let e = 0.5 * (f + ShaperLut::eval_table(t, periodic, -x)); f_sum += w * f; e_sum += w * e; + if self.asym_k.is_some() { + e1_sum += w * 0.5 * (f + ShaperLut::eval_table(t, periodic, 2.0 * bias - x)); + } odd_sum += w * (f - e); wsum += w; } if self.asym_k.is_some() { - (odd_sum / wsum, e_sum / wsum) + (odd_sum / wsum, e_sum / wsum, e1_sum / wsum) } else { - (f_sum / wsum, 0.0) + (f_sum / wsum, 0.0, 0.0) } } @@ -260,10 +307,11 @@ impl Saturator { return; } for c in 0..2 { - let (d0, e0) = self.shaper_dc(&self.m_table, self.m_periodic, self.m_pre, self.m_bias, c); - let (d1, e1) = self.shaper_dc(&self.lut.table, self.lut.periodic, self.pre, self.bias, c); + let (d0, e0, g0) = self.shaper_dc(&self.m_table, self.m_periodic, self.m_pre, self.m_bias, c); + let (d1, e1, g1) = self.shaper_dc(&self.lut.table, self.lut.periodic, self.pre, self.bias, c); self.dc_adj[c] += d1 - d0; self.ev_adj[c] += e1 - e0; + self.ev1_adj[c] += g1 - g0; } self.m_table.copy_from_slice(&self.lut.table); self.m_periodic = self.lut.periodic; @@ -331,6 +379,13 @@ impl Saturator { if self.asym_k.is_some() { self.evc = biquad::hp(EVEN_HP_HZ, 0.70710678, sr); } + self.bal_t = self.asym_k.map_or(0.0, |k| ((BAL_FROM - k) / BAL_FROM).clamp(0.0, 1.0)); + self.bal_rel = (-1.0 / (BAL_RELEASE_S * sr)).exp(); + self.bal_gc = one_pole(sr, 0.02); + self.bal_r = 1.0 - 2.0 * PI * BAL_DC_HZ / sr; + if snap { + self.bal = self.bal_t; + } self.os = (p.os as f64 + 0.5).floor() as i32; if self.os != self.last_os { self.last_os = self.os; @@ -338,6 +393,9 @@ impl Saturator { self.ov[1].clear(); self.ove[0].clear(); self.ove[1].clear(); + self.ove1[0].clear(); + self.ove1[1].clear(); + self.e1_on = false; self.res.clear(); } self.lat = crate::halfband::latency(self.os); @@ -356,11 +414,48 @@ impl Saturator { } } + /// Polarity balancer on the stage output (both channels, linked): follow the peaks of the positive and the + /// negative half-waves and bring the louder side down to the quieter one, by the smoothed amount, then block the DC this + /// makes. The asymmetry a lopsided curve leaves even after its even part is gone (a folder fed a dispersed or lopsided + /// input) is only reachable here. Idle (amount 0): the input passes untouched while the followers and the blocker keep + /// tracking, so engaging starts settled. + #[inline] + fn balance(&mut self, ys: &mut [f64; 2]) { + self.bal += (self.bal_t - self.bal) * self.sm_c; + let hi = ys[0].max(ys[1]).max(0.0); + let lo = (-ys[0].min(ys[1])).max(0.0); + self.bal_ep = hi.max(self.bal_ep * self.bal_rel).max(1e-9); + self.bal_en = lo.max(self.bal_en * self.bal_rel).max(1e-9); + if self.bal_t == 0.0 && self.bal < 1e-4 { + self.bal = 0.0; + self.bal_gp = 1.0; + self.bal_gn = 1.0; + for c in 0..2 { + let o = ys[c] - self.bal_x[c] + self.bal_r * self.bal_y[c] + DENORM; + self.bal_x[c] = ys[c]; + self.bal_y[c] = o; + } + return; + } + let tp = (self.bal_en / self.bal_ep).min(1.0); + let tn = (self.bal_ep / self.bal_en).min(1.0); + self.bal_gp += (1.0 + self.bal * (tp - 1.0) - self.bal_gp) * self.bal_gc; + self.bal_gn += (1.0 + self.bal * (tn - 1.0) - self.bal_gn) * self.bal_gc; + for c in 0..2 { + let z = if ys[c] > 0.0 { ys[c] * self.bal_gp } else { ys[c] * self.bal_gn }; + let o = z - self.bal_x[c] + self.bal_r * self.bal_y[c] + DENORM; + self.bal_x[c] = z; + self.bal_y[c] = o; + ys[c] = o; + } + } + /// Per host block. pub fn begin_block(&mut self) { self.gain_t = (self.out_db * LN10_20).exp(); // an odd shaper (7 of the 15 factory ones) has no even part: skip its even-part oversampling chain once the filters of the // previous one have rung out (until then the even part carries on exactly as before) + // (the bias-centred even part has its own chain, see `tick_split`) self.even_skip = self.asym_k.is_some() && self.lut.is_odd() && self.ove[0].down_quiet(1e-12) && self.ove[1].down_quiet(1e-12); } @@ -395,6 +490,7 @@ impl Saturator { for c in 0..2 { self.dc_adj[c] *= self.adj_dec; self.ev_adj[c] *= self.adj_dec; + self.ev1_adj[c] *= self.adj_dec; } } if smoothing { @@ -453,9 +549,36 @@ impl Saturator { } let rd_band = self.band.tap(self.lat); let rd_res = self.res.tap(self.lat); + // ASYM below 100 %: the part taken away is the even part about the operating point (bias-centred chain). At 100 % + // only the legacy sub-audio high-pass of the even part about 0 acts, bit for bit as before. + let e1_want = self.asym_k.is_some_and(|k| k < 1.0); + let e1_start = e1_want && !self.e1_on; + self.e1_on = e1_want; for c in 0..2 { let xin = bp[c] * self.pre + self.bias; - let sh = if let Some(k) = self.asym_k { + let sh = if let (Some(k), true) = (self.asym_k, e1_want) { + // out = f - LP(e0) - (1 - k) HP(e1): f - e0 + HP(e0) is the legacy ASYM 100 %, and with no bias e1 = e0, so + // this is the legacy f - e0 + k HP(e0); at 0 % it is the odd part about the operating point + if self.dc_warm { + for _ in 0..256 { + self.ov[c].process_fe2(&self.taps, &self.lut, self.os, xin, self.bias, &mut self.ove[c], &mut self.ove1[c]); + } + } else if e1_start { + self.ove1[c].clear(); + } + let (f, e, e1) = self.ov[c].process_fe2(&self.taps, &self.lut, self.os, xin, self.bias, &mut self.ove[c], &mut self.ove1[c]); + if self.dc_warm { + for _ in 0..16384 { + bq(&mut self.evs[c], &self.evc, e); + } + } + if self.dc_warm || e1_start { + for _ in 0..16384 { + bq(&mut self.evs1[c], &self.evc, e1 - self.ev1_adj[c]); + } + } + f - e + bq(&mut self.evs[c], &self.evc, e - self.ev_adj[c]) - (1.0 - k) * bq(&mut self.evs1[c], &self.evc, e1 - self.ev1_adj[c]) + } else 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]); @@ -497,6 +620,9 @@ impl Saturator { } cc[c] = rd_res[c] + y; } + // on the whole stage output: the band SAT HP / LP keep out of the shaper (and SAT MIX's dry) is added back above + // and can lopside the sum on its own + self.balance(&mut cc); self.dc_warm = false; } else { self.res.put([0.0, 0.0]); @@ -557,4 +683,48 @@ mod tests { assert!(swing(full) < 0.5 * swing(legacy), "asym 100 low-passed swing {full:?} vs legacy {legacy:?}"); } } + + /// Band-limited saw through an odd zig-zag curve with a bias and SAT HP 70 Hz (the SatDiff "Zap" preset without its + /// diffusor): (positive peak, negative peak, rms) + /// after the first 0.5 s, per ASYM. + fn zap(asym: f64, os: i32, dir: f64) -> (f64, f64, f64) { + let sr = 48000.0; + let curve = Curve::from_parts(&[(-1.0, -1.0), (-0.2676, 0.6665), (0.2676, -0.6665), (1.0, 1.0)], &[1.0, 0.0, 0.0, 0.0]); + let p = SatParams { shape: CUSTOM, curve, drive: 3.0, bias: 19.0, hp: 70.0, os, mix: 100.0, asym: Some(asym), ..SatParams::default() }; + let mut s = Saturator::new(); + s.derive(&p, sr, true, true); + let (mut hi, mut lo, mut sq, mut n) = (0.0f64, 0.0f64, 0.0, 0.0); + let w = 2.0 * PI * 110.0 / sr; + for i in 0..72000 { + if i % 256 == 0 { + s.begin_block(); + } + let x: f64 = (1..=196).map(|k| (w * k as f64 * i as f64).sin() / k as f64 * if k % 2 == 1 { 1.0 } else { -1.0 }).sum::() * dir * 0.8 * 2.0 / PI; + let y = s.tick([x, x], true)[0]; + if i >= 24000 { + hi = hi.max(y); + lo = lo.max(-y); + sq += y * y; + n += 1.0; + } + } + (hi, lo, (sq / n).sqrt()) + } + + #[test] + fn asym_evens_out_the_lopsidedness_a_bias_gives_an_odd_curve() { + let db = |x: f64| 20.0 * x.log10(); + for os in [0, 1] { + for dir in [1.0, -1.0] { + let r: Vec<(f64, f64, f64)> = [100.0, 25.0, 0.0].iter().map(|&a| zap(a, os, dir)).collect(); + let lop = |t: (f64, f64, f64)| (db(t.0) - db(t.1)).abs(); + let crest = |t: (f64, f64, f64)| db(t.0.max(t.1)) - db(t.2); + eprintln!("os {os} dir {dir}: lopsided by {:.2} / {:.2} / {:.2} dB, crest {:.2} / {:.2} / {:.2} dB (asym 100 / 25 / 0)", + lop(r[0]), lop(r[1]), lop(r[2]), crest(r[0]), crest(r[1]), crest(r[2])); + // the old ASYM saw no even part in an odd curve and left this untouched. Judged on headroom (crest), not on the + // two peaks matching: the balancer's DC blocker re-centres the wave after scaling the halves + assert!(crest(r[2]) < crest(r[0]) - 0.5, "asym 0 must win headroom (0.9 to 5.6 dB when written): {r:?}"); + } + } + } } diff --git a/rust/satcomp-dsp/src/shapers.rs b/rust/satcomp-dsp/src/shapers.rs index 1e42c09..31e76d7 100644 --- a/rust/satcomp-dsp/src/shapers.rs +++ b/rust/satcomp-dsp/src/shapers.rs @@ -1,13 +1,32 @@ -//! The 14 waveshapers and the +-8 lookup table (4097 points) the JSFX uses. +//! The waveshapers (14 from the JSFX, the custom curve, 2 ratio curves) and the +-8 lookup table (4097 points). pub const LUT_LEN: usize = 4097; -pub const SHAPER_NAMES: [&str; 15] = [ +/// Names by stored index. Indices are permanent (presets / projects store them): new shapers are appended, so the ratio +/// curves (15, 16) come after Custom (14). Menus and arrows use `MENU_ORDER`, which keeps Custom last. +pub const SHAPER_NAMES: [&str; 17] = [ "Tube", "Soft", "Rational", "Atan", "Hard", "Tri Fold", "Sine Fold", "Crossover", "Cheby", "Wrap", - "Rectify", "Bitcrush", "Asym Fold", "Diode", "Custom", + "Rectify", "Bitcrush", "Asym Fold", "Diode", "Custom", "Ratio 2:1", "Ratio 4:1", ]; -/// Number of waveshapers (14 built-in + custom). +/// Number of waveshapers (16 built-in + custom). pub const SHAPER_COUNT: usize = SHAPER_NAMES.len(); +/// Shaper indices in menu / arrow order: the built-in curves, then Custom last. +pub const MENU_ORDER: [i32; SHAPER_COUNT] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 14]; + +/// The shaper `d` steps from `sel` in menu order, wrapping around (the [<] [>] arrows). +pub fn shaper_step(sel: i32, d: i32) -> i32 { + let n = MENU_ORDER.len() as i32; + let pos = MENU_ORDER.iter().position(|&i| i == sel).unwrap_or(0) as i32; + MENU_ORDER[(pos + d).rem_euclid(n) as usize] +} + +/// The shaper `d` steps from `sel` in menu order, stopping at the ends (the mouse wheel). +pub fn shaper_step_clamped(sel: i32, d: i32) -> i32 { + let n = MENU_ORDER.len() as i32; + let pos = MENU_ORDER.iter().position(|&i| i == sel).unwrap_or(0) as i32; + MENU_ORDER[(pos + d).clamp(0, n - 1) as usize] +} + /// 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]; @@ -22,6 +41,36 @@ pub fn asym_from(v: &[f32]) -> [f64; SHAPER_COUNT] { /// Shaper index of the user-drawn curve. pub const CUSTOM: i32 = 14; +/// The ratio curves (appended after Custom, see `SHAPER_NAMES`). +pub const RATIO_2: i32 = 15; +pub const RATIO_4: i32 = 16; +/// Highest shaper index (the range of every Shape parameter is 0..=LAST_SHAPER). +pub const LAST_SHAPER: i32 = SHAPER_COUNT as i32 - 1; + +/// Name of a shaper index (clamped). +pub fn shaper_name(sel: i32) -> &'static str { + SHAPER_NAMES[sel.clamp(0, LAST_SHAPER) as usize] +} + +/// Where a ratio shaper meets full scale: +12 dB (x = 4). Both ratios compress from their knee up to there, then hold. +const RATIO_TOP: f64 = 4.0; + +/// Ratio shaper (odd): the straight line (unity, like the other shapers at low level) up to the knee, then `r`:1 in dB +/// until it reaches 1 at `RATIO_TOP`, then flat. The knee follows from the ratio: k = top^(-1 / (r - 1)), so 2:1 bends at +/// -12 dB and 4:1 at -4 dB. DRIVE moves the signal into the knee, like a threshold. +fn ratio(x: f64, r: f64) -> f64 { + let a = x.abs(); + let k = RATIO_TOP.powf(-1.0 / (r - 1.0)); + let y = if a <= k { + a + } else if a >= RATIO_TOP { + 1.0 + } else { + k * (a / k).powf(1.0 / r) + }; + y.copysign(x) +} + /// Max points of the custom curve the SatComp-family editors let you draw, including the two fixed-x end points. pub const MAX_PTS: usize = 20; /// Points a `Curve` can hold (SatDiff's editor uses all of them: 30 free, 15 per half in the odd / even views). @@ -355,6 +404,8 @@ pub fn shaper(sel: i32, x: f64) -> f64 { -0.6 * (1.0 - (x / 0.6).exp()) } } + RATIO_2 => ratio(x, 2.0), + RATIO_4 => ratio(x, 4.0), _ => 0.0, } } @@ -510,6 +561,38 @@ impl ShaperLut { #[cfg(test)] mod tests { + #[test] + fn the_ratio_shapers_bend_at_their_knee_and_meet_full_scale_at_plus_12_db() { + let d = |y: f64| 20.0 * y.abs().log10(); + for (sel, r) in [(RATIO_2, 2.0), (RATIO_4, 4.0)] { + let k = 4f64.powf(-1.0 / (r - 1.0)); // -12.04 dB for 2:1, -4.01 dB for 4:1 + let knee_db = d(k); + assert!((shaper(sel, k * 0.5) - k * 0.5).abs() < 1e-12, "straight below the knee"); + // 6 dB over the knee comes out 6 / r dB over it + let y = shaper(sel, k * 2.0); + assert!((d(y) - (knee_db + 6.0206 / r)).abs() < 1e-3, "{sel}: {}", d(y)); + assert!((shaper(sel, 4.0) - 1.0).abs() < 1e-9 && shaper(sel, 7.9) == 1.0); + let mut prev = 0.0; + for i in 1..8000 { + let x = i as f64 * 0.001; + let y = shaper(sel, x); + assert!(y >= prev - 1e-12 && y <= 1.0 && (y - prev).abs() <= 0.001 + 1e-9, "{sel} at {x}"); + assert_eq!(shaper(sel, -x), -y); + prev = y; + } + } + assert_eq!(shaper_name(RATIO_2), "Ratio 2:1"); + // menu order: every shaper once, Custom last; the arrows wrap, the wheel stops + let mut seen = MENU_ORDER.to_vec(); + seen.sort(); + assert_eq!(seen, (0..SHAPER_COUNT as i32).collect::>()); + assert_eq!(*MENU_ORDER.last().unwrap(), CUSTOM); + assert_eq!((shaper_step(13, 1), shaper_step(RATIO_4, 1), shaper_step(CUSTOM, 1), shaper_step(0, -1)), (RATIO_2, CUSTOM, 0, CUSTOM)); + assert_eq!((shaper_step_clamped(CUSTOM, 1), shaper_step_clamped(0, -1)), (CUSTOM, 0)); + assert_eq!(shaper_name(CUSTOM), "Custom"); + assert!(!is_periodic(RATIO_2) && !is_periodic(RATIO_4)); + } + use super::*; #[test] diff --git a/rust/satcomp-dsp/src/spec.rs b/rust/satcomp-dsp/src/spec.rs new file mode 100644 index 0000000..902a248 --- /dev/null +++ b/rust/satcomp-dsp/src/spec.rs @@ -0,0 +1,503 @@ +// GENERATED by tools/gen_params.py (tools/specgen.py). Do not edit by hand. +//! The parameter layer shared by the plug-in and the CLI: table, metadata, plain values and the one mapping onto the +//! engine's settings. + +#![allow(clippy::excessive_precision, clippy::approx_constant)] + +use crate::paramspec::{Kind, ParamSpec}; +use crate::{EqBandParams, EqStageParams}; +use crate::shapers::Curve; + +/// Highest UI slot number + 1. +pub const SLOTS: usize = 72; + +/// (slot number, id, min, max, default) for every parameter. +pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[ + (1, "shape", 0.0, 16.0, 0.0), + (2, "drive", 0.0, 100.0, 0.0), + (3, "bias", -100.0, 100.0, 0.0), + (69, "asym", 0.0, 100.0, 100.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, 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), + (12, "speed", 0.0, 100.0, 50.0), + (13, "knee", 0.0, 24.0, 6.0), + (14, "knee_shape", 0.0, 100.0, 0.0), + (15, "detector", 0.0, 100.0, 30.0), + (16, "det_hp", 0.0, 400.0, 0.0), + (18, "ff_fb", 0.0, 100.0, 0.0), + (19, "gr_dist", 0.0, 100.0, 0.0), + (20, "makeup", 0.0, 24.0, 0.0), + (21, "mix", 0.0, 100.0, 100.0), + (22, "out_gain", -24.0, 12.0, 0.0), + (23, "gain_match", 0.0, 1.0, 0.0), + (25, "sat_mix", 0.0, 100.0, 100.0), + (26, "bypass", 0.0, 1.0, 0.0), + (27, "sat_out", -24.0, 12.0, 0.0), + (29, "pre_b1_type", 0.0, 2.0, 0.0), + (30, "pre_b1_freq", 20.0, 20000.0, 80.0), + (31, "pre_b1_gain", -18.0, 18.0, 0.0), + (32, "pre_b1_q", 0.1, 10.0, 0.5), + (33, "pre_b2_type", 0.0, 2.0, 0.0), + (34, "pre_b2_freq", 20.0, 20000.0, 200.0), + (35, "pre_b2_gain", -18.0, 18.0, 0.0), + (36, "pre_b2_q", 0.1, 10.0, 0.5), + (37, "pre_b3_type", 0.0, 2.0, 0.0), + (38, "pre_b3_freq", 20.0, 20000.0, 6000.0), + (39, "pre_b3_gain", -18.0, 18.0, 0.0), + (40, "pre_b3_q", 0.1, 10.0, 0.5), + (41, "pre_tilt", -12.0, 12.0, 0.0), + (42, "pre_pivot", 20.0, 20000.0, 600.0), + (43, "pre_out_gain", -12.0, 12.0, 0.0), + (44, "post_b1_type", 0.0, 2.0, 0.0), + (45, "post_b1_freq", 20.0, 20000.0, 80.0), + (46, "post_b1_gain", -18.0, 18.0, 0.0), + (47, "post_b1_q", 0.1, 10.0, 0.5), + (48, "post_b2_type", 0.0, 2.0, 0.0), + (49, "post_b2_freq", 20.0, 20000.0, 200.0), + (50, "post_b2_gain", -18.0, 18.0, 0.0), + (51, "post_b2_q", 0.1, 10.0, 0.5), + (52, "post_b3_type", 0.0, 2.0, 0.0), + (53, "post_b3_freq", 20.0, 20000.0, 6000.0), + (54, "post_b3_gain", -18.0, 18.0, 0.0), + (55, "post_b3_q", 0.1, 10.0, 0.5), + (56, "post_tilt", -12.0, 12.0, 0.0), + (57, "post_pivot", 20.0, 20000.0, 600.0), + (58, "post_out_gain", -12.0, 12.0, 0.0), + (59, "lookahead", 0.0, 10.0, 0.0), + (60, "eq_pre_bypass", 0.0, 1.0, 0.0), + (61, "eq_post_bypass", 0.0, 1.0, 0.0), + (62, "eq_module_bypass", 0.0, 1.0, 0.0), + (63, "sc_on", 0.0, 1.0, 0.0), + (64, "sc_gain", -24.0, 24.0, 0.0), + (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), + (70, "comp_mode", 0.0, 2.0, 0.0), + (71, "up_range", 0.0, 24.0, 12.0), + (68, "lim_on", 0.0, 1.0, 1.0), +]; + +/// Full metadata of every parameter, in the order of `TABLE`. +pub const SPECS: &[ParamSpec] = &[ + ParamSpec { slot: 1, id: "shape", name: "Shape", kind: Kind::Int, min: 0.0, max: 16.0, default: 0.0, step: 1.0, unit: "", choices: &crate::shapers::SHAPER_NAMES }, + ParamSpec { slot: 2, id: "drive", name: "Drive", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 3, id: "bias", name: "Bias", kind: Kind::Float, min: -100.0, max: 100.0, default: 0.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 69, id: "asym", name: "Asym", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 4, id: "sat_hp", name: "Sat HP", kind: Kind::Float, min: 20.0, max: 2000.0, default: 20.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 5, id: "sat_lp", name: "Sat LP", kind: Kind::Float, min: 200.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 6, id: "tone", name: "Tone", kind: Kind::Float, min: 1000.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 7, id: "os", name: "Oversampling", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &["x1", "x2", "x4"] }, + ParamSpec { slot: 8, id: "thresh", name: "Thresh", kind: Kind::Float, min: -40.0, max: 0.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 9, id: "ratio", name: "Ratio", kind: Kind::Float, min: 1.0, max: 20.0, default: 4.0, step: 0.1, unit: "", choices: &[] }, + ParamSpec { slot: 10, id: "attack", name: "Attack", kind: Kind::Float, min: 0.05, max: 100.0, default: 10.0, step: 0.01, unit: "ms", choices: &[] }, + ParamSpec { slot: 11, id: "release", name: "Release", kind: Kind::Float, min: 5.0, max: 2000.0, default: 150.0, step: 1.0, unit: "ms", choices: &[] }, + ParamSpec { slot: 12, id: "speed", name: "Speed", kind: Kind::Float, min: 0.0, max: 100.0, default: 50.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 13, id: "knee", name: "Knee", kind: Kind::Float, min: 0.0, max: 24.0, default: 6.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 14, id: "knee_shape", name: "Knee Shape", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 15, id: "detector", name: "Peak>RMS", kind: Kind::Float, min: 0.0, max: 100.0, default: 30.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 16, id: "det_hp", name: "Low Cut", kind: Kind::Float, min: 0.0, max: 400.0, default: 0.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 18, id: "ff_fb", name: "FF>FB", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 19, id: "gr_dist", name: "GR Dist", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 20, id: "makeup", name: "Makeup", kind: Kind::Float, min: 0.0, max: 24.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 21, id: "mix", name: "Mix", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 22, id: "out_gain", name: "Out Gain", kind: Kind::Float, min: -24.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 23, id: "gain_match", name: "Gain Match", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 25, id: "sat_mix", name: "Sat Mix", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 26, id: "bypass", name: "Bypass", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 27, id: "sat_out", name: "Sat Out", kind: Kind::Float, min: -24.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 29, id: "pre_b1_type", name: "Pre B1 Type", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 30, id: "pre_b1_freq", name: "Pre B1 Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 80.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 31, id: "pre_b1_gain", name: "Pre B1 Gain", kind: Kind::Float, min: -18.0, max: 18.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 32, id: "pre_b1_q", name: "Pre B1 Q", kind: Kind::Float, min: 0.1, max: 10.0, default: 0.5, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 33, id: "pre_b2_type", name: "Pre B2 Type", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 34, id: "pre_b2_freq", name: "Pre B2 Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 200.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 35, id: "pre_b2_gain", name: "Pre B2 Gain", kind: Kind::Float, min: -18.0, max: 18.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 36, id: "pre_b2_q", name: "Pre B2 Q", kind: Kind::Float, min: 0.1, max: 10.0, default: 0.5, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 37, id: "pre_b3_type", name: "Pre B3 Type", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 38, id: "pre_b3_freq", name: "Pre B3 Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 6000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 39, id: "pre_b3_gain", name: "Pre B3 Gain", kind: Kind::Float, min: -18.0, max: 18.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 40, id: "pre_b3_q", name: "Pre B3 Q", kind: Kind::Float, min: 0.1, max: 10.0, default: 0.5, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 41, id: "pre_tilt", name: "Pre Tilt", kind: Kind::Float, min: -12.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 42, id: "pre_pivot", name: "Pre Pivot", kind: Kind::Float, min: 20.0, max: 20000.0, default: 600.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 43, id: "pre_out_gain", name: "Pre Out Gain", kind: Kind::Float, min: -12.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 44, id: "post_b1_type", name: "Post B1 Type", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 45, id: "post_b1_freq", name: "Post B1 Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 80.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 46, id: "post_b1_gain", name: "Post B1 Gain", kind: Kind::Float, min: -18.0, max: 18.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 47, id: "post_b1_q", name: "Post B1 Q", kind: Kind::Float, min: 0.1, max: 10.0, default: 0.5, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 48, id: "post_b2_type", name: "Post B2 Type", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 49, id: "post_b2_freq", name: "Post B2 Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 200.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 50, id: "post_b2_gain", name: "Post B2 Gain", kind: Kind::Float, min: -18.0, max: 18.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 51, id: "post_b2_q", name: "Post B2 Q", kind: Kind::Float, min: 0.1, max: 10.0, default: 0.5, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 52, id: "post_b3_type", name: "Post B3 Type", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 53, id: "post_b3_freq", name: "Post B3 Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 6000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 54, id: "post_b3_gain", name: "Post B3 Gain", kind: Kind::Float, min: -18.0, max: 18.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 55, id: "post_b3_q", name: "Post B3 Q", kind: Kind::Float, min: 0.1, max: 10.0, default: 0.5, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 56, id: "post_tilt", name: "Post Tilt", kind: Kind::Float, min: -12.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 57, id: "post_pivot", name: "Post Pivot", kind: Kind::Float, min: 20.0, max: 20000.0, default: 600.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 58, id: "post_out_gain", name: "Post Out Gain", kind: Kind::Float, min: -12.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 59, id: "lookahead", name: "Lookahead", kind: Kind::Float, min: 0.0, max: 10.0, default: 0.0, step: 0.1, unit: "ms", choices: &[] }, + ParamSpec { slot: 60, id: "eq_pre_bypass", name: "EQ Pre Bypass", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 61, id: "eq_post_bypass", name: "EQ Post Bypass", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 62, id: "eq_module_bypass", name: "EQ Module Bypass", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 63, id: "sc_on", name: "Sidechain", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 64, id: "sc_gain", name: "SC Gain", kind: Kind::Float, min: -24.0, max: 24.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 65, id: "sc_hp", name: "SC HP", kind: Kind::Float, min: 20.0, max: 2000.0, default: 20.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 66, id: "sc_lp", name: "SC LP", kind: Kind::Float, min: 200.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 67, id: "sc_mix", name: "Key Mix", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 70, id: "comp_mode", name: "Comp Mode", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &["down", "up", "both"] }, + ParamSpec { slot: 71, id: "up_range", name: "Range", kind: Kind::Float, min: 0.0, max: 24.0, default: 12.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 68, id: "lim_on", name: "Limiter", kind: Kind::Bool, min: 0.0, max: 1.0, default: 1.0, step: 1.0, unit: "", choices: &[] }, +]; + +/// Every parameter's plain value (the unit it is displayed in), named by its id. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Values { + pub shape: i32, + pub drive: f32, + pub bias: f32, + pub asym: f32, + pub sat_hp: f32, + pub sat_lp: f32, + pub tone: f32, + pub os: i32, + pub thresh: f32, + pub ratio: f32, + pub attack: f32, + pub release: f32, + pub speed: f32, + pub knee: f32, + pub knee_shape: f32, + pub detector: f32, + pub det_hp: f32, + pub ff_fb: f32, + pub gr_dist: f32, + pub makeup: f32, + pub mix: f32, + pub out_gain: f32, + pub gain_match: bool, + pub sat_mix: f32, + pub bypass: bool, + pub sat_out: f32, + pub pre_b1_type: i32, + pub pre_b1_freq: f32, + pub pre_b1_gain: f32, + pub pre_b1_q: f32, + pub pre_b2_type: i32, + pub pre_b2_freq: f32, + pub pre_b2_gain: f32, + pub pre_b2_q: f32, + pub pre_b3_type: i32, + pub pre_b3_freq: f32, + pub pre_b3_gain: f32, + pub pre_b3_q: f32, + pub pre_tilt: f32, + pub pre_pivot: f32, + pub pre_out_gain: f32, + pub post_b1_type: i32, + pub post_b1_freq: f32, + pub post_b1_gain: f32, + pub post_b1_q: f32, + pub post_b2_type: i32, + pub post_b2_freq: f32, + pub post_b2_gain: f32, + pub post_b2_q: f32, + pub post_b3_type: i32, + pub post_b3_freq: f32, + pub post_b3_gain: f32, + pub post_b3_q: f32, + pub post_tilt: f32, + pub post_pivot: f32, + pub post_out_gain: f32, + pub lookahead: f32, + pub eq_pre_bypass: bool, + pub eq_post_bypass: bool, + pub eq_module_bypass: bool, + pub sc_on: bool, + pub sc_gain: f32, + pub sc_hp: f32, + pub sc_lp: f32, + pub sc_mix: f32, + pub comp_mode: i32, + pub up_range: f32, + pub lim_on: bool, +} + +impl Default for Values { + /// Every parameter at its default (the plug-in's INIT). + fn default() -> Self { + Self { + shape: 0, + drive: 0.0f32, + bias: 0.0f32, + asym: 100.0f32, + sat_hp: 20.0f32, + sat_lp: 20000.0f32, + tone: 20000.0f32, + os: 0, + thresh: 0.0f32, + ratio: 4.0f32, + attack: 10.0f32, + release: 150.0f32, + speed: 50.0f32, + knee: 6.0f32, + knee_shape: 0.0f32, + detector: 30.0f32, + det_hp: 0.0f32, + ff_fb: 0.0f32, + gr_dist: 0.0f32, + makeup: 0.0f32, + mix: 100.0f32, + out_gain: 0.0f32, + gain_match: false, + sat_mix: 100.0f32, + bypass: false, + sat_out: 0.0f32, + pre_b1_type: 0, + pre_b1_freq: 80.0f32, + pre_b1_gain: 0.0f32, + pre_b1_q: 0.5f32, + pre_b2_type: 0, + pre_b2_freq: 200.0f32, + pre_b2_gain: 0.0f32, + pre_b2_q: 0.5f32, + pre_b3_type: 0, + pre_b3_freq: 6000.0f32, + pre_b3_gain: 0.0f32, + pre_b3_q: 0.5f32, + pre_tilt: 0.0f32, + pre_pivot: 600.0f32, + pre_out_gain: 0.0f32, + post_b1_type: 0, + post_b1_freq: 80.0f32, + post_b1_gain: 0.0f32, + post_b1_q: 0.5f32, + post_b2_type: 0, + post_b2_freq: 200.0f32, + post_b2_gain: 0.0f32, + post_b2_q: 0.5f32, + post_b3_type: 0, + post_b3_freq: 6000.0f32, + post_b3_gain: 0.0f32, + post_b3_q: 0.5f32, + post_tilt: 0.0f32, + post_pivot: 600.0f32, + post_out_gain: 0.0f32, + lookahead: 0.0f32, + eq_pre_bypass: false, + eq_post_bypass: false, + eq_module_bypass: false, + sc_on: false, + sc_gain: 0.0f32, + sc_hp: 20.0f32, + sc_lp: 20000.0f32, + sc_mix: 100.0f32, + comp_mode: 0, + up_range: 12.0f32, + lim_on: true, + } + } +} + +impl Values { + /// The value at UI slot `slot` as a plain number (switches 0 / 1). + pub fn get(&self, slot: usize) -> Option { + Some(match slot { + 1 => self.shape as f32, + 2 => self.drive, + 3 => self.bias, + 69 => self.asym, + 4 => self.sat_hp, + 5 => self.sat_lp, + 6 => self.tone, + 7 => self.os as f32, + 8 => self.thresh, + 9 => self.ratio, + 10 => self.attack, + 11 => self.release, + 12 => self.speed, + 13 => self.knee, + 14 => self.knee_shape, + 15 => self.detector, + 16 => self.det_hp, + 18 => self.ff_fb, + 19 => self.gr_dist, + 20 => self.makeup, + 21 => self.mix, + 22 => self.out_gain, + 23 => self.gain_match as i32 as f32, + 25 => self.sat_mix, + 26 => self.bypass as i32 as f32, + 27 => self.sat_out, + 29 => self.pre_b1_type as f32, + 30 => self.pre_b1_freq, + 31 => self.pre_b1_gain, + 32 => self.pre_b1_q, + 33 => self.pre_b2_type as f32, + 34 => self.pre_b2_freq, + 35 => self.pre_b2_gain, + 36 => self.pre_b2_q, + 37 => self.pre_b3_type as f32, + 38 => self.pre_b3_freq, + 39 => self.pre_b3_gain, + 40 => self.pre_b3_q, + 41 => self.pre_tilt, + 42 => self.pre_pivot, + 43 => self.pre_out_gain, + 44 => self.post_b1_type as f32, + 45 => self.post_b1_freq, + 46 => self.post_b1_gain, + 47 => self.post_b1_q, + 48 => self.post_b2_type as f32, + 49 => self.post_b2_freq, + 50 => self.post_b2_gain, + 51 => self.post_b2_q, + 52 => self.post_b3_type as f32, + 53 => self.post_b3_freq, + 54 => self.post_b3_gain, + 55 => self.post_b3_q, + 56 => self.post_tilt, + 57 => self.post_pivot, + 58 => self.post_out_gain, + 59 => self.lookahead, + 60 => self.eq_pre_bypass as i32 as f32, + 61 => self.eq_post_bypass as i32 as f32, + 62 => self.eq_module_bypass as i32 as f32, + 63 => self.sc_on as i32 as f32, + 64 => self.sc_gain, + 65 => self.sc_hp, + 66 => self.sc_lp, + 67 => self.sc_mix, + 70 => self.comp_mode as f32, + 71 => self.up_range, + 68 => self.lim_on as i32 as f32, + _ => return None, + }) + } + + /// Store `v` at UI slot `slot` the way the plug-in holds a value the editor or a preset writes: clamped, sent as + /// `(v - min) / (max - min)`, unnormalised by nih-plug (ints rounded, switches above one half) and snapped to the + /// step. Returns false for an unknown slot. + pub fn set(&mut self, slot: usize, v: f32) -> bool { + match slot { + 1 => self.shape = (((v - 0.0) / (16.0 - 0.0)).clamp(0.0, 1.0) * (16 - 0) as f32).round() as i32 + 0, + 2 => self.drive = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 100.0), + 3 => self.bias = (((((v - -100.0) / (100.0 - -100.0)).clamp(0.0, 1.0) * (100.0 - -100.0) + -100.0) / 0.1).round() * 0.1).clamp(-100.0, 100.0), + 69 => self.asym = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 4 => self.sat_hp = (((((v - 20.0) / (2000.0 - 20.0)).clamp(0.0, 1.0) * (2000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 2000.0), + 5 => self.sat_lp = (((((v - 200.0) / (20000.0 - 200.0)).clamp(0.0, 1.0) * (20000.0 - 200.0) + 200.0) / 1.0).round() * 1.0).clamp(200.0, 20000.0), + 6 => self.tone = (((((v - 1000.0) / (20000.0 - 1000.0)).clamp(0.0, 1.0) * (20000.0 - 1000.0) + 1000.0) / 1.0).round() * 1.0).clamp(1000.0, 20000.0), + 7 => self.os = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 8 => self.thresh = (((((v - -40.0) / (0.0 - -40.0)).clamp(0.0, 1.0) * (0.0 - -40.0) + -40.0) / 0.1).round() * 0.1).clamp(-40.0, 0.0), + 9 => self.ratio = (((((v - 1.0) / (20.0 - 1.0)).clamp(0.0, 1.0) * (20.0 - 1.0) + 1.0) / 0.1).round() * 0.1).clamp(1.0, 20.0), + 10 => self.attack = (((((v - 0.05) / (100.0 - 0.05)).clamp(0.0, 1.0) * (100.0 - 0.05) + 0.05) / 0.01).round() * 0.01).clamp(0.05, 100.0), + 11 => self.release = (((((v - 5.0) / (2000.0 - 5.0)).clamp(0.0, 1.0) * (2000.0 - 5.0) + 5.0) / 1.0).round() * 1.0).clamp(5.0, 2000.0), + 12 => self.speed = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 13 => self.knee = (((((v - 0.0) / (24.0 - 0.0)).clamp(0.0, 1.0) * (24.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 24.0), + 14 => self.knee_shape = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 15 => self.detector = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 16 => self.det_hp = (((((v - 0.0) / (400.0 - 0.0)).clamp(0.0, 1.0) * (400.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 400.0), + 18 => self.ff_fb = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 19 => self.gr_dist = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 20 => self.makeup = (((((v - 0.0) / (24.0 - 0.0)).clamp(0.0, 1.0) * (24.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 24.0), + 21 => self.mix = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 22 => self.out_gain = (((((v - -24.0) / (12.0 - -24.0)).clamp(0.0, 1.0) * (12.0 - -24.0) + -24.0) / 0.1).round() * 0.1).clamp(-24.0, 12.0), + 23 => self.gain_match = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 25 => self.sat_mix = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 26 => self.bypass = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 27 => self.sat_out = (((((v - -24.0) / (12.0 - -24.0)).clamp(0.0, 1.0) * (12.0 - -24.0) + -24.0) / 0.1).round() * 0.1).clamp(-24.0, 12.0), + 29 => self.pre_b1_type = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 30 => self.pre_b1_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 31 => self.pre_b1_gain = (((((v - -18.0) / (18.0 - -18.0)).clamp(0.0, 1.0) * (18.0 - -18.0) + -18.0) / 0.1).round() * 0.1).clamp(-18.0, 18.0), + 32 => self.pre_b1_q = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 33 => self.pre_b2_type = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 34 => self.pre_b2_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 35 => self.pre_b2_gain = (((((v - -18.0) / (18.0 - -18.0)).clamp(0.0, 1.0) * (18.0 - -18.0) + -18.0) / 0.1).round() * 0.1).clamp(-18.0, 18.0), + 36 => self.pre_b2_q = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 37 => self.pre_b3_type = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 38 => self.pre_b3_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 39 => self.pre_b3_gain = (((((v - -18.0) / (18.0 - -18.0)).clamp(0.0, 1.0) * (18.0 - -18.0) + -18.0) / 0.1).round() * 0.1).clamp(-18.0, 18.0), + 40 => self.pre_b3_q = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 41 => self.pre_tilt = (((((v - -12.0) / (12.0 - -12.0)).clamp(0.0, 1.0) * (12.0 - -12.0) + -12.0) / 0.1).round() * 0.1).clamp(-12.0, 12.0), + 42 => self.pre_pivot = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 43 => self.pre_out_gain = (((((v - -12.0) / (12.0 - -12.0)).clamp(0.0, 1.0) * (12.0 - -12.0) + -12.0) / 0.1).round() * 0.1).clamp(-12.0, 12.0), + 44 => self.post_b1_type = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 45 => self.post_b1_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 46 => self.post_b1_gain = (((((v - -18.0) / (18.0 - -18.0)).clamp(0.0, 1.0) * (18.0 - -18.0) + -18.0) / 0.1).round() * 0.1).clamp(-18.0, 18.0), + 47 => self.post_b1_q = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 48 => self.post_b2_type = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 49 => self.post_b2_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 50 => self.post_b2_gain = (((((v - -18.0) / (18.0 - -18.0)).clamp(0.0, 1.0) * (18.0 - -18.0) + -18.0) / 0.1).round() * 0.1).clamp(-18.0, 18.0), + 51 => self.post_b2_q = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 52 => self.post_b3_type = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 53 => self.post_b3_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 54 => self.post_b3_gain = (((((v - -18.0) / (18.0 - -18.0)).clamp(0.0, 1.0) * (18.0 - -18.0) + -18.0) / 0.1).round() * 0.1).clamp(-18.0, 18.0), + 55 => self.post_b3_q = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 56 => self.post_tilt = (((((v - -12.0) / (12.0 - -12.0)).clamp(0.0, 1.0) * (12.0 - -12.0) + -12.0) / 0.1).round() * 0.1).clamp(-12.0, 12.0), + 57 => self.post_pivot = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 58 => self.post_out_gain = (((((v - -12.0) / (12.0 - -12.0)).clamp(0.0, 1.0) * (12.0 - -12.0) + -12.0) / 0.1).round() * 0.1).clamp(-12.0, 12.0), + 59 => self.lookahead = (((((v - 0.0) / (10.0 - 0.0)).clamp(0.0, 1.0) * (10.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 10.0), + 60 => self.eq_pre_bypass = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 61 => self.eq_post_bypass = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 62 => self.eq_module_bypass = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 63 => self.sc_on = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 64 => self.sc_gain = (((((v - -24.0) / (24.0 - -24.0)).clamp(0.0, 1.0) * (24.0 - -24.0) + -24.0) / 0.1).round() * 0.1).clamp(-24.0, 24.0), + 65 => self.sc_hp = (((((v - 20.0) / (2000.0 - 20.0)).clamp(0.0, 1.0) * (2000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 2000.0), + 66 => self.sc_lp = (((((v - 200.0) / (20000.0 - 200.0)).clamp(0.0, 1.0) * (20000.0 - 200.0) + 200.0) / 1.0).round() * 1.0).clamp(200.0, 20000.0), + 67 => self.sc_mix = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 70 => self.comp_mode = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 71 => self.up_range = (((((v - 0.0) / (24.0 - 0.0)).clamp(0.0, 1.0) * (24.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 24.0), + 68 => self.lim_on = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + _ => return false, + } + true + } + + /// The UI slot of parameter `id`. + pub fn slot_of(id: &str) -> Option { + TABLE.iter().find(|e| e.1 == id).map(|e| e.0) + } +} + +/// The engine's settings for `v`: the one mapping (the plug-in calls it with its parameters' current values). +pub fn to_dsp(v: &Values, curve: Curve) -> crate::Params { + let stage = |bands: [(i32, f32, f32, f32); 3], tilt: f32, pivot: f32, og: f32| EqStageParams { + bands: [0, 1, 2].map(|i| EqBandParams { ty: bands[i].0 as f64, freq: bands[i].1 as f64, gain: bands[i].2 as f64, q: bands[i].3 as f64 }), + tilt: tilt as f64, pivot: pivot as f64, out_gain: og as f64, + }; + crate::Params { + shape: v.shape, curve, asym: v.asym as f64, drive: v.drive as f64, bias: v.bias as f64, + sat_hp: v.sat_hp as f64, sat_lp: v.sat_lp as f64, tone: v.tone as f64, os: v.os, + thresh: v.thresh as f64, ratio: v.ratio as f64, attack: v.attack as f64, + release: v.release as f64, speed: v.speed as f64, knee: v.knee as f64, + knee_shape: v.knee_shape as f64, detector: v.detector as f64, det_hp: v.det_hp as f64, + comp_mode: v.comp_mode, up_range: v.up_range as f64, + ff_fb: v.ff_fb as f64, gr_dist: v.gr_dist as f64, makeup: v.makeup as f64, + mix: v.mix as f64, out_gain: v.out_gain as f64, gain_match: v.gain_match, + sat_mix: v.sat_mix as f64, bypass: v.bypass, sat_out: v.sat_out as f64, + eq: [stage([(v.pre_b1_type, v.pre_b1_freq, v.pre_b1_gain, v.pre_b1_q), (v.pre_b2_type, v.pre_b2_freq, v.pre_b2_gain, v.pre_b2_q), (v.pre_b3_type, v.pre_b3_freq, v.pre_b3_gain, v.pre_b3_q)], v.pre_tilt, v.pre_pivot, v.pre_out_gain), stage([(v.post_b1_type, v.post_b1_freq, v.post_b1_gain, v.post_b1_q), (v.post_b2_type, v.post_b2_freq, v.post_b2_gain, v.post_b2_q), (v.post_b3_type, v.post_b3_freq, v.post_b3_gain, v.post_b3_q)], v.post_tilt, v.post_pivot, v.post_out_gain)], + lookahead_ms: v.lookahead as f64, eq_pre_bypass: v.eq_pre_bypass, + eq_post_bypass: v.eq_post_bypass, eq_module_bypass: v.eq_module_bypass, + sc_on: v.sc_on, sc_gain: v.sc_gain as f64, sc_hp: v.sc_hp as f64, sc_lp: v.sc_lp as f64, sc_mix: v.sc_mix as f64, + lim_on: v.lim_on, + } +} + +#[cfg(test)] +mod spec_tests { + /// ids / slots unique, ranges and defaults sane, every choice list exactly covers its range. + #[test] + fn the_table_is_consistent() { + crate::paramspec::check(super::SPECS).unwrap(); + assert_eq!(super::TABLE.len(), super::SPECS.len()); + let v = super::Values::default(); + for s in super::SPECS { + assert_eq!(v.get(s.slot), Some(s.default), "{}", s.id); + } + } +} diff --git a/rust/satcomp-plugin/Cargo.toml b/rust/satcomp-plugin/Cargo.toml index 78574eb..7aba53a 100644 --- a/rust/satcomp-plugin/Cargo.toml +++ b/rust/satcomp-plugin/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "satcomp" -version = "0.5.3" +version = "0.5.4" edition = "2021" license = "GPL-3.0-or-later" publish = false @@ -12,11 +12,8 @@ crate-type = ["cdylib", "lib"] 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" +nih_plug_egui = { path = "../vendor/nih_plug_egui", default-features = false, features = ["opengl"] } parking_lot = "0.12" -include_dir = "0.7" [target.'cfg(any(target_os = "macos", windows))'.dependencies] rfd = { version = "0.15", default-features = false } diff --git a/rust/satcomp-plugin/src/gui/golden.rs b/rust/satcomp-plugin/src/gui/golden.rs index f341a93..a25b881 100644 --- a/rust/satcomp-plugin/src/gui/golden.rs +++ b/rust/satcomp-plugin/src/gui/golden.rs @@ -143,6 +143,10 @@ impl Rig { 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)); + if satcomp_ui::bench::timing() { + let _ = self.ctx.tessellate(full.shapes, full.pixels_per_point); + return; + } 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)))); @@ -330,6 +334,9 @@ fn script() -> Vec<(String, u64)> { 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); + // the sans mode (FONT MONO | SANS): the rest of the script draws with a sans UI face and its numerals face + r.click("appearance_sans", 133.0, 213.0); + r.idle("appearance_sans_idle", 2, 0.05); 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); @@ -343,6 +350,16 @@ fn script() -> Vec<(String, u64)> { r.idle("scale_menu_idle", 2, 0.05); r.click("scale_menu_close", 300.0, 300.0); + // help overlay: ? on, bubbles over a cell, the plot, a button at the right edge (flips left), a cell at the bottom (flips + // up), then off again + r.click("help_on", 362.0, 16.0); + r.mv("help_drive", 41.0, 215.0); + r.mv("help_plot", 75.0, 120.0); + r.mv("help_bypass", 520.0, 42.0); + r.mv("help_out_gain", 507.0, 300.0); + r.click("help_off", 362.0, 16.0); + r.mv("help_after_off", 41.0, 215.0); + let mut r2 = Rig::new(2.0); r2.size = Vec2::new(1400.0 / 2.0 * 2.0, 840.0); r2.k = 2.5; @@ -384,6 +401,58 @@ fn ui_matches_golden_fixture() { } } +/// Help mode: the `?` button toggles it, hovering then reports the control under the pointer (a cell by its slot, a button +/// by its label, an area by its id), and nothing is reported while it is off. Every reported target has copy. +#[test] +fn help_mode_reports_what_is_under_the_pointer() { + use satcomp_ui::help::HelpKey; + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + r.mv("off", 41.0, 215.0); + assert_eq!(r.st.kit.help_hit, None, "help is off by default"); + r.click("on", 362.0, 16.0); + assert!(r.st.kit.help_on); + for (x, y, want) in [ + (41.0, 215.0, HelpKey::Slot(2)), // DRIVE + (109.0, 205.0, HelpKey::Slot(3)), // BIAS (top half of its cell) + (109.0, 228.0, HelpKey::Slot(69)), // ASYM (bottom half) + (520.0, 42.0, HelpKey::Id("BYPASS".into())), // a button by its label + (75.0, 120.0, HelpKey::Id("plot".into())), // an area + (132.0, 64.0, HelpKey::Id("draw".into())), // the pencil inside the plot wins over the plot + (362.0, 16.0, HelpKey::Id("?".into())), + (160.0, 16.0, HelpKey::Id("save".into())), + (240.0, 16.0, HelpKey::Id("preset".into())), + (342.0, 16.0, HelpKey::Id("prev_next".into())), + ] { + r.mv("hover", x, y); + assert_eq!(r.st.kit.help_hit.as_ref(), Some(&want), "at ({x}, {y})"); + assert!(super::ui::help_copy(&want).is_some(), "{want:?} has no copy"); + } + r.click("off", 362.0, 16.0); + assert!(!r.st.kit.help_on); + r.mv("after", 41.0, 215.0); + assert_eq!(r.st.kit.help_hit, None); +} + +/// FONT MONO | SANS on the Preferences page: SANS keeps the mono face for the numbers and picks Hanken Grotesk for the UI (one +/// packed `ui-font` value), MONO goes back to that mono face alone. +#[test] +fn the_font_mode_switch_packs_the_ui_and_numerals_faces() { + use satcomp_ui::canvas::{font_pack, font_unpack, SANS_START}; + use std::sync::atomic::Ordering::Relaxed; + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + r.click("about", 80.0, 15.0); + r.click("prefs", 180.0, 42.0); + r.idle("prefs_idle", 2, 0.05); + assert_eq!(r.params.font.load(Relaxed), 0, "Fira Code, mono"); + r.click("sans", 133.0, 213.0); + assert_eq!(r.params.font.load(Relaxed) as usize, font_pack(SANS_START, 0)); + assert_eq!(font_unpack(r.params.font.load(Relaxed) as i64), (SANS_START, 0), "Hanken Grotesk + Fira Code"); + r.click("mono", 86.0, 213.0); + assert_eq!(r.params.font.load(Relaxed), 0, "back to Fira Code alone"); +} + #[test] fn limiter_button_writes_its_parameter() { let mut r = Rig::new(1.0); @@ -423,22 +492,83 @@ fn ui_script_is_deterministic() { 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). +/// ASYM is the bottom half of the BIAS / ASYM group: one host parameter for every shaper (a drag writes "Asym"); the top half +/// is still BIAS. #[test] -fn asym_slider_writes_the_shapers_value() { +fn asym_slider_writes_the_asym_parameter() { 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 + assert!(r.writes.iter().any(|w| w.starts_with("set Asym")), "ASYM half wrote nothing: {:?}", r.writes); 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); } + +/// The compressor mode switch (top half of the group at 152, 240) cycles DWNWARD > UPWARD > UP/DWN; RANGE sits under it. +#[test] +fn the_comp_mode_switch_and_range_write_their_parameters() { + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + r.click("mode", 183.0, 249.0); + assert!(r.writes.iter().any(|w| w.starts_with("set Comp Mode")), "{:?}", r.writes); + r.drag("range", 183.0, 268.0, 183.0, 5); + r.drag("range2", 183.0, 268.0, 258.0, 5); + assert!(r.writes.iter().any(|w| w.starts_with("set Range")), "{:?}", r.writes); + // KNEE and K.SHAPE share the next cell + r.drag("knee", 251.0, 249.0, 239.0, 5); + r.drag("kshape", 251.0, 268.0, 258.0, 5); + assert!(r.writes.iter().any(|w| w.starts_with("set Knee ")) && r.writes.iter().any(|w| w.starts_with("set Knee Shape")), "{:?}", r.writes); +} + +/// Multi-instance audit: idle frame cost and memory of one more open editor (`cargo test -p satcomp editor_frame_cost --release +/// -- --ignored --nocapture`). +#[test] +#[ignore] +fn editor_frame_cost() { + satcomp_ui::bench::frame_cost("satcomp", || Rig::new(1.0), |r| r.frame("t", vec![], 0.03)); +} + +/// The EQ view's Q brackets (SatEQ's): clicking a node selects it, then dragging its right bracket sideways writes its Q, and +/// the closed bracket is the higher Q. +#[test] +fn the_eq_q_brackets_of_the_clicked_node_write_its_q() { + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + r.click("eq_on", 387.0, 42.0); + r.idle("eq_idle", 3, 0.05); + // band 1 (80 Hz, 0 dB) sits at (206, 113); at the default Q 0.5 its brackets are 34 px out (the right one lands on band + // 2's node, which wins, so the left one is dragged) + r.click("node", 206.0, 113.0); + // the editor keeps its own copy of what it wrote, so the bracket follows the new Q between drags: read it back each time + let q_now = |r: &Rig| r.st.kit.pending(32).unwrap_or(0.5); + let mut drag = |r: &mut Rig, dx: f32| { + let d = 8.0 + 40.0 * ((10.0f32 / q_now(r)).ln() / 100f32.ln()); + let bx = (205.78 - d).floor() + 0.5; + r.writes.clear(); + r.mv("br/move", bx, 113.0); + r.button("br/down", PointerButton::Primary, true); + r.mv("br/drag", bx + dx, 113.0); + r.button("br/up", PointerButton::Primary, false); + assert!(r.writes.iter().any(|w| w.starts_with("set Pre B1 Q")), "no Q write: {:?}", r.writes); + q_now(r) + }; + let q0 = q_now(&r); + let closed = drag(&mut r, 12.0); + assert!(closed > q0, "closing the bracket raises Q: {q0} -> {closed}"); + let open = drag(&mut r, -20.0); + assert!(open < closed, "opening it lowers Q: {closed} -> {open}"); +} + +/// A bracket lying on another band's node does not steal that node: band 2's left bracket (Q 0.5) falls on band 1's node. +#[test] +fn a_node_under_a_bracket_is_still_grabbed() { + let mut r = Rig::new(1.0); + r.idle("boot", 3, 0.016); + r.click("eq_on", 387.0, 42.0); + r.idle("eq_idle", 3, 0.05); + r.click("node2", 241.0, 113.0); + r.writes.clear(); + r.drag("node1", 206.0, 113.0, 100.0, 3); + assert!(r.writes.iter().any(|w| w.starts_with("set Pre B1 Gain")), "{:?}", r.writes); + assert!(!r.writes.iter().any(|w| w.starts_with("set Pre B2 Q")), "{:?}", r.writes); +} diff --git a/rust/satcomp-plugin/src/gui/golden.txt b/rust/satcomp-plugin/src/gui/golden.txt index 4843b1a..8053809 100644 --- a/rust/satcomp-plugin/src/gui/golden.txt +++ b/rust/satcomp-plugin/src/gui/golden.txt @@ -1,490 +1,509 @@ -boot0 f811687b03ee124e -boot1 592476b2939fb922 -boot2 14272d4aac7463f7 -boot3 0f7324315059d787 -drive_drag/move f493515a98d2de60 -drive_drag/down d4a5b3040f25f560 -drive_drag/drag1 7b21ae6d252d262e -drive_drag/drag2 e4cd13eae5f322bf -drive_drag/drag3 efcdd967f016706b -drive_drag/drag4 95ac7f5ba6cf9e05 -drive_drag/drag5 b826e43ee8bd275d -drive_drag/drag6 76c530c37fe448eb -drive_drag/up 81294cef789fd52f -drive_drag/settle 64087b6cd90b5dff -thresh_wheel/move a37217784ee0343e -thresh_wheel/wheel c1df4b88c5b32425 -thresh_wheel/settle 063a4af02025e60c -thresh_wheel_dn/move 2e7dc839f2c847f9 -thresh_wheel_dn/wheel d2997cf100a48874 -thresh_wheel_dn/settle fa00f58dfb6cb159 -ratio_drag/move 991fe21b6133f850 -ratio_drag/down 129200ee0fce49c7 -ratio_drag/drag1 9e4c8c5f1657c664 -ratio_drag/drag2 f242bb968638880f -ratio_drag/drag3 1ce3df687ce97139 -ratio_drag/drag4 7dd8052a2e5b568c -ratio_drag/drag5 8f49ad9138fc0873 -ratio_drag/up cb06851121f6ecc9 -ratio_drag/settle 5dae59fc241cde08 -drive_dbl_a/move 97f2bd2ded8ecd27 -drive_dbl_a/down c60ee89e3e43ffa1 -drive_dbl_a/up 179214b2bd5976d6 -drive_dbl_a/settle f5aa25f4ec3ed373 -drive_dbl_b/move ee4d98d3cad742c6 -drive_dbl_b/down 4f047ede8dc8ac13 -drive_dbl_b/up ae4ebbc3b591fc69 -drive_dbl_b/settle d1a38dd1f49d61c3 -hp_drag/move a8f807dd8424ec58 -hp_drag/down 682fcaf2c4152cf6 -hp_drag/drag1 1894bdf0fa92d49d -hp_drag/drag2 ca097ef429107c70 -hp_drag/drag3 98f644daffa0f971 -hp_drag/drag4 2c63e7b9b2cae6f0 -hp_drag/up 4f86d1ad6d3aa353 -hp_drag/settle 3af5eec459936a70 -lp_drag/move 31dc4afa403f45e3 -lp_drag/down 85fcde703eddbfdc -lp_drag/drag1 4672c619733b9681 -lp_drag/drag2 8496a8d610d7d926 -lp_drag/drag3 1265e55a8d59999d -lp_drag/drag4 e2c6c5bf0f564fd9 -lp_drag/up 3502b0987867c2ae -lp_drag/settle 49e5d1b71977f446 -makeup_drag/move 9a91ca682fad0c83 -makeup_drag/down 4ee0ebd5a70cfc64 -makeup_drag/drag1 1275bce5322f5c93 -makeup_drag/drag2 ef530edd012785ee -makeup_drag/drag3 58e692e4fc57bea7 -makeup_drag/drag4 1d3be0794fd3b07f -makeup_drag/up db9fc10aa8c943d0 -makeup_drag/settle f6798bc6c695d692 -idle_a0 7e2d2cb0d2f5955d -idle_a1 d4f849b5fddee9fb -idle_a2 e278e832bf2d5fc5 -idle_a3 686d55389d14eeae -idle_a4 1f3cf18f775616ee -idle_a5 7c4600e30675c0bb -idle_a6 f79076109370d253 -idle_a7 6430f701dfd0f698 -idle_a8 5898587911d2cd48 -idle_a9 5a78759ced9de941 -shape_next/move 7b039bb5eab50ecb -shape_next/down e364c21120c54bfb -shape_next/up 6134f0c081e87641 -shape_next/settle 5919efa75d029631 -shape_next2/move de86880b68fe312c -shape_next2/down 808bbbfa56b71b74 -shape_next2/up 4f9ddf64922d7184 -shape_next2/settle 4b7a98592622d7df -shape_menu_open/move 9896a856f1fdc2ce -shape_menu_open/down a970a3cb3dce4dde -shape_menu_open/up ee00319e93dd527f -shape_menu_open/settle e62f72ec90d9ed4c -shape_menu_idle0 ec57ced48f08e989 -shape_menu_idle1 5d5d38e5cad1945b -shape_menu_pick/move 16c9197e8ba3e607 -shape_menu_pick/down 807363d31e0211df -shape_menu_pick/up 794c10255c4bd010 -shape_menu_pick/settle 4cfdcb22cc4c5cb5 -shape_prev/move 01be24214ac919c2 -shape_prev/down fdbc66859a7b6a66 -shape_prev/up 47163dd900a7df21 -shape_prev/settle 9df7c861bb75dd6c -os_x2/move 2616f0622fb99bbd -os_x2/down 5e6f556b73d160ba -os_x2/up 256cd1cc1e46351f -os_x2/settle cad732965e93c552 -os_x4/move 456186af51500feb -os_x4/down c7fe423d0da19cab -os_x4/up 909c2be887d372d1 -os_x4/settle 499687bf2d43d768 -os_x1/move 6b00deafefc406e1 -os_x1/down dfbf6b535efdc5b1 -os_x1/up 84a82a2972a2d08b -os_x1/settle ccbdb40a8da577b2 -sidechain_on/move 022890fca7687fc8 -sidechain_on/down 12a1f9fdb18052d2 -sidechain_on/up 648c56197dbdaf72 -sidechain_on/settle 93a20c1e8eaefc04 -sidechain_idle0 f0079c17dda2ba39 -sidechain_idle1 cc2a254430ff2374 -sidechain_idle2 3d615bc9ae61375d -sc_gain_drag/move 26915b2f119ec375 -sc_gain_drag/down 5292af7e418b33b4 -sc_gain_drag/drag1 7d306a4f3dd37d61 -sc_gain_drag/drag2 ea6343ad1798dae2 -sc_gain_drag/drag3 6248b3f5678df16c -sc_gain_drag/up c3455b7dd93b6725 -sc_gain_drag/settle 455f66642687222c -sidechain_off/move 9c5de956a94c7cd2 -sidechain_off/down c7684cfff2aea57a -sidechain_off/up 63e728d4109165fa -sidechain_off/settle bebbbc15d1e71899 -delta_on/move acf0612ee65ab466 -delta_on/down b8d62910a01b8507 -delta_on/up 87727562635a982f -delta_on/settle 3de76f94954b289f -delta_off/move 0926db52dc42c055 -delta_off/down 85ffee51b0aee45d -delta_off/up 998285cd575a1c46 -delta_off/settle a3466f39a0448d7a -bypass_on/move 79ce91d46b54eb9c -bypass_on/down 23b15ee9f93f6226 -bypass_on/up b08917b5a2629792 -bypass_on/settle d057e024a2667646 -bypass_idle0 7f5854606f7e88b6 -bypass_idle1 9a108358b12df96f -bypass_idle2 af1ceb5d28bd7089 -bypass_off/move ba631e0174dfc1c6 -bypass_off/down bac69fcb2d3809cc -bypass_off/up 1a2ee67b583c2539 -bypass_off/settle 2a56a599b2124579 -lim_off/move 96752e9388f94b68 -lim_off/down 1004d9f7d266b5dc -lim_off/up e0362738a79aa643 -lim_off/settle 76fec50f54284f70 -lim_off_idle0 837018677ade66ca -lim_off_idle1 3b203f153a430c26 -lim_off_idle2 c8cf3a9091ad624c -lim_on/move 8220462e0f3d09d1 -lim_on/down 90ac96241ae5f298 -lim_on/up 08f7d8b4c594a2e7 -lim_on/settle 13823b45d74225e5 -gain_match/move cf7df92842d6ec32 -gain_match/down e1c56691d84a1345 -gain_match/up 174a2d5f8b817a65 -gain_match/settle 0600ca24847d3a22 -gain_match_idle0 a92400e8b31d7997 -gain_match_idle1 3255437f5df6ada0 -gain_match_idle2 d2f71415574e1193 -gain_match_idle3 6fe425cb98ebda23 -gain_match_idle4 1187537e79a5f405 -gain_match_idle5 1b67af65f52b003b -gain_match_off/move 4d889cea5b96b799 -gain_match_off/down 8e5eeb7114a6408f -gain_match_off/up 1ba3998937a3c730 -gain_match_off/settle ac6922701b5df744 -pencil_on/move 3e7c46e647ad5a22 -pencil_on/down 069eba6a629521fc -pencil_on/up 327676d671a349e6 -pencil_on/settle 6f315eb211223ce4 -pencil_idle0 b9175ed6b4b552b0 -pencil_idle1 23198266518a3560 -pencil_idle2 2f05fd7ac226807a -curve_pt_add/move 90e3a87d9b0c6e2b -curve_pt_add/down de5c4d2fc3fa30e8 -curve_pt_add/up 36762589812e1592 -curve_pt_add/settle ffeaa22ce16c4936 -curve_pt_drag/move 48ec177cb65e6f6f -curve_pt_drag/down 63e17db503bbb54a -curve_pt_drag/drag1 82a13669162c08c2 -curve_pt_drag/drag2 9796509eb798c3ef -curve_pt_drag/drag3 2c3900bfbca9c1ba -curve_pt_drag/drag4 a8c4a4f6c7e0ab37 -curve_pt_drag/up 112629e1a9daa770 -curve_pt_drag/settle 0b73c2a852caf0a4 -curve_pt_add2/move ae7fcdc4a0cd4a11 -curve_pt_add2/down 2c3b1ca8a4a2ad45 -curve_pt_add2/up 9331888dd4568917 -curve_pt_add2/settle a89ea06dfb1fa05c -pencil_off/move 4b453d4796261d5e -pencil_off/down 58a12a2b712dc524 -pencil_off/up d2da61c2f7b11e42 -pencil_off/settle 214addafa0c24340 -scope_on/move 4f1c5c90ae7bbf76 -scope_on/down a821ecc6fa8e6efa -scope_on/up ce433e6d1f24f4aa -scope_on/settle 2fb13f0205bc50af -scope_idle0 009e07232594f489 -scope_idle1 bbcc49b2bbaace9d -scope_idle2 0954066771b86087 -scope_idle3 91d06bc3fb43ec35 -scope_drag/move 58c93f463c17d194 -scope_drag/down 7b0a43c595943f84 -scope_drag/drag1 37736cf314893600 -scope_drag/drag2 b71de36eb46a32bb -scope_drag/drag3 71d6e90cc675d760 -scope_drag/drag4 c817c97fac8f125c -scope_drag/up aa1e3c90b7617b58 -scope_drag/settle 729a09ec8e736176 -scope_off/move 72cf0423086f36d2 -scope_off/down 63ae0366fe442c4a -scope_off/up 84ab56e67ed2764e -scope_off/settle 1afbbb5427b69f73 -ccurve_drag/move a2d978469bcf645e -ccurve_drag/down 309c1c5f89db6763 -ccurve_drag/drag1 d2b82c50162718ac -ccurve_drag/drag2 ed1b47cf33772bfd -ccurve_drag/drag3 b29a1941d612d7fe -ccurve_drag/drag4 7855f5a1f7a57cdf -ccurve_drag/up 8d425b45190fc9f6 -ccurve_drag/settle 9c388c9786d8f5ad -ccurve_floor_wheel/move 74b3d57186bb927b -ccurve_floor_wheel/wheel 7bd872389f8353ae -ccurve_floor_wheel/settle ef32836cced30ce3 -ccurve_ceil_drag/move 5dcde4876d3cbe82 -ccurve_ceil_drag/down 207717ce9de5b4ff -ccurve_ceil_drag/drag1 1d1023c706feccbb -ccurve_ceil_drag/drag2 7858ea4cf31d8cb7 -ccurve_ceil_drag/drag3 e3834ed53f600fe0 -ccurve_ceil_drag/drag4 9fa1f7cf3eed583e -ccurve_ceil_drag/up 0e49a0556731ec4d -ccurve_ceil_drag/settle a2af586e5cba775b -ccurve_floor_dbl_a/move 3ed29dc8252ef6fe -ccurve_floor_dbl_a/down f81a8ca42a08e453 -ccurve_floor_dbl_a/up 8fd0b85218349e3a -ccurve_floor_dbl_a/settle 310d688ced554fe7 -ccurve_floor_dbl_b/move 77fbb2cea239d409 -ccurve_floor_dbl_b/down 095dc1f9502ab6d7 -ccurve_floor_dbl_b/up 8043faa146b8e20f -ccurve_floor_dbl_b/settle acd26d62237503ce -eq_on/move 0d1a552a8a777a87 -eq_on/down 6debc1230d229999 -eq_on/up bb55ea4e08dd0d45 -eq_on/settle 63081cd3022e004e -eq_idle0 dd23d9cf683dfdf0 -eq_idle1 cdedee6310457f84 -eq_idle2 ec4b264892fbcce7 -eq_idle3 3db3a61327cc6d13 -eq_band_drag/move 2242fcfc66db0415 -eq_band_drag/down 306522b704924c62 -eq_band_drag/drag1 e1390545e2be2797 -eq_band_drag/drag2 21213e2e1c130d68 -eq_band_drag/drag3 0359fd90b72dfb04 -eq_band_drag/drag4 e63bef1c3df780a7 -eq_band_drag/drag5 44774d3679a6808c -eq_band_drag/up ac9faf93eb386e25 -eq_band_drag/settle 971cb600e5268a6b -eq_band2_drag/move 38a44fb8257866e3 -eq_band2_drag/down 9c1e87fd45e80ed0 -eq_band2_drag/drag1 c7e1fc12f2bb17b1 -eq_band2_drag/drag2 b6d692e6c70e06cd -eq_band2_drag/drag3 421466e7e31231f9 -eq_band2_drag/drag4 62804dfe1afe7488 -eq_band2_drag/drag5 4af938617d40c47e -eq_band2_drag/up a81aba5acb0dacb2 -eq_band2_drag/settle 0e7999bf90eaa714 -eq_band_wheel/move 2e984e48abcf0438 -eq_band_wheel/wheel 51a80854d991372b -eq_band_wheel/settle fea195b5842f344e -eq_band_dbl_a/move 19962b5da0a34153 -eq_band_dbl_a/down 4aac6f581cb05458 -eq_band_dbl_a/up ad3b50514711c6b6 -eq_band_dbl_a/settle 748a96f3ca4a3d78 -eq_band_dbl_b/move 7839fe00f9cdb56b -eq_band_dbl_b/down c19dc5b8670adac7 -eq_band_dbl_b/up 6af130ee94f29e5c -eq_band_dbl_b/settle c8cdf48747226796 -eq_type_icon/move bf67b366a5ded738 -eq_type_icon/down a7559827fe4955de -eq_type_icon/up a9e9bff0d5c9d659 -eq_type_icon/settle 213fd0f5b822eef1 -eq_type_icon2/move fe23d38cfb9b18eb -eq_type_icon2/down b43819b86f2315a3 -eq_type_icon2/up 45ea5e2cd62e1773 -eq_type_icon2/settle a61f16f38e450611 -eq_freq_cell/move b4e9fff7c8fab543 -eq_freq_cell/down c4210cbe93c27d72 -eq_freq_cell/drag1 303934ca10d216e3 -eq_freq_cell/drag2 ec52c8a761a1c84c -eq_freq_cell/drag3 17af918c48d1ef98 -eq_freq_cell/drag4 c25229e5fa9f66b3 -eq_freq_cell/up d0dcd111e957e57b -eq_freq_cell/settle bc326c1e24df1905 -eq_gain_cell/move e759d677f7bd9416 -eq_gain_cell/down 33ce26a37820face -eq_gain_cell/drag1 6814812f1c12014c -eq_gain_cell/drag2 57cfc8ea8412f00e -eq_gain_cell/drag3 4cb03dd058fa4fc3 -eq_gain_cell/drag4 66edea5698da053a -eq_gain_cell/up b91ffc373f6105af -eq_gain_cell/settle 9e783a6d6148f7c6 -eq_tilt_cell/move 9655bb2c13b72470 -eq_tilt_cell/down 42149029b6e74ffa -eq_tilt_cell/drag1 b2400a042b71936f -eq_tilt_cell/drag2 ef2e4b094d88d7a8 -eq_tilt_cell/drag3 41906062123d5340 -eq_tilt_cell/drag4 01cdc4d9326a5e1d -eq_tilt_cell/up 09261f03182d3143 -eq_tilt_cell/settle 14fb69aa8e60e1a5 -eq_stage_toggle/move a0087c80dcba79c7 -eq_stage_toggle/down d16f18b80bbd840a -eq_stage_toggle/up fbff04a3790e432c -eq_stage_toggle/settle 4155086ca05a11a0 -eq_stage_idle0 eff2a8d8ad669ee3 -eq_stage_idle1 d4d2e75fb035e0ef -eq_stage_idle2 8ee104969f9d530d -eq_stage_toggle2/move 42cf6aa3be130eef -eq_stage_toggle2/down 8a48e3e91ae232fe -eq_stage_toggle2/up 733cad2f44d2262e -eq_stage_toggle2/settle 457203f333da166e -eq_module_byp/move b449d0445f7af882 -eq_module_byp/down 2bcfc523ca401ec0 -eq_module_byp/up 74ad6c391adb512a -eq_module_byp/settle faed87dd8be9e3c3 -eq_byp_idle0 319a039d3cc5b933 -eq_byp_idle1 0605d3fdf56c6007 -eq_module_byp_off/move 269c55ba16fe26b4 -eq_module_byp_off/down c05321894513eadb -eq_module_byp_off/up fc8cf9e92b3dd7a2 -eq_module_byp_off/settle 579d8baedad579dc -eq_off/move 99117633b7929c74 -eq_off/down 4aea672f0380282b -eq_off/up 87d829cb39b03949 -eq_off/settle 4c1dbfb8dd64a099 -preset_next/move ad009c47206a62c9 -preset_next/down 7b952dee8b143542 -preset_next/up f646aec5abf439cd -preset_next/settle 99f3ed1115f7b32e -preset_next_idle0 67ff51f3680fc921 -preset_next_idle1 c9676a091a163ed2 -preset_next_idle2 6b90603c29cfcdac -preset_next2/move 55be7e72e727b271 -preset_next2/down b1a83be928c69236 -preset_next2/up f327c93f48e8c937 -preset_next2/settle c1b03487673604c5 -preset_prev/move 3102214a121c3f75 -preset_prev/down e2fa1fa49239d476 -preset_prev/up de608e1a61568c11 -preset_prev/settle 8abe9208e105e24a -preset_idle0 9ebd41e55cb4b527 -preset_idle1 0d9a577ba21a02e9 -preset_idle2 06b348b331dccaed -preset_idle3 953e7a319074d4fd -preset_idle4 46e84ce788660b60 -preset_idle5 93354b0f10acb291 -preset_idle6 a6530171cbd2450b -preset_idle7 69b483957c0a50a9 -logo_single/move 8c20eb5f0571e6f1 -logo_single/down b66e539952106c19 -logo_single/up 3397216fbe94f020 -logo_single/settle 3e7ba41ee644d1c2 -logo_single_wait0 4fad368b866c365e -logo_single_wait1 f0e42422a4585c86 -logo_single_wait2 bfe4bd03543e6d51 -logo_single_wait3 449402b97e0b6400 -logo_single_wait4 a15f941d055cafd1 -logo_single_wait5 698bd584cdab5c55 -logo_single_wait6 ee9a6372cafcd2bb -logo_single_wait7 cf150f702c6ac460 -logo_menu/move 820c885c70f75946 -logo_menu/down ffde5625a0348d85 -logo_menu/up 08706a5bf2a4961f -logo_menu/settle be9be5949b1d244f -logo_menu_idle0 66f72b893da92eca -logo_menu_idle1 0d8a0da8d28adcc9 -logo_menu_pick/move 645a1b92eab3001e -logo_menu_pick/down 90b51a863281a452 -logo_menu_pick/up 5267605c8d4d72c0 -logo_menu_pick/settle 62af398239fd3580 -logo_dbl_a/move 4516ccd079df815f -logo_dbl_a/down 418dce2ba76f721d -logo_dbl_a/up 310d0acc22184c3d -logo_dbl_a/settle 52421debb1b2a27d -logo_dbl_b/move 0b5852614174de12 -logo_dbl_b/down 9772b900a0034b44 -logo_dbl_b/up 10d1565c93803bc0 -logo_dbl_b/settle a25e5c6e348e9fdb -light_idle0 415620204c52f8f0 -light_idle1 3d439fc7d73962d6 -light_idle2 43e176e9efc00bbb -logo_dbl2_a/move 2d72cb510af8386a -logo_dbl2_a/down 758642cd58e4dc92 -logo_dbl2_a/up d336a01b014dd233 -logo_dbl2_a/settle 68e343fa52274a9b -logo_dbl2_b/move 9a17f131e277f1fc -logo_dbl2_b/down 6f6ec638134a1245 -logo_dbl2_b/up e74b59be26d01b8e -logo_dbl2_b/settle ab6aef15d74ecf36 -about_open/move b712930fb38f36f0 -about_open/down 33801f5fde9380b0 -about_open/up 33ec6cf1bce0ceb8 -about_open/settle 713e0491e040e20b -about_idle0 d199950da971a92c -about_idle1 5cb58a403a75725a -about_idle2 d0d19043a079c48d -about_scroll/move 109fd92ee7fef2a5 -about_scroll/wheel 6d886e5c44995f3d -about_scroll/settle b28954a0249d6c61 -about_scroll2/move 66cb8d13a870e49e -about_scroll2/wheel c9f4dd7397403779 -about_scroll2/settle 23dad40bdb1f7b85 -about_tab_appearance/move e7defc7605216d5e -about_tab_appearance/down c95445f7da9ec748 -about_tab_appearance/up dad89f6e83ada316 -about_tab_appearance/settle 41b9ab6f9b487642 -appearance_idle0 1e4fa13cbb8d82a0 -appearance_idle1 1ecca3ac3f2cdc96 -appearance_scroll/move 02c102b5e31cd67e -appearance_scroll/wheel cfc9c5b2ab9cd197 -appearance_scroll/settle 84e81a151c2a679b -appearance_scheme_pick/move dea88090b445e82e -appearance_scheme_pick/down 1aa7ad0967bb9044 -appearance_scheme_pick/up 48e958fd83ee5803 -appearance_scheme_pick/settle 9825e15a16ee7dfd -appearance_font_pick/move 700db933157fc31a -appearance_font_pick/down 411002691bce3678 -appearance_font_pick/up 411002691bce3678 -appearance_font_pick/settle 4636114778c039ef -appearance_font_pick2/move da09dc0fdad84ac9 -appearance_font_pick2/down d160d7ed1bd0564d -appearance_font_pick2/up 398563c7af32ddf2 -appearance_font_pick2/settle abe1d690a2223032 -about_tab_changelog/move fdacbe2c496d002a -about_tab_changelog/down 9ce47f8d5b2cd86f -about_tab_changelog/up 0f7ecf80fe710b61 -about_tab_changelog/settle bc0b69f242937fd0 -changelog_idle0 6f07046a62abe830 -changelog_idle1 87ffb2a003ecc4c4 -changelog_scroll/move 68e410389377f923 -changelog_scroll/wheel 178e0b98e0ebdbbc -changelog_scroll/settle 2da44795e61e3c85 -changelog_thumb/move adc6254de9342aa6 -changelog_thumb/down 0b43060eb9ca21ae -changelog_thumb/drag1 6856dc25709da849 -changelog_thumb/drag2 f77e82ac61b4a09d -changelog_thumb/drag3 b1553572116757db -changelog_thumb/drag4 48eac5d86c95a0f9 -changelog_thumb/up 9699784d4579889c -changelog_thumb/settle 0f9ab62a76455532 -about_tab_about/move 2c133b1d274e6266 -about_tab_about/down 87dd5e1db89bb8f0 -about_tab_about/up 549c281354bf0a32 -about_tab_about/settle 23ad1339105f9559 -about_close/move 9392ab98c9c9a4a6 -about_close/down 44be6a55380c6b77 -about_close/up 5d9992d4b1cb8341 -about_close/settle 0c9be9fb56945823 -closed_idle0 4f6d464c353319b4 -closed_idle1 08670752ca165f5f -closed_idle2 2eea9e1e4453fcc4 -scale_menu_open/move d60503f53c678e63 -scale_menu_open/down 8d175daa7484b278 -scale_menu_open/up 731ab353b8adce42 -scale_menu_open/settle e033710e51f0877c -scale_menu_idle0 c2031aff50586ee9 -scale_menu_idle1 ee0dd0c98ba4dce3 -scale_menu_close/move ed4b95289387d2da -scale_menu_close/down be6d19f324565aa4 -scale_menu_close/up d613b4334800ecf2 -scale_menu_close/settle a8a803b8bfe81efb -hidpi:hidpi_boot0 7c97a1b45899503c -hidpi:hidpi_boot1 d6d6758ed6d6eee5 -hidpi:hidpi_boot2 ff6b393a4f454e65 -hidpi:hidpi_boot3 9c972060edb8c3b1 -hidpi:hidpi_drive/move 9bd0ba650b5a78a1 -hidpi:hidpi_drive/down 9efc829fcfc9ccae -hidpi:hidpi_drive/drag1 046831c90184d743 -hidpi:hidpi_drive/drag2 1ee39bd6a0299d0c -hidpi:hidpi_drive/drag3 201e0604aded1fcc -hidpi:hidpi_drive/drag4 1637e40c32a5d291 -hidpi:hidpi_drive/up 046febbe9e389ac3 -hidpi:hidpi_drive/settle b85efd194b8fe1c1 -hidpi:hidpi_eq_on/move 4a07f4aaabe92d5c -hidpi:hidpi_eq_on/down 4deca708e1955ca0 -hidpi:hidpi_eq_on/up afabf039462e27e7 -hidpi:hidpi_eq_on/settle 2afd64a2bb5934ae -hidpi:hidpi_idle0 1457a9f4e359a3ef -hidpi:hidpi_idle1 f75869ce985b3597 -hidpi:hidpi_idle2 3c92f5aa53ed4b09 +boot0 867ffd3ddd98c091 +boot1 6726990ea3b31101 +boot2 2c804a7abc0a4e7c +boot3 7f71ba845a48d398 +drive_drag/move 75d3190ea2d2aef7 +drive_drag/down a5d980af3144392b +drive_drag/drag1 083bfba9dc124977 +drive_drag/drag2 0aeb3d905ef5fb42 +drive_drag/drag3 89e207c4b99a7957 +drive_drag/drag4 c9fcac08f68fb2a2 +drive_drag/drag5 996c1f0cdbd559bf +drive_drag/drag6 d4e6edb15a552307 +drive_drag/up e2ef2b7ebcdd9ab7 +drive_drag/settle e0b7904c3f041274 +thresh_wheel/move 644eff3d0c4da7d0 +thresh_wheel/wheel 7643dc83efab7c7f +thresh_wheel/settle 51070a4e29e937ba +thresh_wheel_dn/move 9bc6e35a2aec68a9 +thresh_wheel_dn/wheel 921ed17e624e1997 +thresh_wheel_dn/settle 5b815e384d959c2e +ratio_drag/move 5d482d862eee5023 +ratio_drag/down 96b1c5d0d87e2fa2 +ratio_drag/drag1 254ede93c466ecf5 +ratio_drag/drag2 7aee1bc780be1d30 +ratio_drag/drag3 41aa07595d5e55e2 +ratio_drag/drag4 4b0dd5c430c91630 +ratio_drag/drag5 c96f9b409a95bada +ratio_drag/up 9da145e88b1fa1e2 +ratio_drag/settle 75e2ec44cdaa9aad +drive_dbl_a/move 6eddd51edcd00958 +drive_dbl_a/down f8ca13c79fda9412 +drive_dbl_a/up a88b1f9834f60fe9 +drive_dbl_a/settle bcc179e9f410b800 +drive_dbl_b/move e8788e185ad02cf9 +drive_dbl_b/down b800cdef21be0134 +drive_dbl_b/up 6d5a02011ba422fe +drive_dbl_b/settle 50fac046da5a59ec +hp_drag/move 3179507aac86dfa3 +hp_drag/down 25371a158b57a154 +hp_drag/drag1 30a047c2df350e6f +hp_drag/drag2 820adeff2459af49 +hp_drag/drag3 45a71d8b38bdf6af +hp_drag/drag4 73945f9b76079c1c +hp_drag/up 6781bd854b4bc0d4 +hp_drag/settle c0a020f2853262d8 +lp_drag/move 41759ce440cb8f5b +lp_drag/down 38b4b1dd66cb9220 +lp_drag/drag1 7ae5b331bd775c56 +lp_drag/drag2 7066cbd2731dbd91 +lp_drag/drag3 e721e9c6e2e6399a +lp_drag/drag4 a1c6b41970188a16 +lp_drag/up c64da0680f051429 +lp_drag/settle 22430d4d08af9e2b +makeup_drag/move bb20921f71fffb32 +makeup_drag/down a2e100e8c0b37ff9 +makeup_drag/drag1 0868cc88f74c2ba1 +makeup_drag/drag2 4420ac9c45ad91e9 +makeup_drag/drag3 f38278867c4c72ba +makeup_drag/drag4 8e107dacfa6a3b65 +makeup_drag/up c79fd062f4d44f5a +makeup_drag/settle 77a6fee5914dca04 +idle_a0 d8ce7b3e372610c7 +idle_a1 55758df0fc0af72f +idle_a2 ed2935f91e020ddd +idle_a3 bec78561018d8efe +idle_a4 df47fe66d3cc6e40 +idle_a5 2f82e2ba59cd4569 +idle_a6 f2d668c1430e8d21 +idle_a7 d4a2b9e87460b466 +idle_a8 0f814d1bb0bd138e +idle_a9 b768321b7bd976a4 +shape_next/move 709146d265fa85fe +shape_next/down be4d63d0330e7db8 +shape_next/up c7ae1fcaeb733400 +shape_next/settle 84fba56e4f9a5938 +shape_next2/move fd18b46496be80ed +shape_next2/down 8e23637f829ed0d3 +shape_next2/up 33415b3d719d7b44 +shape_next2/settle 4e11f4f767248411 +shape_menu_open/move 5ed51f1e034cf000 +shape_menu_open/down 24bd4cb6411ffb2f +shape_menu_open/up 81c9fddc150a6586 +shape_menu_open/settle cc32d87363ed274f +shape_menu_idle0 67213c717c86faa2 +shape_menu_idle1 d617391b4aa546dc +shape_menu_pick/move 3ca6f1df8997bd20 +shape_menu_pick/down 8fb4568fe7a4db3c +shape_menu_pick/up aaa4e49d8d1eee48 +shape_menu_pick/settle dd92e8735b769bdd +shape_prev/move 117326150652f548 +shape_prev/down 285035f4fe59e25f +shape_prev/up 4b7ff0bc307c911e +shape_prev/settle 70af9d515a379f1f +os_x2/move 0d50a68a6939def0 +os_x2/down e682578a43b119a5 +os_x2/up ed46cba3280b629f +os_x2/settle 9f50cd8e8ab60166 +os_x4/move e345b2df8eaf17be +os_x4/down 348bb2b77d27bc54 +os_x4/up 17a2424576d34721 +os_x4/settle a656c6b9301aab04 +os_x1/move 022266a1ad90217a +os_x1/down bdecfc8338751478 +os_x1/up c6d09bb86c24bdc5 +os_x1/settle 0acdf4762125bd78 +sidechain_on/move d9358132fc0d9b3a +sidechain_on/down c1cd0a3558f4eddf +sidechain_on/up aaf0e9c42050ce82 +sidechain_on/settle 0b4707783d7fcf1c +sidechain_idle0 2a28af01ba674779 +sidechain_idle1 61a8ea2c631d0631 +sidechain_idle2 83542126cfbae8f1 +sc_gain_drag/move 6f3d775b073756c3 +sc_gain_drag/down 82614cf377d1d5f8 +sc_gain_drag/drag1 9606800b6142183b +sc_gain_drag/drag2 b6cb3e449b5c36ac +sc_gain_drag/drag3 46696d1cc9176d84 +sc_gain_drag/up 8b9b56375f38ece1 +sc_gain_drag/settle 4e032696d6579294 +sidechain_off/move b09ade91f479ce9f +sidechain_off/down 45dcb485ecd3e52e +sidechain_off/up da64e0b25040d425 +sidechain_off/settle 886d2d2c974c86f6 +delta_on/move 422e3ff89e1f7879 +delta_on/down ef2d0d4a88e90d79 +delta_on/up 476137bb4c4c1a40 +delta_on/settle 48c9297a9ed2ff48 +delta_off/move 2b71a12dd9cf6d9e +delta_off/down ce893aebb50457f5 +delta_off/up 0f9ad5d00837052f +delta_off/settle 9422bb97e20d4153 +bypass_on/move a31c8ea4f9605cc5 +bypass_on/down 341d83498be3becc +bypass_on/up d49b046ddff1f0f6 +bypass_on/settle 2989d11bdb895576 +bypass_idle0 7615c903eef5d0d4 +bypass_idle1 3e7eb6d9aef8d93d +bypass_idle2 d182a71587ceb77f +bypass_off/move 1396948fb6e8e1f0 +bypass_off/down b29a232ea41b5412 +bypass_off/up 7a609552392b5f11 +bypass_off/settle 22dc225102d38669 +lim_off/move 66d708929d4b1cc0 +lim_off/down 75ff16f9dbde3353 +lim_off/up eabf8287b5ba51e6 +lim_off/settle 70f4bd875970deb9 +lim_off_idle0 14aa28ff5b6ede1a +lim_off_idle1 350481995737bc92 +lim_off_idle2 f500f1ce9dafc328 +lim_on/move 889e0d31c6115d2a +lim_on/down 4c635d81b0f80c1b +lim_on/up f628ee14baa2fd16 +lim_on/settle 9ae107d5a791d48e +gain_match/move 1000ed588f12388a +gain_match/down c5feaa96fb990ef5 +gain_match/up d1f14d4db895663b +gain_match/settle 9871b4e597ffd9a8 +gain_match_idle0 959b3eb797c8ecbe +gain_match_idle1 6b70ce01cfb73bc9 +gain_match_idle2 87173aa29dc52464 +gain_match_idle3 9f02ad9b219dc256 +gain_match_idle4 31ad4a8c7d9260f2 +gain_match_idle5 0741a78ee1ceda1e +gain_match_off/move b28b79dd5bbefb74 +gain_match_off/down 9bd08ef698e922d8 +gain_match_off/up eab29a3f76aa5767 +gain_match_off/settle 1173cfcd6eefa5b7 +pencil_on/move 80d802f343d34ff4 +pencil_on/down abd9e2bb9f9f60b7 +pencil_on/up 6f598ecc0895aebc +pencil_on/settle 9c0d8019fbe0c042 +pencil_idle0 9ec622c787e5b8a9 +pencil_idle1 b65e3bc9c01a7065 +pencil_idle2 30f75fdfd9bd82cf +curve_pt_add/move abe3d33fd13130f8 +curve_pt_add/down 007aa3637b49a998 +curve_pt_add/up c34f32eef43d83be +curve_pt_add/settle ba62eb0628215522 +curve_pt_drag/move b282f0ab295e5e95 +curve_pt_drag/down aefb706e5012b525 +curve_pt_drag/drag1 7643d77af734e8ab +curve_pt_drag/drag2 c0d4464b28727b42 +curve_pt_drag/drag3 1ea778fbbf5dbf2e +curve_pt_drag/drag4 2c9ceb21310316eb +curve_pt_drag/up 6dd3a3b165494ed0 +curve_pt_drag/settle 0e8402bbd097dec2 +curve_pt_add2/move 496ff21c1fa0bf69 +curve_pt_add2/down bccd104029b9c911 +curve_pt_add2/up d58d64e13fb1ad17 +curve_pt_add2/settle 75be0af95c2f17fc +pencil_off/move c083cab7862ea481 +pencil_off/down b0dea441589434b8 +pencil_off/up cfe1c06a28c72df7 +pencil_off/settle d7ac307388d2f445 +scope_on/move 11e5e1014e2da104 +scope_on/down 05eb23dc4fc8204b +scope_on/up d3cbe7148e2d5037 +scope_on/settle 06dc9514a0a11ffa +scope_idle0 963140453df7ce52 +scope_idle1 71e9f0558fddf702 +scope_idle2 12136ef1da62d400 +scope_idle3 107cd8e3c550469d +scope_drag/move 8675071eb7e36374 +scope_drag/down 4358f0e6543be004 +scope_drag/drag1 5da9cc360783d70e +scope_drag/drag2 1c58b51a0c921a25 +scope_drag/drag3 2ac53d9e3faaddff +scope_drag/drag4 fc8a5c72cb4eedcf +scope_drag/up 20ae331b4424a246 +scope_drag/settle 78e8dca9ec409a0c +scope_off/move 069fb7fe4e458fb0 +scope_off/down 183007618de101e4 +scope_off/up 6d89fbd648099968 +scope_off/settle 297489737fce0fd1 +ccurve_drag/move 84abc62db093f812 +ccurve_drag/down 6b8e0e4261225bff +ccurve_drag/drag1 e2289f28b0e4dc24 +ccurve_drag/drag2 247c26a343da2611 +ccurve_drag/drag3 8358efed89e3e4fa +ccurve_drag/drag4 b3df2ba6ec221f3f +ccurve_drag/up 439cfcea5f97ddfa +ccurve_drag/settle 394f9ad842136a55 +ccurve_floor_wheel/move f1d098f4c0b7ad63 +ccurve_floor_wheel/wheel 8d8057d39d0130a8 +ccurve_floor_wheel/settle f97cc0e124c028c4 +ccurve_ceil_drag/move 977abf71aaec2315 +ccurve_ceil_drag/down 2fb96bf122e66ff7 +ccurve_ceil_drag/drag1 1720a4339ab185b0 +ccurve_ceil_drag/drag2 70134e4115d3b2bb +ccurve_ceil_drag/drag3 4ef9db3590d9a826 +ccurve_ceil_drag/drag4 247efffaba370b79 +ccurve_ceil_drag/up 57fcde99383416d3 +ccurve_ceil_drag/settle f47ee82cf974bbb5 +ccurve_floor_dbl_a/move 1f068948aac764fe +ccurve_floor_dbl_a/down 48230ca17257dd11 +ccurve_floor_dbl_a/up a6a4ea4a5dd8132a +ccurve_floor_dbl_a/settle 1f0bb6f708c1b2fe +ccurve_floor_dbl_b/move f96c7cf7221e8ec6 +ccurve_floor_dbl_b/down 20fa46f914120e9a +ccurve_floor_dbl_b/up ddf284a99a4a3b8b +ccurve_floor_dbl_b/settle 3bc77412d88de35c +eq_on/move a3316b02a0891b53 +eq_on/down 66c4786230cc7e5d +eq_on/up 2f9386367dc0419e +eq_on/settle 69433a32c55c58b2 +eq_idle0 28a71fc2cba9a3d2 +eq_idle1 d3d57ca5a6ed555c +eq_idle2 ccf3fa39b395a6f1 +eq_idle3 db2cc66028b4ee77 +eq_band_drag/move 9d9b86edd938a800 +eq_band_drag/down 24572fbcb4b2c4a5 +eq_band_drag/drag1 167f702354f95d5d +eq_band_drag/drag2 fccac7950b0b2716 +eq_band_drag/drag3 f3f6fe584ea9fe6a +eq_band_drag/drag4 59a35641f91ae529 +eq_band_drag/drag5 3f398bfb79451d84 +eq_band_drag/up c5ab15bdd3725baa +eq_band_drag/settle c2a27b073aed635a +eq_band2_drag/move e0132dbfb44ea482 +eq_band2_drag/down 9f0fd89e740c9151 +eq_band2_drag/drag1 eaeae854f4e09aad +eq_band2_drag/drag2 0654d5958b2a4299 +eq_band2_drag/drag3 6ad1e1f01681ceff +eq_band2_drag/drag4 0d2f4d6b1c082be0 +eq_band2_drag/drag5 cbd68beb5234d246 +eq_band2_drag/up 06870c7cf38e3826 +eq_band2_drag/settle 31a31b5213440fec +eq_band_wheel/move 3d4f3c8ec82a4236 +eq_band_wheel/wheel 4ae26d9e8038fa6b +eq_band_wheel/settle 6fb78726b9bc3baf +eq_band_dbl_a/move 0aeb6f5b2e2b89ec +eq_band_dbl_a/down 1ee4850e8b5cd215 +eq_band_dbl_a/up 869ebcec751f096b +eq_band_dbl_a/settle f74c70ff489523a0 +eq_band_dbl_b/move 1f3aea3ce6ab94a1 +eq_band_dbl_b/down cc8606e4eefc3def +eq_band_dbl_b/up d2738cae1dee9c58 +eq_band_dbl_b/settle f13a7db4644dda96 +eq_type_icon/move 97246fda6f0e0d8c +eq_type_icon/down b496748a4ecaa700 +eq_type_icon/up 341891f43d684538 +eq_type_icon/settle bda84c1a9ec73576 +eq_type_icon2/move 3e690d18828b24b0 +eq_type_icon2/down 98af177d26dced74 +eq_type_icon2/up 366819d08bf33704 +eq_type_icon2/settle af9c3e733b6af0d5 +eq_freq_cell/move 5a5404a8d1a0be4b +eq_freq_cell/down f0993725616f05ce +eq_freq_cell/drag1 59e0893535940290 +eq_freq_cell/drag2 f5d53a5b0b5b2fc8 +eq_freq_cell/drag3 2e89f0d5986b1fc5 +eq_freq_cell/drag4 170acf7e72fdf734 +eq_freq_cell/up 28d3955f4c16ba6a +eq_freq_cell/settle 6410ae2809de3652 +eq_gain_cell/move f7f47c137ee82e7c +eq_gain_cell/down 5af521476d7c1bc0 +eq_gain_cell/drag1 289ffe4f3e707b5c +eq_gain_cell/drag2 0029ec181e9166a8 +eq_gain_cell/drag3 e35289b7b0dd10f6 +eq_gain_cell/drag4 b486948e6efa3cff +eq_gain_cell/up 303caab9c4bbb604 +eq_gain_cell/settle 39d8bb7a7ec29575 +eq_tilt_cell/move 7b17716c46e3e2a5 +eq_tilt_cell/down 33aa7c4150a07507 +eq_tilt_cell/drag1 d3268b8bd01c21ad +eq_tilt_cell/drag2 2ae8bea2328911ac +eq_tilt_cell/drag3 01153e4bcee0ae27 +eq_tilt_cell/drag4 4959717508581a35 +eq_tilt_cell/up c715f0ac50fff224 +eq_tilt_cell/settle af5a40476fcac0e6 +eq_stage_toggle/move 677667e2fde76575 +eq_stage_toggle/down 86aa2edc182b4ab1 +eq_stage_toggle/up 4ddfca1973b71f70 +eq_stage_toggle/settle d89f99a0607cfd9c +eq_stage_idle0 3677cfeae454d9b1 +eq_stage_idle1 2c0a4f40445b3d3b +eq_stage_idle2 833a64494538d0c7 +eq_stage_toggle2/move 2373938144bde1ef +eq_stage_toggle2/down 0f22bb3d8e015f33 +eq_stage_toggle2/up 1a6a939f584bbc87 +eq_stage_toggle2/settle ab4c4bb3458d6837 +eq_module_byp/move f5f4f47ce0488e7f +eq_module_byp/down 5da856d09ae57dcf +eq_module_byp/up e99fabfae5efef7a +eq_module_byp/settle 09e1edb616212192 +eq_byp_idle0 85378f322ee3fd24 +eq_byp_idle1 33a0c5a4e6b39d96 +eq_module_byp_off/move 4af8ca21007837f1 +eq_module_byp_off/down 93986c9b0859c846 +eq_module_byp_off/up f7b65c8ee7d03809 +eq_module_byp_off/settle 44a4010544042363 +eq_off/move a73fc690d5990ba3 +eq_off/down f94bf5866c3864a0 +eq_off/up e2b5abb217b6887d +eq_off/settle fd34d85161be1019 +preset_next/move a42e90e456c33255 +preset_next/down fbd5e8baee1239bc +preset_next/up ca7657d5a8f3f96e +preset_next/settle c9264c181e586c00 +preset_next_idle0 43c26bfcd49e21df +preset_next_idle1 7e22050ad856ffc8 +preset_next_idle2 81a9346903e42f37 +preset_next2/move bf029b85b7a2b67a +preset_next2/down 26a85d6fa79e41ed +preset_next2/up 4253eadd5ef76c19 +preset_next2/settle 86fd6b39d5ecc103 +preset_prev/move fb4b20b80e1104f7 +preset_prev/down 593ef110805a1199 +preset_prev/up a984bc304c39cb1a +preset_prev/settle fcaec946c0dca32d +preset_idle0 253a002f911bae40 +preset_idle1 55bda6e728b6105c +preset_idle2 734aaa3284273284 +preset_idle3 6e2252df4da3abc9 +preset_idle4 cc0dac9a4e532280 +preset_idle5 a3bced11aae481a9 +preset_idle6 a46c08c2087a7463 +preset_idle7 4cc3881b507e5e45 +logo_single/move c7b755a23f33bf99 +logo_single/down fcb74d0fa5983f1e +logo_single/up 3d921987e085fb67 +logo_single/settle 9761a674335f8380 +logo_single_wait0 958a503492596d9c +logo_single_wait1 13e1f16f0679b7b8 +logo_single_wait2 badfb3b0149786df +logo_single_wait3 5e3776a918afa0ce +logo_single_wait4 94a865d340bf8d3b +logo_single_wait5 28aaed9c53c5ca76 +logo_single_wait6 cf272f5932b91e00 +logo_single_wait7 f2ccedbdd7757f0f +logo_menu/move 54fad35da85fe944 +logo_menu/down c3fdaf8d0d132d15 +logo_menu/up 75ea1c7a9a49b5e3 +logo_menu/settle acd83c69c8fee81f +logo_menu_idle0 c80d251097804c06 +logo_menu_idle1 e6c94a8ce79a3221 +logo_menu_pick/move 0072fcda87728382 +logo_menu_pick/down da51c14f3a9f403f +logo_menu_pick/up b715aad3079f32e0 +logo_menu_pick/settle ad173938d9be367c +logo_dbl_a/move 42119e3d66621a4b +logo_dbl_a/down dd1efdeadb3da78d +logo_dbl_a/up a373c935a9464b6e +logo_dbl_a/settle 0c5aeacda8d308be +logo_dbl_b/move 6f43b4815d351a2d +logo_dbl_b/down b777b2b1c146cbad +logo_dbl_b/up 09e1274de29e07e5 +logo_dbl_b/settle 32f633ea7af0ee02 +light_idle0 dd3e3c30496527b9 +light_idle1 bb339d01ce822f3c +light_idle2 9f238561acaeae4d +logo_dbl2_a/move 3d6471a27be17420 +logo_dbl2_a/down 9f2721369faf380c +logo_dbl2_a/up 96333605a35d3b05 +logo_dbl2_a/settle a1e288ceee61d529 +logo_dbl2_b/move c00fad4ebb08a152 +logo_dbl2_b/down 311a99406d5bef4d +logo_dbl2_b/up adbf146418fdbce6 +logo_dbl2_b/settle b37d5ac209acc976 +about_open/move 183d157446264ca0 +about_open/down 46b6a342cc89014f +about_open/up 67bdb483eea9da64 +about_open/settle 6e4abd866decd548 +about_idle0 aa378159c5e94232 +about_idle1 4b12b1290f456d72 +about_idle2 6ddae118a6207ba4 +about_scroll/move f0ef1b6c904db008 +about_scroll/wheel d21620847a603fd3 +about_scroll/settle 726ebaa800e636ae +about_scroll2/move e644f77fd58856b7 +about_scroll2/wheel 23ee53dedb9a2512 +about_scroll2/settle 17ca3333a2d7e5d6 +about_tab_appearance/move 431b7b26296c5efe +about_tab_appearance/down fd0fa33f627d84ab +about_tab_appearance/up ef04e98e5ce4ff48 +about_tab_appearance/settle 98a6f74f8b9acbb0 +appearance_idle0 9e4c8c81aaa68d8a +appearance_idle1 ec4e875bb2b29234 +appearance_scroll/move ad395a27f2818697 +appearance_scroll/wheel 2968bb6d66874786 +appearance_scroll/settle 3f8bbb3df8f17c96 +appearance_scheme_pick/move a862ce00aa35eafb +appearance_scheme_pick/down 87ad88b87c88ab65 +appearance_scheme_pick/up c604ba959fff4b98 +appearance_scheme_pick/settle 7344770cc0d14274 +appearance_font_pick/move ce4f92b4e821474f +appearance_font_pick/down 10da327978110fb1 +appearance_font_pick/up 10da327978110fb1 +appearance_font_pick/settle 8b0d5e13765b9953 +appearance_font_pick2/move 717eec955ffdb401 +appearance_font_pick2/down 005ef06620fbb2ed +appearance_font_pick2/up fb46ae106cabd26c +appearance_font_pick2/settle 7c5cb38984cb2278 +appearance_sans/move 706d79be12441bdd +appearance_sans/down 827387dd0431a5b2 +appearance_sans/up 2b8c5397660f4749 +appearance_sans/settle d0159fc7ecf7ac0d +appearance_sans_idle0 8b439bb507347c9b +appearance_sans_idle1 545ca9927a432b4d +about_tab_changelog/move c81811858db77c7b +about_tab_changelog/down 90af09959d2cd3c9 +about_tab_changelog/up a7e033ec93608895 +about_tab_changelog/settle 3ca693a5ad6f7c56 +changelog_idle0 c787ae0223f33e89 +changelog_idle1 165494d8f750b996 +changelog_scroll/move c41244b805f15f80 +changelog_scroll/wheel 786bf73c6f84978b +changelog_scroll/settle 20f153d9e840f14b +changelog_thumb/move 6b6f3e8d1cfcdf8f +changelog_thumb/down 0c8698de0e8899a2 +changelog_thumb/drag1 a7172b23b4c2a531 +changelog_thumb/drag2 5200882a5efb575f +changelog_thumb/drag3 4b0bf6fa1c314fe3 +changelog_thumb/drag4 2d20f2ec34c60bba +changelog_thumb/up 0ac3cf75ea79da54 +changelog_thumb/settle 8418254e3f174d8b +about_tab_about/move 63318a66e88fe2b8 +about_tab_about/down 59259b93ba6e3847 +about_tab_about/up b23a5c1c4521dfaf +about_tab_about/settle a487357d57113068 +about_close/move 63a90ffa230cca2f +about_close/down 18f0d56f5f324e07 +about_close/up 55eb23cab5b8a612 +about_close/settle 8f6704297b54aacf +closed_idle0 62eb41f3d54d25cf +closed_idle1 aaeb93f90e2c4210 +closed_idle2 5f9c094bb1498643 +scale_menu_open/move 1bde8c0603b754de +scale_menu_open/down 7a16a8fc9dd9fe49 +scale_menu_open/up 3f214fc0b11bbcf8 +scale_menu_open/settle 7bdb252d67b15c96 +scale_menu_idle0 2e06e51b866ba76c +scale_menu_idle1 0661977400d38782 +scale_menu_close/move 815173f21b8dfb11 +scale_menu_close/down 70cd7bff8f47a174 +scale_menu_close/up 05bcadcdf79d4776 +scale_menu_close/settle d77673efd9954f39 +help_on/move 39809cdedf15c0c3 +help_on/down 64b9b4ff56a1647a +help_on/up 00446223d512f3fa +help_on/settle f37a13e2b49d2a17 +help_drive d6f4b47e0e8777a2 +help_plot 730768df6cb1ee89 +help_bypass 5ae78ffef1d7acb5 +help_out_gain 200ba3ed209aa730 +help_off/move 4956e5ede4b113e8 +help_off/down 057e802f9dc33d48 +help_off/up 5942a244137350b5 +help_off/settle d0b79847f9dac2e6 +help_after_off 787af43794b7c0ce +hidpi:hidpi_boot0 1438f7ee83e9ca64 +hidpi:hidpi_boot1 89b24aeba8e3b1fb +hidpi:hidpi_boot2 4cf19cc657c3a541 +hidpi:hidpi_boot3 c9aa7a94f3ba226d +hidpi:hidpi_drive/move 757626c9cb35866b +hidpi:hidpi_drive/down 43602f323f6c6128 +hidpi:hidpi_drive/drag1 c82777c378c361c6 +hidpi:hidpi_drive/drag2 d4e77d36dc8c8215 +hidpi:hidpi_drive/drag3 bf3106c2800d2970 +hidpi:hidpi_drive/drag4 602de1efbf633260 +hidpi:hidpi_drive/up 19556da529407e01 +hidpi:hidpi_drive/settle bd6e289fe2355843 +hidpi:hidpi_eq_on/move 2ab9df7c4579e7dc +hidpi:hidpi_eq_on/down 49d564cb0d2a3c55 +hidpi:hidpi_eq_on/up 05fd352168c83edf +hidpi:hidpi_eq_on/settle fd17f19fafb0f9a6 +hidpi:hidpi_idle0 c45a2b7e0ed965f1 +hidpi:hidpi_idle1 eefdbbedf7d58d6f +hidpi:hidpi_idle2 e121493f3ca315fb diff --git a/rust/satcomp-plugin/src/gui/mod.rs b/rust/satcomp-plugin/src/gui/mod.rs index f71c89f..82b8820 100644 --- a/rust/satcomp-plugin/src/gui/mod.rs +++ b/rust/satcomp-plugin/src/gui/mod.rs @@ -4,7 +4,7 @@ mod golden; use crate::params::SatCompParams; use crate::Shared; -use satcomp_ui::canvas::{Canvas, FONT_NAMES, H, W}; +use satcomp_ui::canvas::{Canvas, H, W}; use satcomp_ui::init_ctx; use nih_plug::prelude::Editor; use nih_plug_egui::egui::{self, LayerId}; @@ -22,7 +22,8 @@ pub(crate) fn run_frame( shared: &Shared, ) { let screen = ctx.screen_rect(); - let s = ((screen.width() / W).min(screen.height() / H) * 4.0).floor() / 4.0; + // quarter steps; a window a pixel or two short of a step (a host rounding the size down) still gets that step + let s = ((screen.width() / W).min(screen.height() / H) * 4.0 + 0.02).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(); @@ -65,7 +66,7 @@ pub(crate) fn run_frame( 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 face = satcomp_ui::canvas::font_sanitize(params.font.load(std::sync::atomic::Ordering::Relaxed)); let state = State::new(pal, light, face, ¶ms); let editor_state = params.editor_state.clone(); let look_params = params.clone(); diff --git a/rust/satcomp-plugin/src/gui/ui.rs b/rust/satcomp-plugin/src/gui/ui.rs index b196b98..1a3abe2 100644 --- a/rust/satcomp-plugin/src/gui/ui.rs +++ b/rust/satcomp-plugin/src/gui/ui.rs @@ -11,7 +11,7 @@ use crate::Shared; use nih_plug::prelude::*; use satcomp_dsp::biquad::{eq_coef, mag_db}; use satcomp_dsp::eq::{decode_band, decode_tilt, kind_of, ui_idx}; -use satcomp_dsp::shapers::{Curve, ShaperLut, CUSTOM, MAX_PTS, MIN_GAP, SHAPER_NAMES}; +use satcomp_dsp::shapers::{shaper_name, shaper_step, shaper_step_clamped, Curve, ShaperLut, CUSTOM, MAX_PTS, MENU_ORDER, MIN_GAP, SHAPER_NAMES}; use satcomp_dsp::GainComputer; use std::ops::{Deref, DerefMut}; use std::sync::atomic::Ordering; @@ -33,12 +33,15 @@ struct MItem { } /// 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 560x336 base size). const SIZES: [f32; 6] = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5]; +/// EQ view Q brackets: distance from the node at max Q, and the extra span down to min Q (pixels; SatEQ's 9 / 70 scaled to +/// this smaller plot) +const EQ_QB_MIN: f32 = 8.0; +const EQ_QB_SPAN: f32 = 40.0; struct Menu { kind: MenuKind, @@ -58,8 +61,12 @@ pub enum Dlg { } mod ccurve; +mod help; mod scope; +#[cfg(test)] +pub(crate) use help::copy as help_copy; + pub struct State { /// widget interaction state (satcomp-ui); `State` derefs to it pub kit: Kit, @@ -78,7 +85,6 @@ pub struct State { /// scope viewport drag start: (mouse x, mouse y, window step, ceiling step) scope_drag: (f32, f32, usize, usize), /// 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, @@ -103,6 +109,10 @@ pub struct State { gr_hold: f32, gr_hold_t: f64, gr_ri: usize, + /// upward compressor lift (dB): decaying display value and its hold, like the gr_* ones + gl_disp: f32, + gl_hold: f32, + gl_hold_t: f64, ovl: f32, ovr: f32, hl_l: f32, @@ -120,6 +130,7 @@ pub struct State { rd_last: f64, rd_tick: bool, rd_gr: f32, + rd_gl: f32, rd_lim: f32, rd_pk: f32, rd_rms: f32, @@ -131,6 +142,8 @@ pub struct State { rd_lvl: f32, // EQ page eqv: usize, + /// per stage, the band whose node was clicked last (it shows the Q brackets); -1 = none yet + eq_sel: [i32; 2], eq_page: bool, ex0: f32, epw: f32, @@ -187,6 +200,7 @@ impl State { self.hl_l_t = now; self.hl_r_t = now; self.gr_hold_t = now; + self.gl_hold_t = now; self.sat_clip_t = -10.0; self.hold_until = now; self.spec_t = now; @@ -194,7 +208,7 @@ impl State { } pub fn new(pal: usize, light: bool, face: usize, params: &SatCompParams) -> Self { - let mut kit = Kit::new(69); + let mut kit = Kit::new(TABLE.iter().map(|e| e.0).max().unwrap_or(0) + 1); 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 }; @@ -206,6 +220,8 @@ impl State { }; sp(2, 0, 0, 0.5); sp(3, 0, 0, 1.0); + sp(69, 0, 0, 1.0); + sp(71, 0, 0, 0.1); sp(4, 1, 1, 1.0); sp(5, 1, 2, 10.0); sp(6, 1, 2, 10.0); @@ -257,7 +273,6 @@ impl State { meter_t: 0.0, scope_t: 0.0, scope_drag: (0.0, 0.0, 0, 0), - asym_drag: (0.0, 0.0), app: AppState::new(), dummy_params: Arc::new(SatCompParams::from_defaults(None)), dummy_shared: Arc::new(Shared::new()), @@ -273,6 +288,9 @@ impl State { gr_hold: 0.0, gr_hold_t: 0.0, gr_ri: 0, + gl_disp: 0.0, + gl_hold: 0.0, + gl_hold_t: 0.0, ovl: 0.0, ovr: 0.0, hl_l: 0.0, @@ -287,6 +305,7 @@ impl State { rd_last: 0.0, rd_tick: false, rd_gr: 0.0, + rd_gl: 0.0, rd_lim: 0.0, rd_pk: 0.0, rd_rms: 0.0, @@ -297,6 +316,7 @@ impl State { rd_ghr: 0.0, rd_lvl: -100.0, eqv: 0, + eq_sel: [-1; 2], eq_page: false, ex0: 0.0, epw: 0.0, @@ -346,7 +366,7 @@ impl State { 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.face = satcomp_ui::canvas::font_sanitize(params.font.load(Ordering::Relaxed)); self.scope_cfg = params.scope.load(Ordering::Relaxed); self.cc_cfg = params.ccurve.load(Ordering::Relaxed); self.restore_custom(params); @@ -465,31 +485,25 @@ impl<'a> AppearanceUi<'a> for Gui<'a> { 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; + self.cv.set_face(face); } fn about_paras(&self) -> &'static [&'static [&'static str]] { ABOUT_TEXT } + fn about_misc(&self) -> &'static [&'static str] { + ABOUT_MISC + } 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 + // the file must exist for the crate's current version (docs/manual/tools/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")), + include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/manual/SatComp/SatComp-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf")), )) } fn draw_flow(&mut self, r: Rect, byp: bool) { @@ -515,14 +529,17 @@ 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 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"], + &["A waveshaping saturator with compressor and 2-stage 3-band EQ.", "Made with bricking intentions (:"], + &["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"], + &["Squash it [DWNWARD], lift the quiet bits [UPWARD], or have it both ways with [UP/DWN]. [RNGE] caps how far the lift goes."], + &["Refine tone with the [PRE-COMP] / [POST-COMP] 3-band EQ, then dial in the desired gain in the output module.", "[Drag] a node in the EQ view for frequency and gain, the brackets of the node clicked last for Q"], ]; +/// Lines under the shared Misc Controls block on the About page. +const ABOUT_MISC: &[&str] = &["[Click] the GR meter to cycle its range", "[Click] the output meter to reset its peak and clip readout"]; /// Changelog, newest first. Keep each entry to two short sentences or fewer. const CHANGELOG: &[(&str, &[&str])] = &[ + ("v0.5.4", &["Compressor modes: DWNWARD as before, UPWARD lifts quiet parts below the threshold (up to RNGE), UP/DWN does both. The GR meter, the compressor plot and the scope follow the mode.", "Two new shapers, Ratio 2:1 and Ratio 4:1, and one ASYM for the saturator that evens out lopsided saturation.", "A help overlay: click ? at the end of the preset bar, then point at any control for a short description of it.", "Preferences: a sans-serif mode for the UI font (FONT MONO | SANS) with its own face for the numbers, and a STARTUP SCALE every new instance opens at. Shift + click on the logo rolls a random colour scheme and font.", "The draw view shows the stretch of the curve the signal reaches."]), ("v0.5.3", &["The draw view takes 20 points (was 10) and gets an EVEN tool next to ODD: it mirrors the drawn half across the Y axis.", "Buttons and switches light up under the pointer, and the header has a redrawn icon with the version next to the name.", "The saturator's oversampling filters are faster, so it uses less CPU with the same sound.", "The compressor plot has CEIL and FLOOR labels to rescale it (up to +18 dB, with a dashed 0 dB line, so a clipped signal is visible), dB legends, and a draggable curve: the line above the threshold sets the ratio, the line below it the threshold."]), ("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."]), @@ -622,7 +639,7 @@ impl<'a> Gui<'a> { format!("{:.1}ms", v) } } - 2 | 12 | 14 | 15 | 17 | 18 | 19 | 21 | 25 | 67 => format!("{:.0}%", v), + 2 | 12 | 14 | 15 | 17 | 18 | 19 | 21 | 25 | 67 | 69 => format!("{:.0}%", v), 3 => format!("{:+.0}%", v), 4 | 16 | 65 => { if v <= if n == 4 || n == 65 { 20.5 } else { 15.0 } { @@ -664,7 +681,8 @@ impl<'a> Gui<'a> { format!("{:.0}ms", v) } } - 13 | 20 => format!("{:.1}dB", v), + 13 | 71 => format!("{:.1}", v), // the compact KNEE / RNGE rows: the unit does not fit + 20 => format!("{:.1}dB", v), 22 | 27 | 64 => format!("{:+.1}dB", v), _ => format!("{:.1}", v), } @@ -680,19 +698,20 @@ impl<'a> Gui<'a> { fn selector(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32) { let aw = 16.0; let cy = y + h * 0.5; + self.help_slot(n, x, y, w, h); 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); + self.click_set(n, shaper_step_clamped(sel, if self.wheel > 0 { -1 } else { 1 }) 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 }); + self.click_set(n, shaper_step(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 }); + self.click_set(n, shaper_step(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); + let items = MENU_ORDER.iter().map(|&i| MItem { label: SHAPER_NAMES[i as usize].to_string(), kind: 0, id: i }).collect(); + self.menu = Some(Menu { kind: MenuKind::Shape, x, y: y + h, items, checked: sel, scroll: 0 }); } self.press = false; } @@ -704,7 +723,7 @@ impl<'a> Gui<'a> { 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(); + let name = shaper_name(sel).to_uppercase(); self.cv.textc(x + aw, y + ((h - 8.0) * 0.5).floor(), w - 2.0 * aw, &name); } @@ -746,6 +765,12 @@ impl<'a> Gui<'a> { /// header logo: left click = next colour scheme, right click = scheme dropdown fn logo(&mut self, x: f32, y: f32) { let hv = self.hit(x, y, 20.0, 20.0); + if hv && self.shift && self.press && self.act == 0 { + // shift + click: the dice, a random colour scheme and font + self.roll_dice(); + self.logo_pend = -1.0; + self.press = false; + } 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 { @@ -771,14 +796,19 @@ impl<'a> Gui<'a> { // plug-in icon in a 20 x 20 plate: 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 { + // (the dice plate is always the filled one: a die face in the background colour) + if self.light != hv || self.shift { self.cv.fill(x, y, 20.0, 20.0); self.cv.setbg(); } else { self.cv.boxr(x, y, 20.0, 20.0); self.setc(false); } - self.cv.logo_art(0, x, y); + if self.shift { + self.cv.dice_art(x, y); + } else { + self.cv.logo_art(0, x, y); + } self.setc(false); } @@ -789,7 +819,7 @@ impl<'a> Gui<'a> { 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); + self.cv.textc_n(x, y + (h * 0.4 + 1.0).floor(), w, &s); let cx = x + (w * 0.5).floor(); let d = self.mval(3).clamp(-12.0, 12.0) / 12.0; let bw = (d.abs() * (w * 0.5 - 3.0)).floor(); @@ -802,6 +832,8 @@ impl<'a> Gui<'a> { } // ------------------------------------------------------------------ meters + /// Compressor meter; click cycles the range (3 / 6 / 12 / 18 dB). Its look follows Comp Mode: DWNWARD = the gain reduction + /// falling from the top (accent), UPWARD = the lift rising from the bottom (gain colour), UP/DWN = centre-tapped (as SatXComp). 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); @@ -813,10 +845,26 @@ impl<'a> Gui<'a> { } else if self.now - self.gr_hold_t > 1.0 { self.gr_hold = (self.gr_hold - 0.4).max(0.0); } + let l = self.env.shared.gl_pk.swap(0.0, Ordering::Relaxed); + self.gl_disp = l.max(self.gl_disp * 0.9); + if l >= self.gl_hold { + self.gl_hold = l; + self.gl_hold_t = self.now; + } else if self.now - self.gl_hold_t > 1.0 { + self.gl_hold = (self.gl_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 mode = (self.sget(70) + 0.5).floor().clamp(0.0, 2.0) as i32; + if mode == 1 { + self.draw_lift_meter(x, y, w, h); + return; + } else if mode == 2 { + self.draw_updown_meter(x, y, w, h); + return; + } let rng = |i: usize| [3.0f32, 6.0, 12.0, 18.0][i.min(3)]; while self.gr_ri < 3 && self.gr_disp > rng(self.gr_ri) { self.gr_ri += 1; @@ -836,7 +884,7 @@ impl<'a> Gui<'a> { 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); + self.cv.textc_n(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; @@ -847,13 +895,129 @@ impl<'a> Gui<'a> { 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); + self.cv.text_n(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); + } + } + } + + /// Colour of gain that is ADDED (the upward compressor's lift): the inverse of the accent, as SatXComp. + pub(super) fn gain_colour(&self) -> [f32; 3] { + satcomp_ui::canvas::gain_colour(self.cv.bk, self.cv.fg, self.cv.ac) + } + + /// the lift as the meters' number window shows it + fn lift_str(l: f32) -> String { + if l >= 9.95 { format!("+{:.0}", l) } else if l > 0.04 { format!("+{:.1}", l) } else { "0.0".to_string() } + } + + /// UPWARD: the lift rises from the bottom in the gain colour, its number (gain colour) in the window at the top. + fn draw_lift_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { + let rng = |i: usize| [3.0f32, 6.0, 12.0, 18.0][i.min(3)]; + while self.gr_ri < 3 && self.gl_disp > rng(self.gr_ri) { + self.gr_ri += 1; + } + let rg = rng(self.gr_ri); + let inv = self.gain_colour(); + let bot = y + h - 1.0; + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.setrgb(inv); + let up = ((h - 2.0) * (self.gl_disp / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, bot - up, w - 2.0, up); + self.setc(false); + let hp = bot - 1.0 - ((h - 3.0) * (self.gl_hold / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, hp, w - 2.0, 1.0); + self.cv.set_font(1); + 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 = Self::lift_str(self.rd_gl); + self.cv.setrgb(inv); + self.cv.textc_n(x, y + 3.0, w, &gs); + self.setc(false); + 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 = bot - (h - 2.0) * (v / rg); + if ty < y + 13.0 { + continue; // under the 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_n(x + 2.0, (ty + 2.0).clamp(y + 14.0, y + h - 11.0), &s); } else { self.cv.fill(x + w - 3.0, ty, 2.0, 1.0); } } } + /// UP/DWN: centre-tapped, as SatXComp. The lift grows up from the centre line (gain colour, number window at the top), the + /// reduction grows down from it (accent, number window at the bottom). + fn draw_updown_meter(&mut self, x: f32, y: f32, w: f32, h: f32) { + let rng = |i: usize| [3.0f32, 6.0, 12.0, 18.0][i.min(3)]; + let peak = self.gl_disp.max(self.gr_disp); + 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); + self.cv.setrgb(inv); + let up_px = (half * (self.gl_disp / 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 / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, cy + 1.0, w - 2.0, dn_px); + self.setc(false); + let hu = cy - (half * (self.gl_hold / 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 / rg).min(1.0)).floor(); + self.cv.fill(x + 1.0, hd, w - 2.0, 1.0); + self.cv.fill(x + 1.0, cy, w - 2.0, 1.0); + self.cv.set_font(1); + // number windows: the lift at the top (gain colour), the reduction at the bottom (accent) + for (top, ny) in [(true, y + 1.0), (false, y + h - 12.0)] { + self.cv.setbg(); + self.cv.fill(x + 1.0, ny, w - 2.0, 11.0); + self.setc(false); + self.cv.fill(x + 1.0, if top { y + 12.0 } else { y + h - 13.0 }, w - 2.0, 1.0); + } + let gs = Self::lift_str(self.rd_gl); + self.cv.setrgb(inv); + self.cv.textc_n(x, y + 3.0, w, &gs); + let r = self.rd_gr; + let rs = if r > 0.04 { format!("-{:.1}", r) } else { "0.0".to_string() }; + self.setc(true); + self.cv.textc_n(x, y + h - 10.0, w, &rs); + self.setc(false); + 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 in [cy + off, cy - off] { + if ty < y + 13.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_n(x + 2.0, (ty - 4.0).clamp(y + 14.0, y + h - 24.0), &s); + } else { + self.cv.fill(x + w - 3.0, ty, 2.0, 1.0); + } + } + } + } + /// 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) { @@ -925,69 +1089,26 @@ impl<'a> Gui<'a> { } 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); + /// Compressor mode switch (DWNWARD / UPWARD / UP/DWN; click or wheel steps through them) over the RANGE slider (the most the + /// upward part lifts; dim in the plain downward mode). As SatXComp's per-band group. + fn up_group(&mut self, x: f32, y: f32) { + let mode = (self.sget(70) + 0.5).floor().clamp(0.0, 2.0) as i32; + let label = ["DWNWARD", "UPWARD", "UP/DWN"][mode as usize]; + if self.btn(x, y, 62.0, 19.0, label, (mode > 0) as u8) { + self.click_set(70, ((mode + 1) % 3) as f32); + } else if self.hit(x, y, 62.0, 19.0) && self.wheel != 0 { + let nx = (mode + if self.wheel > 0 { 1 } else { -1 }).clamp(0, 2); + if nx != mode { + self.click_set(70, nx as f32); + } + self.wheel = 0; + } + let keep = self.dk; + if mode == 0 { + self.set_dk(keep * 0.5); + } + self.cell1(71, x, y + 18.0, 62.0, 20.0, "RNGE"); + self.set_dk(keep); self.setc(false); } @@ -998,11 +1119,13 @@ 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; + // static curve as heard: the shaper minus the share of its even part about the operating point (the bias) that ASYM + // removes, y = f(v) - (1 - k) (f(v) + f(2b - v)) / 2 (the DSP's high-passes pass the whole audio band) + let ak = dsp.asym.clamp(0.0, 100.0) * 0.01; + let b2 = 2.0 * dsp.bias * 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) + l.eval(v) * (1.0 - r) - r * l.eval(b2 - 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); @@ -1091,14 +1214,14 @@ impl<'a> Gui<'a> { 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); + self.cv.text_n(x + 3.0, y + 3.0, &s); let s = if sh.sat_meas.load(Ordering::Relaxed) { self.setc(blink(self.now)); format!("MEAS {:.1}s", sh.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.cv.textr_n(x, y + h - 14.0, w - 3.0, &s); self.setc(false); } @@ -1250,6 +1373,31 @@ impl<'a> Gui<'a> { lx = qx; ly = qy; } + // the signal as it reaches the shaper: the stretch of the curve it covers at the current drive and bias (input peak + // x drive around the bias point), redrawn as a dimmed accent line over the curve (a line only: a dot would sit on the + // handles). It shows how much of a detailed curve a low drive actually uses. + { + let (g, b, pk, on): (f64, f64, f64, bool) = { let d = self.env.dsp; ((d.drive * 0.01 * 36.0 * 0.11512925).exp(), d.bias * 0.01, self.mval(0).min(1.0) as f64, d.drive > 0.0 || d.bias != 0.0) }; + if on && pk > 0.0005 { + let (lo, hi) = ((b - pk * g).max(-1.0) as f32, (b + pk * g).min(1.0) as f32); + if hi > lo { + let keep = self.dk; + self.set_dk(keep * 0.6); + self.setc(true); + let m = ((hi - lo) * 48.0).ceil().max(2.0) as i32; + let (mut ax, mut ay) = (px(lo), py(c.eval(lo as f64) as f32)); + for j in 1..=m { + let vx = lo + (hi - lo) * j as f32 / m as f32; + let (qx, qy) = (px(vx), py(c.eval(vx as f64) as f32)); + self.cv.line(ax, ay, qx, qy); + ax = qx; + ay = qy; + } + self.set_dk(keep); + self.setc(false); + } + } + } 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() { @@ -1278,7 +1426,7 @@ impl<'a> Gui<'a> { self.cv.set_font(1); let tool = if !sym { "FREE" } else if self.even { "EVEN" } else { "ODD" }; self.cv.text(x + 3.0, y + 3.0, &format!("DRAW {tool}")); - self.cv.textr(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, MAX_PTS)); + self.cv.textr_n(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, MAX_PTS)); } // ------------------------------------------------------------------ comp plot @@ -1289,6 +1437,7 @@ impl<'a> Gui<'a> { let cells = [(64usize, "SC", 71.0f32), (65, "HP", 66.0), (66, "LP", 66.0)]; let mut cx = x; for (n, lbl, w) in cells { + self.help_slot(n, cx, y, w, h); let hv = self.hit(cx, y, w, h); if hv && self.press && self.act == 0 { self.begin_drag(n); @@ -1303,7 +1452,7 @@ impl<'a> Gui<'a> { 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); + self.cv.textr_n(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); @@ -1329,6 +1478,12 @@ impl<'a> Gui<'a> { (1.0 - (py - self.ey0) / ((self.eph - 2.0) * 0.5)) * 18.0 } + /// Pixel distance from a node to its Q brackets for Q slot `n` (log Q: closed = max Q, open = min Q). + fn eq_qd(&self, n: usize) -> f32 { + let (qmin, qmax) = (self.meta[n].min, self.meta[n].max); + EQ_QB_MIN + EQ_QB_SPAN * ((qmax / self.sget(n).clamp(qmin, qmax)).ln() / (qmax / qmin).ln()) + } + fn eq_disp_prep(&mut self, st: usize) { let sr = self.env.shared.sample_rate.load(Ordering::Relaxed) as f64; let stage = self.env.dsp.eq[st]; @@ -1421,6 +1576,8 @@ impl<'a> Gui<'a> { let sw = (w / 3.0).floor(); let sel = ui_idx(b, self.sget(n) as f64); let def = if b == 1 { 2 } else { 1 }; + self.help_slot(n, x, y, w, 17.0); + self.help_slot(nq, x, y + 18.0, w, h - 18.0); for i in 0..3usize { let sx = x + i as f32 * sw; if self.hit(sx, y, sw, 17.0) && self.press && self.act == 0 { @@ -1452,7 +1609,7 @@ impl<'a> Gui<'a> { self.cv.set_font(1); self.cv.text(x + 3.0, y + 22.0, "Q"); let s = self.fmt(nq, self.sget(nq)); - self.cv.textc(x + 8.0, y + 22.0, w - 8.0, &s); + self.cv.textc_n(x + 8.0, y + 22.0, w - 8.0, &s); self.cv.fill(x + 2.0, y + h - 4.0, ((t * (w - 4.0)).floor()).max(1.0), 2.0); self.setc(false); } @@ -1481,6 +1638,30 @@ impl<'a> Gui<'a> { } } let mut pvx = self.eq_fx(self.et_p); + // Q brackets of the band clicked last (SatEQ's): drag one sideways, closed = max Q, open = min Q + let sel = self.eq_sel[self.eqv]; + if hv && sel >= 0 && self.press && self.act == 0 { + let b = sel as usize; + let d = self.eq_qd(sb + b * 4 + 3); + let vis = |bx: f32| bx >= x + 1.0 && bx <= x + w - 2.0; + let (nx, ny) = (self.enx[b], self.eny[b]); + // another band's node under the pointer wins (the plot is small: a bracket often lands on a neighbour) + let on_node = (0..3).any(|k| k != b && (self.mx - self.enx[k]).abs() <= 4.5 && (self.my - self.eny[k]).abs() <= 4.5); + let near = !on_node && (self.my - ny).abs() <= 8.0 && [nx - d, nx + d].iter().any(|&bx| vis(bx) && (self.mx - bx).abs() <= 3.0); + if near { + self.act = 112; + self.vt1 = sb + b * 4 + 3; + self.vt2 = 0; + self.press = false; + } + } + if self.act == 112 && self.down && sel >= 0 { + let n = sb + sel as usize * 4 + 3; + let (qmin, qmax) = (self.meta[n].min, self.meta[n].max); + let t = ((self.mx - self.enx[sel as usize]).abs() - EQ_QB_MIN) / EQ_QB_SPAN; + let q = qmax * (qmin / qmax).powf(t.clamp(0.0, 1.0)); + self.setv(n, q); + } if hv && self.wheel != 0 && best >= 0 { self.wheel_adj(sb + best as usize * 4 + 3); } @@ -1488,6 +1669,8 @@ impl<'a> Gui<'a> { if best >= 0 { let bi = best as usize; let n = sb + bi * 4; + let v = self.eqv; + self.eq_sel[v] = best; if self.dbl(130 + best) { let d = self.meta[n + 1].def; self.sset(n + 1, d); @@ -1577,19 +1760,43 @@ impl<'a> Gui<'a> { self.cv.fill(self.enx[b] - 1.0, self.eny[b] - 1.0, 3.0, 3.0); } } + let sel = self.eq_sel[self.eqv]; + if sel >= 0 { + // a bracket outside the plot is not drawn (nor grabbable) + let b = sel as usize; + let d = self.eq_qd(sb + b * 4 + 3); + let (px, py) = (self.enx[b], self.eny[b].floor()); + let (top, bot) = ((py - 7.0).max(y + 1.0), (py + 8.0).min(self.ey0 + self.eph - 2.0)); + self.setc(self.act == 112); + for (bx, dir) in [(px - d, 1.0f32), (px + d, -1.0f32)] { + let bx = bx.floor(); + if bx < x + 1.0 || bx > x + w - 2.0 { + continue; + } + let tx = bx.min(bx + 2.0 * dir).max(x + 1.0); + let tw = 3.0f32.min(x + w - 1.0 - tx); + self.cv.fill(bx, top, 1.0, bot - top); + if py - 7.0 >= y + 1.0 { + self.cv.fill(tx, top, tw, 1.0); + } + if py + 8.0 <= self.ey0 + self.eph - 2.0 { + self.cv.fill(tx, bot - 1.0, tw, 1.0); + } + } + } self.setc(false); self.cv.set_font(1); let s = if self.et_t.abs() < 0.05 { "TILT 0.0dB".to_string() } else { format!("TILT {:+.1}dB", self.et_t) }; - self.cv.text(x + 3.0, y + 2.0, &s); + self.cv.text_n(x + 3.0, y + 2.0, &s); // ---- stage tabs let sw = (w / 2.0).floor(); let ey = y + self.eph; self.sq_tog(60, x + 24.0, ey + 3.0, 8.0); self.sq_tog(61, x + sw + 20.0, ey + 3.0, 8.0); - if self.btn(x, ey, sw, 14.0, "PRE-COMP", (self.eqv == 0) as u8) { + if self.btn_sel(x, ey, sw, 14.0, "PRE-COMP", (self.eqv == 0) as u8) { self.eqv = 0; } - if self.btn(x + sw, ey, w - sw, 14.0, "POST-COMP", (self.eqv == 1) as u8) { + if self.btn_sel(x + sw, ey, w - sw, 14.0, "POST-COMP", (self.eqv == 1) as u8) { self.eqv = 1; } let (a0, a1) = self.eq_active(); @@ -1622,7 +1829,7 @@ impl<'a> Gui<'a> { self.cv.set_font(1); self.cv.text(x + 3.0, 287.0, "GAIN"); self.cv.set_font(2); - self.cv.textc(x, 300.0, 62.0, "---"); + self.cv.textc_n(x, 300.0, 62.0, "---"); } else { self.cell(n + 2, x, 284.0, 62.0, 38.0, "GAIN"); } @@ -1810,17 +2017,11 @@ impl<'a> Gui<'a> { /// 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); + // the shared layer decides what a load writes (the CLI applies the same list) + for (n, v) in p.writes() { 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.env.params.custom_curve.lock() = p.drawn().pts().to_vec(); self.set_preset_name(&p.name); self.base = None; self.hold_until = self.now + 0.6; @@ -1852,25 +2053,12 @@ impl<'a> Gui<'a> { return true; } } - Curve::from_points(&b.curve) != self.env.params.curve_snapshot() || satcomp_dsp::shapers::asym_from(&b.asym) != self.env.params.asym_snapshot() + Curve::from_points(&b.curve) != self.env.params.curve_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 + // the shared layer decides what a preset keeps (the CLI's --save-preset writes the same) + Preset::capture(name, |n| self.sget(n), &self.env.params.curve_snapshot()) } fn preset_count(&self) -> usize { @@ -2015,45 +2203,52 @@ impl<'a> Gui<'a> { self.dlg = None; } - /// Header preset bar (save icon | name | prev next) and the window-scale button. + /// Header preset bar (save square | name | prev next | help `?`) and the window-scale button. fn preset_bar(&mut self) { let (y, h) = (8.0, 16.0); + // the bar spans 152..370: save 16 | name 150 | prev 16 | next 16 | gap 4 | ? 16 + let (sx, nx, nw, ax, qx) = (152.0, 168.0, 150.0, 318.0, 354.0); // save icon - if self.btn(152.0, y, 26.0, h, "", 0) { + if self.btn(sx, y, h, h, "", 0) { self.pending = 2; } - self.over_btn(152.0, y, 26.0, h, 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); + self.help_area("save", sx, y, h, h); + self.over_btn(sx, y, h, h, false); + self.cv.boxr(sx + 3.0, y + 3.0, 10.0, 10.0); + self.cv.fill(sx + 6.0, y + 3.0, 4.0, 3.0); + self.cv.boxr(sx + 5.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, 142.0, h); + let hv = self.hit(nx, y, nw, h); if hv && self.press && self.act == 0 { - self.open_preset_menu(178.0, y + h); + self.open_preset_menu(nx, y + h); self.press = false; } + self.help_area("preset", nx, y, nw, h); self.setc(false); - self.cv.boxr(178.0, y, 142.0, h); + self.cv.boxr(nx, y, nw, h); self.cv.set_font(2); let modified = self.is_modified(); let mut t = shown; - while self.cv.text_w(&t) > if modified { 124.0 } else { 136.0 } && t.chars().count() > 3 { + while self.cv.text_w(&t) > if modified { nw - 18.0 } else { nw - 6.0 } && t.chars().count() > 3 { t.pop(); } if modified { t = format!("*{t}*"); } - self.cv.textc(178.0, y + ((h - 8.0) * 0.5).floor(), 142.0, &t); + self.cv.textc(nx, y + ((h - 8.0) * 0.5).floor(), nw, &t); + // help mode toggle: lit while on (hovering a control then shows its bubble) + self.help_btn(qx, y, h); // prev / next for (i, dir) in [(0, -1), (1, 1)] { - let x = 320.0 + i as f32 * 25.0; - if self.btn(x, y, 25.0, h, "", 0) { + let x = ax + i as f32 * h; + if self.btn(x, y, h, h, "", 0) { self.step_preset(dir); } - self.over_btn(x, y, 25.0, h, false); - let (cx, cy) = (x + 12.5, y + h * 0.5); + self.help_area("prev_next", x, y, h, h); + self.over_btn(x, y, h, h, false); + let (cx, cy) = (x + h * 0.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 { @@ -2067,6 +2262,7 @@ impl<'a> Gui<'a> { let items = SIZES.iter().map(|v| format!("{:.0}%", v * 100.0)).collect(); self.open_menu(MenuKind::Size, 376.0, y + h, items, cur); } + self.help_area("ui_scale", 376.0, y, 42.0, h); } // ------------------------------------------------------------------ about page @@ -2199,9 +2395,9 @@ impl<'a> Gui<'a> { let ytop = cy - bh * 0.5 + 0.5; self.cv.fill(ccx, sy + sh_, 1.0, ytop - sy - sh_ - 3.0); self.cv.tri((ccx - 3.0, ytop - 4.0), (ccx + 4.0, ytop - 4.0), (ccx + 0.5, ytop)); - self.cv.text(ccx + 8.0, sy + sh_ + 3.0, &s); + self.cv.text_n(ccx + 8.0, sy + sh_ + 3.0, &s); } else { - self.cv.textc(bx[3] - 10.0, cy - bh * 0.5 - 14.0, bw[3] + 20.0, &s); + self.cv.textc_n(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. CLICK PRE EQ, POST EQ OR LIM TO SWITCH IT" } else { "CLICK PRE EQ, POST EQ OR LIM TO SWITCH IT" }); let _ = byp; @@ -2225,6 +2421,7 @@ impl<'a> Gui<'a> { if self.rd_tick { self.rd_last = self.now; self.rd_gr = self.gr_disp; + self.rd_gl = self.gl_disp; self.rd_lim = self.lim_disp; self.rd_pk = self.opk_max; self.rd_rms = sh.fms.load(Ordering::Relaxed); @@ -2283,6 +2480,8 @@ impl<'a> Gui<'a> { } // hovering highlights the lockup (a UI-coloured plate behind it, the text in the background colour): it opens About self.cv.header_title(34.0, 16.0, 20.0, "SATCOMP", &ver, 114.0, over); + self.help_area("logo", 10.0, 6.0, 20.0, 20.0); + self.help_area("title", 31.0, 6.0, tw + 6.0, 20.0); self.setc(false); self.preset_bar(); // LIM switch + output peak meter @@ -2291,6 +2490,7 @@ impl<'a> Gui<'a> { self.click_set(68, if on { 0.0 } else { 1.0 }); } self.out_meter(464.0, 8.0, 86.0, 16.0); + self.help_area("out_meter", 464.0, 8.0, 86.0, 16.0); // ---------- tab row let ab = self.app.about > 0; @@ -2304,7 +2504,7 @@ impl<'a> Gui<'a> { let os_i = (self.sget(7) + 0.5).floor() as i32; for i in 0..3 { let l = ["x1", "x2", "x4"][i as usize]; - if self.btn(152.0 + i as f32 * 40.0, 34.0, 40.0, 16.0, l, (os_i == i) as u8) { + if self.btn_sel(152.0 + i as f32 * 40.0, 34.0, 40.0, 16.0, l, (os_i == i) as u8) { self.click_set(7, i as f32); } } @@ -2338,39 +2538,48 @@ impl<'a> Gui<'a> { if !ab { self.set_dk(if byp { 0.5 } else { 1.0 }); self.draw_plot(10.0, 56.0, 130.0, 128.0); + self.help_area(if self.curve_edit { "draw" } else { "plot" }, 10.0, 56.0, 130.0, 128.0); + self.help_area("draw", 126.0, 58.0, 12.0, 12.0); self.set_dk(if byp || (self.eq_page && eq_mod_byp) { 0.5 } else { 1.0 }); if !self.eq_page { self.scope_icon(false); } if self.eq_page { + self.help_area("eq_graph", 152.0, 56.0, 266.0, 114.0); self.draw_eq(152.0, 56.0, 266.0, 128.0); } else if self.scope_on() { + self.help_area("scope", 152.0, 56.0, 266.0, 112.0); self.draw_scope(152.0, 56.0, 266.0, 112.0); self.scope_row(152.0, 167.0); } else if self.sget(63) > 0.5 { // sidechain: shorter plot + a control row for the key (SC gain, HP, LP, solo) + self.help_area("ccurve", 152.0, 56.0, 266.0, 112.0); self.draw_ccurve(152.0, 56.0, 266.0, 112.0); self.sc_row(152.0, 167.0); } else { + self.help_area("ccurve", 152.0, 56.0, 266.0, 128.0); self.draw_ccurve(152.0, 56.0, 266.0, 128.0); } if !self.eq_page { self.scope_icon(true); + self.help_area("scope_icon", 402.0, 59.0, 13.0, 12.0); } } self.set_dk(1.0); self.draw_meter(430.0, 56.0, 28.0, 266.0); + self.help_area("gr_meter", 430.0, 56.0, 28.0, 266.0); self.set_dk(if byp { 0.5 } else { 1.0 }); // ---------- SAT cells if !ab { self.cell(2, 10.0, 196.0, 62.0, 38.0, "DRIVE"); - self.bias_asym(78.0, 196.0, 62.0, 38.0); + self.cell2(3, 69, 78.0, 196.0, 62.0, 38.0, "BIAS", "ASYM"); 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, "SAT GAIN"); self.sat_vu(144.0, 196.0, 5.0, 126.0); + self.help_area("sat_vu", 142.0, 196.0, 9.0, 126.0); // ---------- COMP cells (or the EQ page's cells) if self.eq_page { @@ -2384,8 +2593,10 @@ impl<'a> Gui<'a> { self.cell(9, 220.0, 196.0, 62.0, 38.0, "RATIO"); self.cell(10, 288.0, 196.0, 62.0, 38.0, "ATTACK"); self.cell(11, 356.0, 196.0, 62.0, 38.0, "RELEASE"); - self.cell(13, 152.0, 240.0, 62.0, 38.0, "KNEE"); - self.cell(14, 220.0, 240.0, 62.0, 38.0, "K.SHAPE"); + // the compressor mode switch over RANGE, then KNEE over K.SHAPE (two stacked groups, as SatXComp) + self.up_group(152.0, 240.0); + self.cell1(13, 220.0, 240.0, 62.0, 19.0, "KNEE"); + self.cell1(14, 220.0, 258.0, 62.0, 20.0, "SHPE"); self.cell(15, 288.0, 240.0, 62.0, 38.0, "PEAK>RMS"); self.cell(16, 356.0, 240.0, 62.0, 38.0, "LOW CUT"); self.cell(59, 152.0, 284.0, 62.0, 38.0, "L.AHEAD"); @@ -2408,7 +2619,7 @@ impl<'a> Gui<'a> { 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.cv.textr_n(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); @@ -2424,15 +2635,17 @@ impl<'a> Gui<'a> { self.cv.text(464.0, 70.0, "TRIM"); "-----dB".to_string() }; - self.cv.textr(464.0, 70.0, 86.0, &s1); + self.cv.textr_n(464.0, 70.0, 86.0, &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(464.0, 88.0, "PK"); - self.cv.textr(464.0, 88.0, 86.0, &s1); + self.cv.textr_n(464.0, 88.0, 86.0, &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(464.0, 100.0, "RMS"); - self.cv.textr(464.0, 100.0, 86.0, &s1); + self.cv.textr_n(464.0, 100.0, 86.0, &s1); + self.help_area("readouts", 464.0, 55.0, 86.0, 57.0); + self.help_area("gm_readout", 464.0, 68.0, 86.0, 12.0); // 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) { @@ -2444,12 +2657,15 @@ impl<'a> Gui<'a> { } } self.diff_box(464.0, 146.0, 86.0, 38.0); + self.help_area("in_out", 464.0, 146.0, 86.0, 38.0); self.cell(20, 464.0, 196.0, 86.0, 38.0, "MAKEUP"); self.cell(21, 464.0, 240.0, 86.0, 38.0, "MIX"); self.cell_o(22, 464.0, 284.0, 86.0, 38.0, "OUT GAIN"); self.resize_grip(); + self.help_area("ui_scale", 544.0, 320.0, 16.0, 16.0); self.menu_draw(); + self.help_draw(); self.poll_dialog(); self.run_pending(); if editing { diff --git a/rust/satcomp-plugin/src/gui/ui/ccurve.rs b/rust/satcomp-plugin/src/gui/ui/ccurve.rs index 24e2569..9ea36e5 100644 --- a/rust/satcomp-plugin/src/gui/ui/ccurve.rs +++ b/rust/satcomp-plugin/src/gui/ui/ccurve.rs @@ -57,7 +57,7 @@ impl<'a> Gui<'a> { self.cv.set_font(1); let ct = format!("CEIL {}", db_str(hi)); let ft = format!("FLOOR {}", db_str(lo)); - let (cw, fw) = (self.cv.text_w(&ct) + 8.0, self.cv.text_w(&ft) + 8.0); + let (cw, fw) = (self.cv.text_w_n(&ct) + 8.0, self.cv.text_w_n(&ft) + 8.0); let (by, bh) = (y + h - 15.0, 12.0); let fx = x + w - 3.0 - fw; let cx = fx - 3.0 - cw; @@ -117,17 +117,31 @@ impl<'a> Gui<'a> { } else { gc }; + // static gain change at an input level (dB): the downward reduction above the threshold and / or the upward lift below + // it (the mirror of the reduction about the threshold, capped at RANGE), as the compressor computes them + let (mode, range) = (self.env.dsp.comp_mode, self.env.dsp.up_range); + let (down, up) = (mode != 1, mode >= 1); + let net = |v: f32| -> f32 { + let mut g = 0.0; + if down { + g -= gc.gr(v as f64) as f32; + } + if up { + g += (gc.gr(2.0 * gc.thr - v as f64).min(range)) as f32; + } + g + }; let hxt = vx(thr); let hyt = vy(thr); // the ratio handle sits on the curve a little below the ceiling (never under the scope icon in the corner) let hin = (hi - 6.0).min(0.0); let hxr = vx(hin); - let hyr = vyc(hin - gc.gr(hin as f64) as f32); + let hyr = vyc(hin + net(hin)); let on_lbl = self.hit(cx, by, cw, bh) || self.hit(fx, by, fw, bh); if hv && self.press && self.act == 0 && !on_lbl { // an interaction point: the handles first, then the curve itself (above the threshold = ratio, below = threshold) let xin = mx_db(self.mx); - let curve_y = vyc(xin - gc.gr(xin as f64) as f32); + let curve_y = vyc(xin + net(xin)); let pick = if (self.mx - hxr).abs() <= 6.0 && (self.my - hyr).abs() <= 6.0 { 121 } else if (self.mx - hxt).abs() <= 6.0 && (self.my - hyt).abs() <= 6.0 { @@ -157,12 +171,25 @@ impl<'a> Gui<'a> { let vz = self.mval(1); let lvl = if vz > 0.000001 { (8.6858896 * vz.ln()).clamp(-96.0, hi) } else { -96.0 }; let live = lvl > SILENT; - self.setc(true); + // the fill up to the live level: the curve in the accent, except the upward lift (the band between the unity line + // and the curve above it), which takes the gain colour, as the meter does + let inv = self.gain_colour(); for i in 0..(w - 2.0) as i32 { let xin = lo + span * i as f32 / (w - 3.0); if live && xin <= lvl { - let py = vyc(xin - gc.gr(xin as f64) as f32); - self.cv.fill(x + 1.0 + i as f32, py, 1.0, y + h - 1.0 - py); + let g = net(xin); + let py = vyc(xin + g); + let px = x + 1.0 + i as f32; + if g > 0.0 { + let pu = vyc(xin); + self.setc(true); + self.cv.fill(px, pu, 1.0, y + h - 1.0 - pu); + self.cv.setrgb(inv); + self.cv.fill(px, py, 1.0, pu - py); + } else { + self.setc(true); + self.cv.fill(px, py, 1.0, y + h - 1.0 - py); + } } } self.setc(false); @@ -178,16 +205,16 @@ impl<'a> Gui<'a> { let mut db = (hi / 12.0).floor() * 12.0; while db > lo + 3.0 { let s = db_str(db); - let tw = self.cv.text_w(&s); + let tw = self.cv.text_w_n(&s); let (px, py) = (vx(db), vy(db)); self.cv.fill(x + 1.0, py, 3.0, 1.0); // tick on the left edge if py + 2.0 >= y + 13.0 && py + 11.0 < y + h - 12.0 { - self.cv.text(x + 6.0, py + 2.0, &s); + self.cv.text_n(x + 6.0, py + 2.0, &s); } self.cv.fill(px, y + h - 4.0, 1.0, 3.0); // tick on the bottom edge let tx = (px - tw * 0.5).max(x + 3.0); if tx > x + 22.0 && tx + tw < cx - 3.0 { - self.cv.text(tx, y + h - 13.0, &s); + self.cv.text_n(tx, y + h - 13.0, &s); } db -= 12.0; } @@ -203,7 +230,7 @@ impl<'a> Gui<'a> { for i in 0..=n { let xin = lo + span * i as f32 / n as f32; let px = x + (i as f32 / n as f32) * (w - 1.0); - let py = vyc(xin - gc.gr(xin as f64) as f32); + let py = vyc(xin + net(xin)); if i > 0 { self.cv.line(lx, ly, px, py); } @@ -211,7 +238,7 @@ impl<'a> Gui<'a> { ly = py; } if live { - let (px, py) = (vx(lvl), vyc(lvl - gc.gr(lvl as f64) as f32)); + let (px, py) = (vx(lvl), vyc(lvl + net(lvl))); self.cv.fill(px - 1.0, py - 1.0, 3.0, 3.0); } // threshold: a dashed line from its handle straight down @@ -224,7 +251,7 @@ impl<'a> Gui<'a> { let mn = self.mval(2); let mn_db = if mn > 0.000001 { (8.6858896 * mn.ln()).clamp(-96.0, hi) } else { -96.0 }; if sc_mode && mn_db > SILENT { - let gr_now = if live { gc.gr(lvl as f64) as f32 } else { 0.0 }; + let gr_now = if live { -net(lvl) } else { 0.0 }; let yin = vyc(mn_db); let yout = vyc((mn_db - gr_now).max(lo)); self.cv.tri((x + 1.0, yin - 3.0), (x + 1.0, yin + 4.0), (x + 6.0, yin + 0.5)); @@ -243,13 +270,13 @@ impl<'a> Gui<'a> { self.setc(self.act == act); self.cv.boxr(bx, by, bw, bh); self.cv.set_font(1); - self.cv.text(bx + 4.0, by + 3.0, t); + self.cv.text_n(bx + 4.0, by + 3.0, t); } self.setc(false); self.cv.set_font(1); if self.rd_tick { self.rd_lvl = lvl; - self.rd_ghr = if live { gc.gr(lvl as f64) as f32 } else { 0.0 }; + self.rd_ghr = if live { -net(lvl) } else { 0.0 }; } let shown = self.rd_lvl > -90.0; let s = if sc_mode { @@ -259,11 +286,14 @@ impl<'a> Gui<'a> { } else { format!("SC ----- IN {} GR 00.0dB", mn) } + } else if shown && self.rd_ghr < -0.04 { + // the upward part is lifting: UP instead of GR + format!("LVL {:+05.1} OUT {:+05.1} UP {:04.1}dB", self.rd_lvl, self.rd_lvl - self.rd_ghr, -self.rd_ghr) } else if shown { - format!("LVL {:+05.1} OUT {:+05.1} GR {:04.1}dB", self.rd_lvl, self.rd_lvl - self.rd_ghr, self.rd_ghr) + format!("LVL {:+05.1} OUT {:+05.1} GR {:04.1}dB", self.rd_lvl, self.rd_lvl - self.rd_ghr, self.rd_ghr.max(0.0)) } else { "LVL ----- OUT ----- GR 00.0dB".to_string() }; - self.cv.text(x + 3.0, y + 2.0, &s); + self.cv.text_n(x + 3.0, y + 2.0, &s); } } diff --git a/rust/satcomp-plugin/src/gui/ui/help.rs b/rust/satcomp-plugin/src/gui/ui/help.rs new file mode 100644 index 0000000..7a1f8e0 --- /dev/null +++ b/rust/satcomp-plugin/src/gui/ui/help.rs @@ -0,0 +1,190 @@ +//! Help overlay for SatComp: maps what the pointer is over (`HelpKey`) to its bubble. Shared entries come from +//! `satcomp_ui::help::common`; the copy is drafted in docs/internal/helpcopy/satcomp.md and common.md. + +use super::Gui; +use satcomp_ui::help::{common as c, h, Help, HelpKey}; +use satcomp_ui::kit::Widgets; + +const SIDECHAIN: Help = h( + "SIDECHAIN", + "Keys the compressor from the plugin's sidechain input instead of the signal itself. Lights red when no sidechain is routed to the plugin.\nOpens the sidechain controls under the compressor graph, and [KEY MIX] takes the place of [FF>FB].", +); +const EQ: Help = h( + "EQ", + "Opens the EQ page: a 3-band EQ with tilt before the compressor ([PRE-COMP]) and another after it ([POST-COMP]).\n[Click] Shows / hides the EQ page\n[Click square] Bypasses the whole EQ module (lit = a band is active, X = bypassed)", +); +const COMP_PLOT: Help = h( + "COMPRESSOR", + "Shows the compressor curve with the live level moving along it. In [UPWARD] and [UP/DWN] the area being lifted is filled in the gain color, and the readout shows [UP] instead of [GR].", +); +const SC: Help = h("SC", "Sets the level of the sidechain key going into the detector. Raise it to make a quiet key trigger more compression."); +const SC_HP_LP: Help = h("HP / LP", "Filters the sidechain key so the compressor reacts only to part of its spectrum, e.g. just the kick drum's low end."); +const SC_SOLO: Help = h("SOLO", "Allows listening to the filtered sidechain key on its own, to tune [SC], [HP] and [LP]."); +const GR_METER: Help = h( + "GR METER", + "Shows how much the compressor is changing the level. In [DWNWARD] the reduction grows from the top, in [UPWARD] the lift rises from the bottom in the gain color, and in [UP/DWN] both grow from the center.\n[Click] Cycles the meter range", +); +const SAT_LEVEL: Help = h("SAT LEVEL", "Shows the level after the saturator. Turns to the accent color when it clips."); +const THRESH: Help = h("THRESH", "Sets the level where compression starts. Lower values compress more of the signal."); +const RATIO: Help = h("RATIO", "Sets how strongly the level is reduced above the threshold. 2:1 is gentle, 10:1 and up is close to limiting, [INF] is a limiter."); +const ATTACK: Help = h("ATTACK", "Sets how quickly the compressor reacts. Short attack tames transients, longer attack lets them punch through."); +const RELEASE: Help = h( + "RELEASE", + "Sets how quickly the compressor lets go. Short release sounds lively and can pump, long release sounds smoother.\nAt its maximum, [AUTO] adapts the release to the material.", +); +const COMP_MODE: Help = h( + "COMP MODE", + "[DWNWARD] turns loud parts down, as a classic compressor does. [UPWARD] lifts quiet parts below the threshold, up to [RNGE]. [UP/DWN] does both.\n[Click] Cycles the modes", +); +const RNGE: Help = h("RNGE", "Sets the most the upward mode may lift quiet material."); +const KNEE: Help = h("KNEE", "Sets how gradually compression sets in around the threshold. 0 dB is a hard knee; wider knees sound softer and more transparent."); +const SHPE: Help = h("SHPE", "Shapes the curve inside the knee. Low values ease in gradually; higher values hold off longer and then bend more firmly."); +const PEAK_RMS: Help = h("PEAK>RMS", "Blends the detector from peak (reacts to every transient) to RMS (follows the average level, smoother and more musical)."); +const LOW_CUT: Help = h("LOW CUT", "Filters low end out of the detector only, so bass does not make the compressor pump. The audio itself is not filtered."); +const LAHEAD: Help = h("L.AHEAD", "Lets the compressor see the incoming signal early, so it can catch fast transients cleanly. Adds latency."); +const SPEED: Help = h("SPEED", "Scales attack and release together. Lower values make the compressor react faster, higher values slower; 50 % uses the times as set."); +const FF_FB: Help = h("FF>FB", "Blends the detection from feed-forward (precise, modern) to feedback (smoother, vintage-style). Replaced by [KEY MIX] while [SIDECHAIN] is on."); +const KEY_MIX: Help = h("KEY MIX", "Blends what the detector hears, from the signal itself (0 %) to the sidechain key (100 %)."); +const GR_DIST: Help = h("GR DIST", "Adds saturation that follows the gain reduction: the harder the compressor works, the more grit it adds."); +const EQ_TABS: Help = h( + "PRE-COMP / POST-COMP", + "Selects which EQ the page edits: before the compressor (shapes what it reacts to and what it saturates) or after it (final tone).\n[Click square] Bypasses that EQ", +); +const EQ_GRAPH: Help = h( + "EQ GRAPH", + "Shows the response of the selected EQ, with the tilt amount in the corner.\n[Drag node] Sets frequency and gain\n[Drag brackets] Sets the Q of the node clicked last (closed = narrow, open = broad)\n[Wheel] Sets the Q of the nearest node\n[Drag pivot line] Sets the pivot\n[Drag elsewhere] Sets the tilt\n[Double-click] Resets a node, the pivot or the tilt", +); +const EQ_TYPE: Help = h("BAND TYPE", "Selects the filter type of the band. Shelves and bells use [GAIN]; the cut filters ignore it."); +const EQ_FREQ: Help = h("FREQ", "Sets the band frequency."); +const EQ_GAIN: Help = h("GAIN", "Boosts or cuts the band. Shows --- on cut filters, which have no gain."); +const EQ_Q: Help = h("Q", "Sets the band width. Low Q is broad and gentle, high Q is narrow and focused."); +const EQ_TILT: Help = h("TILT", "Tilts the whole spectrum around the pivot: positive values brighten (lows down, highs up), negative values darken."); +const EQ_PIVOT: Help = h("PIVOT", "Sets the frequency the tilt pivots around."); +const EQ_OUT: Help = h("OUT GAIN", "Sets the level after this EQ, to make up for boosts or cuts."); +const MAKEUP: Help = h("MAKEUP", "Brings the level back up after compression."); +const MIX: Help = h("MIX", "Blends the processed signal with the dry one, for parallel compression. Lower values keep more of the original dynamics."); +const OUT_GAIN: Help = h("OUT GAIN", "Sets the final output level."); + +/// The bubble for a help target, if it has one. +pub(crate) fn copy(key: &HelpKey) -> Option { + Some(match key { + HelpKey::Slot(n) => match *n { + 1 => c::SHAPE, + 2 => c::DRIVE, + 3 => c::BIAS, + 69 => c::ASYM, + 4 | 5 => c::SAT_HP_LP, + 6 => c::TONE, + 25 => c::SAT_MIX, + 27 => c::SAT_GAIN, + 8 => THRESH, + 9 => RATIO, + 10 => ATTACK, + 11 => RELEASE, + 70 => COMP_MODE, + 71 => RNGE, + 13 => KNEE, + 14 => SHPE, + 15 => PEAK_RMS, + 16 => LOW_CUT, + 59 => LAHEAD, + 12 => SPEED, + 18 => FF_FB, + 67 => KEY_MIX, + 19 => GR_DIST, + 64 => SC, + 65 | 66 => SC_HP_LP, + 20 => MAKEUP, + 21 => MIX, + 22 => OUT_GAIN, + // EQ page, per set: 29 + set * 15; band b at + b * 4 (type, freq, gain, q), then tilt, pivot, out gain + 29..=58 => match (n - 29) % 15 { + 12 => EQ_TILT, + 13 => EQ_PIVOT, + 14 => EQ_OUT, + k => [EQ_TYPE, EQ_FREQ, EQ_GAIN, EQ_Q][k % 4], + }, + _ => return None, + }, + HelpKey::Id(id) => match id.as_str() { + "?" => c::HELP, + "logo" => c::COLOR_SWITCHER, + "title" => c::TITLE, + "ui_scale" => c::UI_SCALE, + "save" => c::SAVE, + "preset" => c::PRESET, + "prev_next" => c::PREV_NEXT, + "LIM" => c::LIM, + "out_meter" => c::OUT_METER, + "x1" | "x2" | "x4" => c::OVERSAMPLING, + "SIDECHAIN" => SIDECHAIN, + "EQ" => EQ, + "DELTA" => c::DELTA, + "BYPASS" => c::BYPASS, + "plot" => c::TRANSFER, + "draw" => c::DRAW, + "ccurve" => COMP_PLOT, + "scope_icon" => c::SCOPE_ICON, + "scope" => c::SCOPE_VIEW, + "SRC" => c::SRC, + "WAVE" => c::WAVE, + "WIN" => c::WIN, + "CEIL" => c::CEIL, + "SOLO" => SC_SOLO, + "gr_meter" => GR_METER, + "sat_vu" => SAT_LEVEL, + "DWNWARD" | "UPWARD" | "UP/DWN" => COMP_MODE, + "PRE-COMP" | "POST-COMP" => EQ_TABS, + "eq_graph" => EQ_GRAPH, + "readouts" => c::READOUTS, + "GAIN MATCH" | "gm_readout" => c::GAIN_MATCH, + "in_out" => c::IN_OUT, + _ => return None, + }, + }) +} + +impl Gui<'_> { + /// End of frame: the bubble for whatever the pointer is over (none during a menu, a resize or the theme editor). + pub(super) fn help_draw(&mut self) { + let busy = self.menu.is_some() || self.resizing || self.app.editing(); + self.help_overlay(busy, 560.0, 336.0, copy); + } + + /// Report a non-parameter area as a help target (`id` as `copy` knows it). + pub(super) fn help_area(&mut self, id: &str, x: f32, y: f32, w: f32, hh: f32) { + self.help_id(id, x, y, w, hh); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_param_on_screen_and_every_named_widget_has_copy() { + let slots = [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 25, 27, 59, 64, 65, 66, 67, 69, 70, 71]; + for n in slots.into_iter().chain(29..=58) { + assert!(copy(&HelpKey::Slot(n)).is_some(), "slot {n}"); + } + for id in [ + "?", "logo", "title", "ui_scale", "save", "preset", "prev_next", "LIM", "out_meter", "x1", "x2", "x4", "SIDECHAIN", "EQ", "DELTA", + "BYPASS", "plot", "draw", "ccurve", "scope_icon", "scope", "SRC", "WAVE", "WIN", "CEIL", "SOLO", "gr_meter", "sat_vu", "DWNWARD", + "UPWARD", "UP/DWN", "PRE-COMP", "POST-COMP", "eq_graph", "readouts", "GAIN MATCH", "gm_readout", "in_out", + ] { + assert!(copy(&HelpKey::Id(id.into())).is_some(), "{id}"); + } + assert!(copy(&HelpKey::Slot(7)).is_none(), "oversampling is keyed by its buttons"); + } + + #[test] + fn eq_slots_map_to_their_cell() { + // set 1 (post), band 2: type 29 + 15 + 8 = 52, q = 55; tilt 56, pivot 57, out 58 + assert_eq!(copy(&HelpKey::Slot(52)).unwrap().title, "BAND TYPE"); + assert_eq!(copy(&HelpKey::Slot(55)).unwrap().title, "Q"); + assert_eq!(copy(&HelpKey::Slot(56)).unwrap().title, "TILT"); + assert_eq!(copy(&HelpKey::Slot(57)).unwrap().title, "PIVOT"); + assert_eq!(copy(&HelpKey::Slot(58)).unwrap().title, "OUT GAIN"); + assert_eq!(copy(&HelpKey::Slot(30)).unwrap().title, "FREQ"); + } +} diff --git a/rust/satcomp-plugin/src/gui/ui/scope.rs b/rust/satcomp-plugin/src/gui/ui/scope.rs index b355cd9..662768b 100644 --- a/rust/satcomp-plugin/src/gui/ui/scope.rs +++ b/rust/satcomp-plugin/src/gui/ui/scope.rs @@ -1,5 +1,6 @@ //! Waveform scope ("transient meter"): an alternate view of the compressor plot. 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. +//! output in the UI colour, with the gain reduction the compressor removed stacked on top in the accent colour. What the +//! upward compressor lifted is the top of the output, drawn in the gain colour (the inverse of the accent). use super::*; @@ -16,24 +17,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) { +/// (output peak, peak without the upward lift, 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, 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); + 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) = ring.get(i as usize); - let (a, b) = (fin(a), fin(b)); - o = o.max(a); - p = p.max(b); + let (a, c, b) = ring.get3(i as usize); + o = o.max(fin(a)); + m = m.max(fin(c)); + p = p.max(fin(b)); } - (o, p.max(o)) + (o, m.min(o), p.max(o)) } /// a ring value made safe to draw: non-finite or negative peaks (only possible with broken audio upstream) read as 0 @@ -127,7 +129,7 @@ impl<'a> Gui<'a> { self.scope_t = self.now; let pos = self.scope_clk.update(head, dt, 1.0 / satcomp_dsp::ScopeRing::BUCKET_S); let last = (pos / k).floor() as i64 - 1; // newest complete column - let mut cols = vec![(0.0f32, 0.0f32); ncol]; + 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); } @@ -137,7 +139,7 @@ impl<'a> Gui<'a> { // output (UI colour) if src < 2 { self.setc(false); - for (c, &(o, _)) in cols.iter().enumerate() { + for (c, &(o, _, _)) in cols.iter().enumerate() { let ho = hpx(o); if ho > 0.0 { let cx = x + 1.0 + c as f32; @@ -149,10 +151,25 @@ impl<'a> Gui<'a> { } } } + // lift (gain colour): what the upward compressor added, the top of the output (OUT+GR), or alone from the baseline (GR) + if src != 1 { + let inv = self.gain_colour(); + self.cv.setrgb(inv); + for (c, &(o, m, _)) in cols.iter().enumerate() { + let cx = x + 1.0 + c as f32; + let (lo, hi) = if src == 0 { (hpx(m), hpx(o)) } else { (0.0, hpx(o - m)) }; + if hi > lo { + self.cv.fill(cx, base - hi, 1.0, hi - lo); + if full { + self.cv.fill(cx, base + lo + 1.0, 1.0, hi - lo); + } + } + } + } // 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() { + 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 { @@ -185,13 +202,13 @@ impl<'a> Gui<'a> { } if dragging { let t = format!("WIN {} CEIL {}", WIN_L[win], fmt_db(ceil_db(ceil))); - let tw = self.cv.text_w(&t); + let tw = self.cv.text_w_n(&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); + self.cv.text_n(x + 8.0, y + 8.0, &t); } } @@ -204,6 +221,7 @@ impl<'a> Gui<'a> { 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); + self.help_id(lbl, cx, y, w, h); if self.hit(cx, y, w, h) { if self.press && self.act == 0 { self.sc_set(shift, bits, (cur + 1) % n); @@ -232,6 +250,7 @@ impl<'a> Gui<'a> { 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); + self.help_id(lbl, cx, y, w, h); if self.hit(cx, y, w, h) { if self.press && self.act == 0 { self.act = act; @@ -253,7 +272,7 @@ impl<'a> Gui<'a> { 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); + self.cv.textr_n(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); @@ -283,7 +302,7 @@ mod tests { 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 (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/lib.rs b/rust/satcomp-plugin/src/lib.rs index c50d340..9206894 100644 --- a/rust/satcomp-plugin/src/lib.rs +++ b/rust/satcomp-plugin/src/lib.rs @@ -22,6 +22,8 @@ pub struct Shared { pub opk: [AtomicF32; 2], pub clip: AtomicBool, pub gr_pk: AtomicF32, + /// upward compressor lift (dB, positive), accumulated like `gr_pk` + pub gl_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` @@ -61,6 +63,7 @@ impl Shared { opk: [AtomicF32::new(0.0), AtomicF32::new(0.0)], clip: AtomicBool::new(false), gr_pk: AtomicF32::new(0.0), + gl_pk: AtomicF32::new(0.0), lim_gr_pk: AtomicF32::new(0.0), sat_pk: AtomicF32::new(0.0), fms: AtomicF32::new(1e-9), @@ -96,7 +99,6 @@ 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 { @@ -106,7 +108,7 @@ impl Default for SatComp { engine.tap = shared.tap.clone(); engine.scope = shared.scope.clone(); engine.meter = shared.meter.clone(); - 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] } + Self { params: Arc::new(SatCompParams::default()), shared, engine, last_latency: u32::MAX, last_curve: satcomp_dsp::shapers::Curve::linear() } } } @@ -171,7 +173,7 @@ impl Plugin for SatComp { engine.scope = self.shared.scope.clone(); engine.meter = self.shared.meter.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, &mut self.last_asym)); + engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve)); self.engine = engine; } @@ -182,7 +184,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, &mut self.last_asym)); + self.engine.set_params(&self.params.to_dsp_rt(&mut self.last_curve)); let lat = self.engine.latency(); if lat != self.last_latency { self.last_latency = lat; @@ -220,6 +222,8 @@ impl Plugin for SatComp { } sh.gr_pk.fetch_max(e.gr_pk as f32, Ordering::Relaxed); e.gr_pk = 0.0; + sh.gl_pk.fetch_max(e.gl_pk as f32, Ordering::Relaxed); + e.gl_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); @@ -279,3 +283,79 @@ mod shadow_tests { assert_eq!(p.to_dsp().drive, plain.drive, "the real parameters are untouched"); } } + +/// The shared parameter layer (satcomp_dsp::spec, also used by the CLI) against the plug-in's own parameters. +#[cfg(test)] +mod shared_layer_tests { + use crate::params::{SatCompParams, TABLE}; + use nih_plug::prelude::{Param, ParamPtr}; + + fn held(p: &SatCompParams, n: usize, norm: f32) -> Option { + Some(match p.ptr(n)? { + ParamPtr::FloatParam(f) => unsafe { (*f).preview_plain(norm) }, + ParamPtr::IntParam(i) => unsafe { (*i).preview_plain(norm) as f32 }, + ParamPtr::BoolParam(b) => unsafe { (*b).preview_plain(norm) as i32 as f32 }, + _ => return None, + }) + } + + /// The editor writes `(v - min) / (max - min)` and reads it back the same way (satcomp-ui kit), so every range must be + /// linear: the plug-in holds the value the editor shows. + #[test] + fn every_parameter_holds_the_value_the_editor_writes() { + let p = SatCompParams::from_defaults(None); + for &(n, id, mn, mx, _) in TABLE { + for t in [0.0f32, 0.25, 0.5, 0.75, 1.0] { + let v = mn + (mx - mn) * t; + let got = held(&p, n, (v - mn) / (mx - mn)).unwrap(); + let step = satcomp_dsp::spec::SPECS.iter().find(|s| s.slot == n).unwrap().step; + assert!((got - v).abs() <= step.max(1e-4) * 0.51 + 1e-4, "{id}: the editor writes {v}, the plug-in holds {got}"); + } + } + } + + /// `Values::set` (the CLI's and presets' path) stores exactly what the plug-in holds after the editor or a preset writes the + /// same value: on and off the step grid, inside and past the range. The CLI's parity rests on it. + #[test] + fn the_shared_values_store_what_the_plug_in_holds() { + let p = SatCompParams::from_defaults(None); + let mut v = satcomp_dsp::spec::Values::default(); + for &(n, id, mn, mx, _) in TABLE { + for t in [-0.1f32, 0.0, 0.013, 0.25, 0.4999, 0.5, 0.731, 1.0, 1.2] { + let want = mn + (mx - mn) * t; + let h = held(&p, n, ((want - mn) / (mx - mn)).clamp(0.0, 1.0)).unwrap(); + assert!(v.set(n, want), "{id}"); + assert_eq!(v.get(n).unwrap().to_bits(), h.to_bits(), "{id} = {want}: shared {} vs plug-in {h}", v.get(n).unwrap()); + } + } + } + + /// The plug-in's defaults read through the shared layer are the shared layer's own defaults, and the tables agree. + #[test] + fn the_plug_in_defaults_are_the_shared_defaults() { + assert_eq!(SatCompParams::from_defaults(None).values(), satcomp_dsp::spec::Values::default()); + assert_eq!(TABLE.len(), satcomp_dsp::spec::SPECS.len()); + for (e, s) in TABLE.iter().zip(satcomp_dsp::spec::SPECS) { + assert_eq!((e.0, e.1, e.2, e.3, e.4), (s.slot, s.id, s.min, s.max, s.default)); + } + } +} + +/// Windows gives a host's thread 1 MB of stack (REAPER scans plug-ins on it); macOS gives 8 MB, so an oversized stack +/// temporary only shows up there. SatEQ 0.1.0 failed to load on Windows that way (its engine built ~225 KB of bands on the +/// stack, several times over). Built on a 1 MB thread here: an overflow aborts the test run. +#[cfg(test)] +mod stack_budget_tests { + #[test] + fn the_plugin_builds_within_a_windows_thread_stack() { + std::thread::Builder::new() + .stack_size(1024 * 1024) + .spawn(|| { + let p = ::default(); + std::hint::black_box(&p); + }) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/rust/satcomp-plugin/src/params.rs b/rust/satcomp-plugin/src/params.rs index 50a6593..d1f693d 100644 --- a/rust/satcomp-plugin/src/params.rs +++ b/rust/satcomp-plugin/src/params.rs @@ -2,79 +2,12 @@ use nih_plug::prelude::*; use nih_plug_egui::EguiState; -use satcomp_dsp::shapers::{asym_from, Curve, SHAPER_COUNT}; -use satcomp_dsp::{EqBandParams, EqStageParams}; +use satcomp_dsp::shapers::Curve; use std::sync::atomic::{AtomicBool, AtomicI32}; 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, 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, 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), - (12, "speed", 0.0, 100.0, 50.0), - (13, "knee", 0.0, 24.0, 6.0), - (14, "knee_shape", 0.0, 100.0, 0.0), - (15, "detector", 0.0, 100.0, 30.0), - (16, "det_hp", 0.0, 400.0, 0.0), - (18, "ff_fb", 0.0, 100.0, 0.0), - (19, "gr_dist", 0.0, 100.0, 0.0), - (20, "makeup", 0.0, 24.0, 0.0), - (21, "mix", 0.0, 100.0, 100.0), - (22, "out_gain", -24.0, 12.0, 0.0), - (23, "gain_match", 0.0, 1.0, 0.0), - (25, "sat_mix", 0.0, 100.0, 100.0), - (26, "bypass", 0.0, 1.0, 0.0), - (27, "sat_out", -24.0, 12.0, 0.0), - (29, "pre_b1_type", 0.0, 2.0, 0.0), - (30, "pre_b1_freq", 20.0, 20000.0, 80.0), - (31, "pre_b1_gain", -18.0, 18.0, 0.0), - (32, "pre_b1_q", 0.1, 10.0, 0.5), - (33, "pre_b2_type", 0.0, 2.0, 0.0), - (34, "pre_b2_freq", 20.0, 20000.0, 200.0), - (35, "pre_b2_gain", -18.0, 18.0, 0.0), - (36, "pre_b2_q", 0.1, 10.0, 0.5), - (37, "pre_b3_type", 0.0, 2.0, 0.0), - (38, "pre_b3_freq", 20.0, 20000.0, 6000.0), - (39, "pre_b3_gain", -18.0, 18.0, 0.0), - (40, "pre_b3_q", 0.1, 10.0, 0.5), - (41, "pre_tilt", -12.0, 12.0, 0.0), - (42, "pre_pivot", 20.0, 20000.0, 600.0), - (43, "pre_out_gain", -12.0, 12.0, 0.0), - (44, "post_b1_type", 0.0, 2.0, 0.0), - (45, "post_b1_freq", 20.0, 20000.0, 80.0), - (46, "post_b1_gain", -18.0, 18.0, 0.0), - (47, "post_b1_q", 0.1, 10.0, 0.5), - (48, "post_b2_type", 0.0, 2.0, 0.0), - (49, "post_b2_freq", 20.0, 20000.0, 200.0), - (50, "post_b2_gain", -18.0, 18.0, 0.0), - (51, "post_b2_q", 0.1, 10.0, 0.5), - (52, "post_b3_type", 0.0, 2.0, 0.0), - (53, "post_b3_freq", 20.0, 20000.0, 6000.0), - (54, "post_b3_gain", -18.0, 18.0, 0.0), - (55, "post_b3_q", 0.1, 10.0, 0.5), - (56, "post_tilt", -12.0, 12.0, 0.0), - (57, "post_pivot", 20.0, 20000.0, 600.0), - (58, "post_out_gain", -12.0, 12.0, 0.0), - (59, "lookahead", 0.0, 10.0, 0.0), - (60, "eq_pre_bypass", 0.0, 1.0, 0.0), - (61, "eq_post_bypass", 0.0, 1.0, 0.0), - (62, "eq_module_bypass", 0.0, 1.0, 0.0), - (63, "sc_on", 0.0, 1.0, 0.0), - (64, "sc_gain", -24.0, 24.0, 0.0), - (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), -]; +/// The table lives in the shared parameter layer (satcomp-dsp/src/spec.rs); slider numbers follow SatComp.jsfx. +pub use satcomp_dsp::spec::TABLE; #[derive(Params)] pub struct SatCompParams { @@ -107,9 +40,6 @@ 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, @@ -119,6 +49,8 @@ pub struct SatCompParams { pub drive: FloatParam, #[id = "bias"] pub bias: FloatParam, + #[id = "asym"] + pub asym: FloatParam, #[id = "sat_hp"] pub sat_hp: FloatParam, #[id = "sat_lp"] @@ -241,6 +173,10 @@ pub struct SatCompParams { pub sc_lp: FloatParam, #[id = "sc_mix"] pub sc_mix: FloatParam, + #[id = "comp_mode"] + pub comp_mode: IntParam, + #[id = "up_range"] + pub up_range: FloatParam, #[id = "lim_on"] pub lim_on: BoolParam, } @@ -256,7 +192,7 @@ impl SatCompParams { pub fn from_defaults(d: Option) -> Self { Self { editor_state: { - let (w, h) = d.as_ref().map(|d| d.size((560.0, 336.0))).unwrap_or((700, 420)); + let (w, h) = satcomp_ui::appearance::start_size((560.0, 336.0), 1.25); EguiState::from_size(w, h) }, palette: Arc::new(AtomicI32::new(0)), @@ -268,11 +204,11 @@ impl SatCompParams { 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 }), + shape: IntParam::new("Shape", 0, IntRange::Linear { min: 0, max: 16 }), 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), + asym: FloatParam::new("Asym", 100.0, FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), 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), @@ -334,6 +270,8 @@ impl 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), + comp_mode: IntParam::new("Comp Mode", 0, IntRange::Linear { min: 0, max: 2 }), + up_range: FloatParam::new("Range", 12.0, FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), lim_on: BoolParam::new("Limiter", true), } } @@ -345,14 +283,9 @@ 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.asym_snapshot()) + self.to_dsp_with(self.curve_snapshot()) } // --- shadow (generated by tools/gen_shadow.py, do not edit) --- @@ -361,7 +294,7 @@ impl SatCompParams { let d: Option = None; Self { editor_state: { - let (w, h) = d.as_ref().map(|d| d.size((560.0, 336.0))).unwrap_or((700, 420)); + let (w, h) = satcomp_ui::appearance::start_size((560.0, 336.0), 1.25); EguiState::from_size(w, h) }, palette: Arc::new(AtomicI32::new(0)), @@ -373,11 +306,11 @@ impl SatCompParams { 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", over(1).map(|v| (v + 0.5).floor() as i32).unwrap_or(self.shape.value()), IntRange::Linear { min: 0, max: 14 }), + shape: IntParam::new("Shape", over(1).map(|v| (v + 0.5).floor() as i32).unwrap_or(self.shape.value()), IntRange::Linear { min: 0, max: 16 }), drive: FloatParam::new("Drive", over(2).unwrap_or(self.drive.value()), FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), bias: FloatParam::new("Bias", over(3).unwrap_or(self.bias.value()), FloatRange::Linear { min: -100.0, max: 100.0 }).with_unit(" %").with_step_size(0.1), + asym: FloatParam::new("Asym", over(69).unwrap_or(self.asym.value()), FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), sat_hp: FloatParam::new("Sat HP", over(4).unwrap_or(self.sat_hp.value()), FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), sat_lp: FloatParam::new("Sat LP", over(5).unwrap_or(self.sat_lp.value()), FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), tone: FloatParam::new("Tone", over(6).unwrap_or(self.tone.value()), FloatRange::Linear { min: 1000.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), @@ -439,6 +372,8 @@ impl SatCompParams { sc_hp: FloatParam::new("SC HP", over(65).unwrap_or(self.sc_hp.value()), FloatRange::Linear { min: 20.0, max: 2000.0 }).with_unit(" Hz").with_step_size(1.0), sc_lp: FloatParam::new("SC LP", over(66).unwrap_or(self.sc_lp.value()), FloatRange::Linear { min: 200.0, max: 20000.0 }).with_unit(" Hz").with_step_size(1.0), sc_mix: FloatParam::new("Key Mix", over(67).unwrap_or(self.sc_mix.value()), FloatRange::Linear { min: 0.0, max: 100.0 }).with_unit(" %").with_step_size(1.0), + comp_mode: IntParam::new("Comp Mode", over(70).map(|v| (v + 0.5).floor() as i32).unwrap_or(self.comp_mode.value()), IntRange::Linear { min: 0, max: 2 }), + up_range: FloatParam::new("Range", over(71).unwrap_or(self.up_range.value()), FloatRange::Linear { min: 0.0, max: 24.0 }).with_unit(" dB").with_step_size(0.1), lim_on: BoolParam::new("Limiter", over(68).map(|v| v > 0.5).unwrap_or(self.lim_on.value())), } } @@ -447,49 +382,103 @@ impl SatCompParams { /// follow the mouse and not the host's later answer. Costs a rebuilt parameter set, so use it only while a write is pending. pub fn to_dsp_over(&self, over: &dyn Fn(usize) -> Option) -> satcomp_dsp::Params { let shadow = self.from_values(over); - shadow.to_dsp_with(self.curve_snapshot(), self.asym_snapshot()) + shadow.to_dsp_with(self.curve_snapshot()) } // --- end shadow --- /// 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, last_asym: &mut [f64; SHAPER_COUNT]) -> satcomp_dsp::Params { + pub fn to_dsp_rt(&self, last: &mut satcomp_dsp::shapers::Curve) -> satcomp_dsp::Params { if let Some(g) = self.custom_curve.try_lock() { *last = satcomp_dsp::shapers::Curve::from_points(&g); } - if let Some(g) = self.asym.try_lock() { - *last_asym = asym_from(&g); - } - self.to_dsp_with(*last, *last_asym) + self.to_dsp_with(*last) } - 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, 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, - knee_shape: self.knee_shape.value() as f64, detector: self.detector.value() as f64, det_hp: self.det_hp.value() as f64, - ff_fb: self.ff_fb.value() as f64, gr_dist: self.gr_dist.value() as f64, makeup: self.makeup.value() as f64, - mix: self.mix.value() as f64, out_gain: self.out_gain.value() as f64, gain_match: self.gain_match.value(), - sat_mix: self.sat_mix.value() as f64, bypass: self.bypass.value(), sat_out: self.sat_out.value() as f64, - eq: [stage([(&self.pre_b1_type, &self.pre_b1_freq, &self.pre_b1_gain, &self.pre_b1_q), (&self.pre_b2_type, &self.pre_b2_freq, &self.pre_b2_gain, &self.pre_b2_q), (&self.pre_b3_type, &self.pre_b3_freq, &self.pre_b3_gain, &self.pre_b3_q)], &self.pre_tilt, &self.pre_pivot, &self.pre_out_gain), stage([(&self.post_b1_type, &self.post_b1_freq, &self.post_b1_gain, &self.post_b1_q), (&self.post_b2_type, &self.post_b2_freq, &self.post_b2_gain, &self.post_b2_q), (&self.post_b3_type, &self.post_b3_freq, &self.post_b3_gain, &self.post_b3_q)], &self.post_tilt, &self.post_pivot, &self.post_out_gain)], - 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, + /// The parameters' current values in the shared parameter layer's plain form. + pub fn values(&self) -> satcomp_dsp::spec::Values { + satcomp_dsp::spec::Values { + shape: self.shape.value(), + drive: self.drive.value(), + bias: self.bias.value(), + asym: self.asym.value(), + sat_hp: self.sat_hp.value(), + sat_lp: self.sat_lp.value(), + tone: self.tone.value(), + os: self.os.value(), + thresh: self.thresh.value(), + ratio: self.ratio.value(), + attack: self.attack.value(), + release: self.release.value(), + speed: self.speed.value(), + knee: self.knee.value(), + knee_shape: self.knee_shape.value(), + detector: self.detector.value(), + det_hp: self.det_hp.value(), + ff_fb: self.ff_fb.value(), + gr_dist: self.gr_dist.value(), + makeup: self.makeup.value(), + mix: self.mix.value(), + out_gain: self.out_gain.value(), + gain_match: self.gain_match.value(), + sat_mix: self.sat_mix.value(), + bypass: self.bypass.value(), + sat_out: self.sat_out.value(), + pre_b1_type: self.pre_b1_type.value(), + pre_b1_freq: self.pre_b1_freq.value(), + pre_b1_gain: self.pre_b1_gain.value(), + pre_b1_q: self.pre_b1_q.value(), + pre_b2_type: self.pre_b2_type.value(), + pre_b2_freq: self.pre_b2_freq.value(), + pre_b2_gain: self.pre_b2_gain.value(), + pre_b2_q: self.pre_b2_q.value(), + pre_b3_type: self.pre_b3_type.value(), + pre_b3_freq: self.pre_b3_freq.value(), + pre_b3_gain: self.pre_b3_gain.value(), + pre_b3_q: self.pre_b3_q.value(), + pre_tilt: self.pre_tilt.value(), + pre_pivot: self.pre_pivot.value(), + pre_out_gain: self.pre_out_gain.value(), + post_b1_type: self.post_b1_type.value(), + post_b1_freq: self.post_b1_freq.value(), + post_b1_gain: self.post_b1_gain.value(), + post_b1_q: self.post_b1_q.value(), + post_b2_type: self.post_b2_type.value(), + post_b2_freq: self.post_b2_freq.value(), + post_b2_gain: self.post_b2_gain.value(), + post_b2_q: self.post_b2_q.value(), + post_b3_type: self.post_b3_type.value(), + post_b3_freq: self.post_b3_freq.value(), + post_b3_gain: self.post_b3_gain.value(), + post_b3_q: self.post_b3_q.value(), + post_tilt: self.post_tilt.value(), + post_pivot: self.post_pivot.value(), + post_out_gain: self.post_out_gain.value(), + lookahead: self.lookahead.value(), + 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(), + sc_hp: self.sc_hp.value(), + sc_lp: self.sc_lp.value(), + sc_mix: self.sc_mix.value(), + comp_mode: self.comp_mode.value(), + up_range: self.up_range.value(), lim_on: self.lim_on.value(), } } + fn to_dsp_with(&self, curve: satcomp_dsp::shapers::Curve) -> satcomp_dsp::Params { + satcomp_dsp::spec::to_dsp(&self.values(), curve) + } + /// Parameter by JSFX slider 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(), + 69 => self.asym.as_ptr(), 4 => self.sat_hp.as_ptr(), 5 => self.sat_lp.as_ptr(), 6 => self.tone.as_ptr(), @@ -551,6 +540,8 @@ impl SatCompParams { 65 => self.sc_hp.as_ptr(), 66 => self.sc_lp.as_ptr(), 67 => self.sc_mix.as_ptr(), + 70 => self.comp_mode.as_ptr(), + 71 => self.up_range.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 e24c009..b8095f3 100644 --- a/rust/satcomp-plugin/src/presets.rs +++ b/rust/satcomp-plugin/src/presets.rs @@ -1,115 +1,17 @@ -//! Presets: JSON files of parameter values keyed by parameter id. -//! Factory bank = every `presets/*.json` embedded at build time (+ built-in INIT). -//! User presets = `*.satcomp` files; the dropdown lists the user folder, "Load preset..." opens any file. +//! Presets: the format, factory bank and user folder live in the shared layer (`satcomp_dsp::preset`, also read by the CLI); +//! this adds the file dialogs and keeps the editor's tests hermetic. -use crate::params::TABLE; -use include_dir::{include_dir, Dir}; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; -static FACTORY_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/presets"); - -pub const EXT: &str = "satcomp"; -/// Never stored in a preset: Bypass is a performance switch, Gain Match is a level-dependent measurement. -pub const EXCLUDED: [&str; 3] = ["bypass", "gain_match", "sc_on"]; - -#[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: "satcomp-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 == "satcomp-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/SatComp/Presets (macOS), %APPDATA%\SatComp\Presets (Windows), ~/.config/SatComp/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("SatComp").join("Presets")) -} +pub use satcomp_dsp::preset::{EXCLUDED, EXT, Preset, factory, load_file, save_file, user_dir}; /// (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)); - } - } - } - } + return Vec::new(); } - 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()) + satcomp_dsp::preset::scan_user() } #[cfg(any(target_os = "macos", windows))] @@ -142,60 +44,3 @@ pub fn open_dialog() -> Option { pub fn save_dialog(_default_name: &str) -> Option { None } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - 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"], 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(); - assert!(!p.to_json().contains("curve")); // not written when unused - 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.curve, p.curve); - let old = r#"{"format":"satcomp-preset","version":1,"name":"x","params":{}}"#; - assert!(Preset::from_json(old).unwrap().curve.is_empty()); - } - - #[test] - fn factory_bank_has_the_drum_presets() { - let f = factory(); - for n in ["Drums_Baked", "Drums_Bricked", "Drums_Cooked", "Drums_Cruncher", "Drums_Thicc", "Drums_Tubed"] { - assert!(f.iter().any(|p| p.name == n), "missing factory preset {n}"); - } - // Cruncher uses the Custom shaper and ships its curve - let c = f.iter().find(|p| p.name == "Drums_Cruncher").unwrap(); - assert!(c.curve.len() >= 2); - } - - #[test] - fn factory_starts_with_init() { - assert_eq!(factory()[0].name, "INIT"); - } -} diff --git a/rust/satcomp-ui/Cargo.toml b/rust/satcomp-ui/Cargo.toml index 61daf19..31a4366 100644 --- a/rust/satcomp-ui/Cargo.toml +++ b/rust/satcomp-ui/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "satcomp-ui" -version = "0.5.3" +version = "0.5.4" edition = "2021" license = "GPL-3.0-or-later" publish = false @@ -9,6 +9,6 @@ publish = false # 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" } +nih_plug_egui = { path = "../vendor/nih_plug_egui", default-features = false, features = ["opengl"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/rust/satcomp-ui/assets/fonts/DMSans-Regular.ttf b/rust/satcomp-ui/assets/fonts/DMSans-Regular.ttf new file mode 100755 index 0000000..07266ae Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/DMSans-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/Figtree-Regular.ttf b/rust/satcomp-ui/assets/fonts/Figtree-Regular.ttf new file mode 100644 index 0000000..aa0edcf Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/Figtree-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/FiraSans-Regular.ttf b/rust/satcomp-ui/assets/fonts/FiraSans-Regular.ttf new file mode 100755 index 0000000..6f80647 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/FiraSans-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/HankenGrotesk-Regular.ttf b/rust/satcomp-ui/assets/fonts/HankenGrotesk-Regular.ttf new file mode 100755 index 0000000..6dc3655 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/HankenGrotesk-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/Lexend-Regular.ttf b/rust/satcomp-ui/assets/fonts/Lexend-Regular.ttf new file mode 100755 index 0000000..b869458 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/Lexend-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/Overpass-Regular.ttf b/rust/satcomp-ui/assets/fonts/Overpass-Regular.ttf new file mode 100755 index 0000000..f7a8da7 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/Overpass-Regular.ttf differ diff --git a/rust/satcomp-ui/assets/fonts/Questrial-Regular.ttf b/rust/satcomp-ui/assets/fonts/Questrial-Regular.ttf new file mode 100755 index 0000000..0f8c316 Binary files /dev/null and b/rust/satcomp-ui/assets/fonts/Questrial-Regular.ttf differ diff --git a/rust/satcomp-ui/src/appearance.rs b/rust/satcomp-ui/src/appearance.rs index a1c843a..e41ba09 100644 --- a/rust/satcomp-ui/src/appearance.rs +++ b/rust/satcomp-ui/src/appearance.rs @@ -8,7 +8,30 @@ //! //! 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::canvas::{font_pack, font_unpack, is_sans, num_faces, FONT_NAMES, PALETTES, SANS_START}; + +/// Row height of the font lists. +const FONT_ROW_H: f32 = 15.0; + +/// The rows of a font list as (face, label); `None` = a group header. Mono mode: the mono faces. Sans mode: list 1 = the sans UI +/// faces, list 2 = the faces that can set numbers, grouped. +fn font_list_items(sans: bool, list: u8) -> Vec<(Option, &'static str)> { + if list == 3 { + // the STARTUP SCALE list: 0 = off (factory sizes), k = START_SCALES[k - 1] + return ["OFF (FACTORY)", "100%", "125%", "150%", "175%", "200%", "250%"].iter().enumerate().map(|(k, l)| (Some(k), *l)).collect(); + } + if !sans { + return (0..SANS_START).map(|f| (Some(f), FONT_NAMES[f])).collect(); + } + if list != 2 { + return (SANS_START..FONT_NAMES.len()).map(|f| (Some(f), FONT_NAMES[f])).collect(); + } + let mut v = vec![(None, "SANS-SERIF")]; + v.extend(crate::canvas::NUM_SANS.iter().map(|&f| (Some(f), FONT_NAMES[f]))); + v.push((None, "MONOSPACE")); + v.extend((0..SANS_START).map(|f| (Some(f), FONT_NAMES[f]))); + v +} use crate::kit::Widgets; use serde::{Deserialize, Serialize}; use std::path::PathBuf; @@ -64,24 +87,18 @@ pub struct Defaults { 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, + // (files written before 0.5.4 also hold a `scale`: ignored, the start-up scale is its own global setting, `prefs.json`) } 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) } + /// The persisted font value (UI face, and the numerals face in the sans mode), made valid. pub fn face_index(&self) -> i32 { - self.face.clamp(0, FONT_NAMES.len() as i32 - 1) + crate::canvas::font_sanitize(self.face) as i32 } } @@ -100,6 +117,56 @@ fn write_defaults(p: Option, d: &Defaults) { } } +fn prefs_path() -> Option { + data_dir().map(|d| d.join("prefs.json")) +} + +/// Settings that are not part of a look (`SatComp/prefs.json`, shared by every plug-in). +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Debug)] +struct Prefs { + /// the window scale every NEW instance of every plug-in opens at; `None` = each plug-in's factory size + #[serde(default)] + start_scale: Option, +} + +/// The choices of the START SCALE row (the same steps as the window scale menus). +pub const START_SCALES: [f32; 6] = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5]; + +/// `act` of the About page's and the theme list's scrollbar drags. Every plug-in reads an `act` below its VIEW_ACT (100 or +/// 1000) as a slot number, and SatEQ / SatXComp / SatFilt have more than 140 slots, so these sit above any slot count. +pub const ACT_ABOUT_SCROLL: i32 = 9140; +pub const ACT_THEME_SCROLL: i32 = 9141; + +fn read_prefs() -> Prefs { + prefs_path().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() +} + +/// The global start-up scale, if one is set. +pub fn load_start_scale() -> Option { + read_prefs().start_scale.map(|s| s.clamp(1.0, 2.5)) +} + +/// Set (or clear, `None`) the global start-up scale. Takes effect the next time a plug-in instance is created; open instances +/// and saved projects keep their own size. +pub fn save_start_scale(scale: Option) { + let Some(p) = prefs_path() else { return }; + let mut prefs = read_prefs(); + prefs.start_scale = scale; + if let Some(dir) = p.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(s) = serde_json::to_string_pretty(&prefs) { + let _ = std::fs::write(p, s); + } +} + +/// The window size (logical pixels) a NEW instance opens at, for a plug-in with base size `base` whose factory scale is +/// `factory`: the global start-up scale when one is set, else the factory scale. A project restores its own size over this. +pub fn start_size(base: (f32, f32), factory: f32) -> (u32, u32) { + let s = load_start_scale().unwrap_or(factory); + ((base.0 * s).round() as u32, (base.1 * s).round() as u32) +} + /// The GLOBAL default (all plug-ins). pub fn load_defaults() -> Option { read_defaults(defaults_path()) @@ -196,12 +263,17 @@ pub fn load_themes() -> Vec { .unwrap_or_default() } +/// Name of the dice's throwaway scheme: listed with the user themes, carried by a project that uses it, never written to the +/// themes file (saving it from the theme editor stores it under a "Random N" name). +pub const RANDOM_NAME: &str = "RANDOM"; + fn save_themes(v: &[UserTheme]) { + let v: Vec<&UserTheme> = v.iter().filter(|t| t.name != RANDOM_NAME).collect(); 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) { + if let Ok(s) = serde_json::to_string_pretty(&v) { let _ = std::fs::write(p, s); } } @@ -321,7 +393,33 @@ pub struct ThemeEdit { pub osk: Option, } +impl ThemeEdit { + /// A new blank theme (black on white, red accent) for tests that open the editor without going through the pages. + pub fn blank() -> Self { + Self { name: String::new(), col: [[0.0; 3], [1.0; 3], [1.0, 0.0, 0.0], [1.0; 3], [0.0; 3], [1.0, 0.0, 0.0]], preview_light: false, index: None, picker: None, osk: None } + } +} + /// One line of the scrolling About / Changelog text. Head = version title (+ rule), takes the next Pad row too. +/// The About page's shared Misc Controls block (every plug-in; its own `about_misc` lines follow). +pub const MISC_CONTROLS: &[&str] = &[ + "== Misc Controls ==", + "[Click] [?] at the end of the preset bar to toggle help, then point at any control to see what it does", + "[Double-click] a slider to reset it to its default value", + "[Click] the logo to cycle the color scheme", + "[Right-click] the logo for the color scheme list", + "[Double-click] the logo to switch between dark and light mode", + "[Shift+Click] the logo to roll a random color scheme and font", + "[Click] the title to open or close this page", +]; + +/// The About page's closing credits (the footer names the font in use and the author). +pub const CREDITS: &[&str] = &[ + "== Credits ==", + "GPL-3.0-or-later. Built with nih-plug and egui.", + "Typefaces under the SIL Open Font License 1.1.", +]; + pub enum Row { Text(f32, String), Head(String), @@ -369,12 +467,16 @@ pub struct AppState { 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 + /// a font dropdown on the Preferences page is open pub font_open: bool, + /// which one: 1 = the font (mono mode) or the UI font (sans mode), 2 = the numerals font + pub font_list: u8, /// 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, + /// the global start-up scale (cached like `has_global`) + pub start_scale: Option, pub themes: Vec, pub edit: Option, pub real_in: RealInput, @@ -392,13 +494,14 @@ impl AppState { if self.about == 3 { self.ap_scroll = pal.saturating_sub(2); self.has_global = load_defaults().is_some(); + self.start_scale = load_start_scale(); } } self.about_scroll = 0; } pub fn new() -> Self { - Self { about: 0, about_last: 1, 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) } + Self { about: 0, about_last: 1, about_scroll: 0, ap_scroll: 0, del_arm: -10.0, note: (-10.0, ""), font_open: false, font_list: 1, def_menu: 0, has_global: load_defaults().is_some(), start_scale: load_start_scale(), 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. @@ -450,6 +553,11 @@ impl AppState { return i; } match self.themes.iter().position(|u| u.name == t.name) { + // the dice's scheme is throwaway: the project's own copy is the one it was saved with + Some(i) if t.name == RANDOM_NAME => { + self.themes[i] = t; + PALETTES.len() + i + } Some(i) => PALETTES.len() + i, None => { self.themes.push(t); @@ -493,15 +601,10 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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 @@ -515,9 +618,17 @@ pub trait AppearanceUi<'c>: Widgets<'c> { fn fill_label(&self) -> &'static str { "SPECTRUM FILL" } + /// Names of its two states (false, true). + fn fill_choices(&self) -> [&'static str; 2] { + ["OUTLINE", "SOLID"] + } - /// About page copy: paragraphs of source lines. + /// About page copy: paragraphs of source lines. A line `== Title ==` is a section heading. fn about_paras(&self) -> &'static [&'static [&'static str]]; + /// The plug-in's own lines under the shared Misc Controls block (its meters). + fn about_misc(&self) -> &'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. @@ -544,7 +655,52 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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 + /// Shift + click on the logo: a freshly generated colour scheme (the throwaway RANDOM entry of the user list, replaced on + /// every roll and checked for legibility, see `randtheme`) and a random font, never the current one. + fn roll_dice(&mut self) { + self.roll_colour(); + let now = self.kit_ref().now; + let cur = self.face(); + // the mode is part of the roll: mono (one face) or sans (a sans UI face with a face for the numbers); never the same font + for t in 0..8 { + let r = |k: f64| rand_u32(now + 1.7 + k + t as f64 * 0.37) as usize; + let packed = if r(0.0) % 2 == 0 { + let f = r(0.1) % SANS_START; + font_pack(f, f) + } else { + let nf = num_faces(); + font_pack(SANS_START + r(0.2) % (FONT_NAMES.len() - SANS_START), nf[r(0.3) % nf.len()]) + }; + if packed != cur { + self.commit_face(packed); + break; + } + } + } + + /// The colour half of the dice (also the Preferences page's dice): generate a legible scheme into the RANDOM entry and + /// select it. + fn roll_colour(&mut self) { + let now = self.kit_ref().now; + let seed = ((rand_u32(now + 3.1) as u64) << 32) | rand_u32(now + 5.9) as u64; + let (dark, light) = crate::randtheme::random_scheme(seed); + let t = UserTheme { name: RANDOM_NAME.to_string(), dark, light }; + let a = self.app(); + let idx = match a.themes.iter().position(|u| u.name == RANDOM_NAME) { + Some(i) => { + a.themes[i] = t; + i + } + None => { + a.themes.push(t); + a.themes.len() - 1 + } + }; + self.set_pal(PALETTES.len() + idx); + self.app().ap_scroll = (PALETTES.len() + idx).saturating_sub(2); + } + + /// Save this instance's look (scheme, mode, font, fill) 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(); @@ -556,7 +712,6 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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); @@ -588,7 +743,6 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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); @@ -598,8 +752,6 @@ pub trait AppearanceUi<'c>: Widgets<'c> { let f = self.factory_fill_solid(); self.commit_fft_solid(f); } - let f = self.factory_scale(); - self.set_scale(f); } } } @@ -678,13 +830,15 @@ pub trait AppearanceUi<'c>: Widgets<'c> { // ------------------------------------------------------------------ pages /// About / Appearance / Changelog inside `r` (tab row 22 units above it). fn draw_about(&mut self, r: Rect, byp: bool) { + // the About / Preferences / Changelog pages are not part of the processing: never dimmed by BYPASS + self.set_dk(1.0); 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) { + if self.btn_sel(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; @@ -692,6 +846,7 @@ pub trait AppearanceUi<'c>: Widgets<'c> { if id == 3 { a.ap_scroll = pal.saturating_sub(2); a.has_global = load_defaults().is_some(); + a.start_scale = load_start_scale(); } } } @@ -748,8 +903,15 @@ pub trait AppearanceUi<'c>: Widgets<'c> { }; let (by, bh) = (by + off, bh - off); let mut rows = Vec::new(); - for para in self.about_paras() { - for l in *para { + let misc: [&[&str]; 2] = [MISC_CONTROLS, self.about_misc()]; + let tail: [&[&str]; 2] = [&misc.concat(), CREDITS]; + for para in self.about_paras().iter().copied().chain(tail.iter().copied()) { + for l in para { + if let Some(h) = l.strip_prefix("== ").and_then(|l| l.strip_suffix(" ==")) { + rows.push(Row::Head(h.to_string())); + rows.push(Row::Pad); + continue; + } for t in self.wrap(l, r.w - 30.0) { rows.push(Row::Text(0.0, t)); } @@ -758,8 +920,9 @@ pub trait AppearanceUi<'c>: Widgets<'c> { } 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])); + let (ui, num) = font_unpack(self.face() as i64); + let names = if ui == num { FONT_NAMES[ui].to_string() } else { format!("{} + {}", FONT_NAMES[ui], FONT_NAMES[num]) }; + self.cv().text(r.x + 6.0, r.y + r.h - 17.0, &format!("Font: {names} (SIL OFL 1.1)")); self.cv().textr(r.x, r.y + r.h - 17.0, r.w - 6.0, "thomchantra"); } @@ -769,19 +932,46 @@ pub trait AppearanceUi<'c>: Widgets<'c> { // 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 sx_row = 0.0; + // the font takes two rows (FONT MONO | SANS, then its dropdown or the UI | NUM pair) + // the scheme list takes what the rest leaves (at least 3 rows: a short page such as SatEQ's scrolls a shorter list) + let rows = ((r.h - 154.0 - hx - sx_row) / RH).floor().max(3.0) as usize; + let extra = rows as f32 * RH - 100.0; 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 + // Font dropdowns: their 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 fy2 = fy + 22.0; + let (ui_face, num_face) = font_unpack(self.face() as i64); + let sans = is_sans(ui_face); + let dx = lx + 44.0; + let right = lx + lw; + // the dropdowns of row 2: one (mono) or UI | NUM (sans) + let half = ((right - dx - 34.0) * 0.5).floor(); + // STARTUP SCALE: label and dropdown at the right end of the FONT row; the MONO | SANS buttons narrow if the label needs it + let (sw_dd, label_w) = (52.0, 92.0); + let mw = if right - sw_dd - 6.0 - label_w >= dx + 2.0 * 48.0 + 8.0 { 48.0 } else { 40.0 }; + let dd = |k: u8| -> Rect { + if k == 3 { + return Rect::new(right - sw_dd, fy - 4.0, sw_dd, 18.0); + } + match (sans, k) { + (false, _) => Rect::new(dx, fy2 - 4.0, right - dx, 18.0), + (true, 1) => Rect::new(dx, fy2 - 4.0, half, 18.0), + _ => Rect::new(dx + half + 34.0, fy2 - 4.0, right - dx - half - 34.0, 18.0), + } + }; + let list_kind = self.app_ref().font_list; + let items = font_list_items(sans, list_kind); + let list_r = { + let d = dd(list_kind.max(1)); + let h = items.len() as f32 * FONT_ROW_H + 2.0; + let w = d.w.max(124.0).min(right - lx); + let x = d.x.min(right - w); + Rect::new(x, (d.y - h).max(r.y + 2.0), w, h) + }; let bw = ((lw - 8.0) * 0.5).floor(); - let by = fy + 20.0; + let by = fy + 42.0 + sx_row; 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); @@ -792,9 +982,24 @@ pub trait AppearanceUi<'c>: Widgets<'c> { }; 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); + if real.4 >= list_r.x && real.4 < list_r.x + list_r.w && real.5 >= list_r.y && real.5 < list_r.y + list_r.h { + let i = (((real.5 - list_r.y - 1.0) / FONT_ROW_H).floor().max(0.0) as usize).min(items.len() - 1); + if list_kind == 3 { + if let Some(k) = items[i].0 { + let next = if k == 0 { None } else { Some(START_SCALES[k - 1]) }; + save_start_scale(next); + self.app().start_scale = next; + let now = self.kit_ref().now; + self.app().note = (now, if next.is_some() { "Startup scale saved: new instances open at it" } else { "Startup scale off: factory sizes" }); + } + } else if let Some(f) = items[i].0 { + let packed = match (sans, list_kind) { + (false, _) => font_pack(f, f), + (true, 1) => font_pack(f, num_face), + _ => font_pack(ui_face, f), + }; + self.commit_face(packed); + } } self.app().font_open = false; } @@ -815,7 +1020,7 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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) { + if self.btn_sel(r.x + dx, r.y + 4.0, 64.0, 16.0, l, (light == lt) as u8) { self.set_light(lt); } } @@ -824,8 +1029,9 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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) { + let ch = self.fill_choices(); + for (dx, l, sd) in [(0.0, ch[0], false), (74.0, ch[1], true)] { + if self.btn_sel(bx0 + dx, ly0, if sd { 56.0 } else { 72.0 }, 16.0, l, (solid == sd) as u8) { self.commit_fft_solid(sd); } } @@ -837,21 +1043,13 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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 + // dice: a freshly generated legible scheme (the RANDOM entry), colour only 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.roll_colour(); } self.setc(false); self.cv().boxr(dx0 + 4.0, dy0 + 2.0, 10.0, 10.0); @@ -898,10 +1096,10 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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.act = ACT_THEME_SCROLL; k.press = false; } - if self.kit_ref().act == 141 && self.kit_ref().down { + if self.kit_ref().act == ACT_THEME_SCROLL && 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; } @@ -944,28 +1142,79 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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; + let act141 = self.kit_ref().act == ACT_THEME_SCROLL; self.setc(act141); self.cv().fill(tx + 1.0, top.floor(), 5.0, thumb); self.setc(false); - // ---- font (dropdown) and the buttons under it + // ---- font: the mode (MONO = one face for everything, SANS = a sans UI face with a face for numbers), then its dropdowns 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; + for (k, l) in ["MONO", "SANS"].iter().enumerate() { + let on = sans == (k == 1); + if self.btn_sel(dx + k as f32 * (mw - 1.0), fy - 4.0, mw, 18.0, l, on as u8) && !on { + let packed = if k == 1 { + // into the sans mode: Hanken Grotesk for the UI, the mono face for the numbers + font_pack(SANS_START, ui_face) + } else { + // back to the mono mode: the numbers' face if it is a mono one + let f = if is_sans(num_face) { 0 } else { num_face }; + font_pack(f, f) + }; + self.commit_face(packed); + } + } + let (ui_face, num_face) = font_unpack(self.face() as i64); + let sans = is_sans(ui_face); + if sans { + self.setc(false); + self.cv().text(lx, fy2, "UI"); + self.cv().text(dd(2).x - 28.0, fy2, "NUM"); + } + for k in if sans { 1u8..=2 } else { 1u8..=1 } { + let d = dd(k); + if !was_open && menu == 0 && self.hit(d.x, d.y, d.w, d.h) && self.kit_ref().press && self.kit_ref().act == 0 { + let a = self.app(); + a.font_open = true; + a.font_list = k; + self.kit().press = false; + } + let f = if k == 2 { num_face } else { ui_face }; + self.setc(false); + self.cv().boxr(d.x, d.y, d.w, d.h); + let keep = self.cv().face; + self.cv().face = f; // the name is drawn in its own typeface + let mut name = FONT_NAMES[f].to_string(); + while self.cv().text_w(&name) > d.w - 20.0 && name.chars().count() > 3 { + name.pop(); + } + self.cv().text(d.x + 6.0, fy2, &name); + self.cv().face = keep; + let (ax, ay) = (d.x + d.w - 10.0, fy2 + 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); + } + + // STARTUP SCALE: the window scale every new instance of every plug-in opens at (prefs.json); OFF = each plug-in's factory + // size. Open instances and saved projects keep their own size. + { + let d = dd(3); + self.setc(false); + self.cv().textr(d.x - 6.0 - label_w, fy, label_w, "STARTUP SCALE"); + if !was_open && menu == 0 && self.hit(d.x, d.y, d.w, d.h) && self.kit_ref().press && self.kit_ref().act == 0 { + let a = self.app(); + a.font_open = true; + a.font_list = 3; + self.kit().press = false; + } + self.cv().boxr(d.x, d.y, d.w, d.h); + let cur = self.app_ref().start_scale.map(|s| format!("{:.0}%", s * 100.0)).unwrap_or_else(|| "OFF".into()); + self.cv().text_n(d.x + 5.0, fy, &cur); + let (ax, ay) = (d.x + d.w - 9.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); + self.setc(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; @@ -1016,24 +1265,43 @@ pub trait AppearanceUi<'c>: Widgets<'c> { k.mx = real.4; k.my = real.5; self.cv().setbg(); - self.cv().fill(dx, list_y, dw, list_h); + self.cv().fill(list_r.x, list_r.y, list_r.w, list_r.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.cv().boxr(list_r.x, list_r.y, list_r.w, list_r.h); + let cur = if list_kind == 3 { + self.app_ref().start_scale.and_then(|s| START_SCALES.iter().position(|&v| (v - s).abs() < 0.01)).map_or(0, |k| k + 1) + } else if sans && list_kind == 2 { + num_face + } else { + ui_face + }; + for (i, (f, label)) in items.iter().enumerate() { + let y = list_r.y + 1.0 + i as f32 * FONT_ROW_H; + let Some(f) = *f else { + // a group header (the numerals list): dim, not selectable + let dk = self.kit_ref().dk; + self.set_dk(dk * 0.5); + self.setc(false); + self.cv().text(list_r.x + 6.0, y + 4.0, label); + self.set_dk(dk); + continue; + }; + let hov = real.4 >= list_r.x && real.4 < list_r.x + list_r.w && real.5 >= y && real.5 < y + FONT_ROW_H; self.setc(false); - let on = i == face; - if on { - self.cv().fill(dx + 1.0, y, dw - 2.0, FH); + if f == cur { + self.cv().fill(list_r.x + 1.0, y, list_r.w - 2.0, FONT_ROW_H); self.cv().setbg(); } else if hov { - self.cv().boxr(dx + 2.0, y + 1.0, dw - 4.0, FH - 2.0); + self.cv().boxr(list_r.x + 2.0, y + 1.0, list_r.w - 4.0, FONT_ROW_H - 2.0); + } + if list_kind == 3 { + self.cv().text(list_r.x + 6.0, y + 4.0, label); + } else { + let keep = self.cv().face; + self.cv().face = f; + self.cv().text(list_r.x + 6.0, y + 4.0, label); + self.cv().face = keep; } - 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); } @@ -1079,11 +1347,11 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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.act = ACT_ABOUT_SCROLL; k.press = false; self.about_scroll_drag_start(); } - if self.kit_ref().act == 140 && self.kit_ref().down { + if self.kit_ref().act == ACT_ABOUT_SCROLL && 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; } @@ -1108,7 +1376,7 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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; + let act140 = self.kit_ref().act == ACT_ABOUT_SCROLL; self.setc(act140); self.cv().fill(tx + 1.0, top.floor(), 5.0, thumb); self.setc(false); @@ -1156,6 +1424,14 @@ pub trait AppearanceUi<'c>: Widgets<'c> { if name.is_empty() { name = format!("Custom {}", self.app_ref().themes.len() + 1); } + // saving the dice's throwaway scheme keeps it: under a numbered name (RANDOM itself is never written to the file) + if name.eq_ignore_ascii_case(RANDOM_NAME) { + let mut k = 1; + while self.app_ref().themes.iter().any(|u| u.name.eq_ignore_ascii_case(&format!("Random {k}"))) { + k += 1; + } + name = format!("Random {k}"); + } 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)) @@ -1204,7 +1480,7 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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.cv().textc_n(x, y + (h * 0.4 + 1.0).floor(), w, val); self.setc(false); clicked } @@ -1248,7 +1524,7 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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.cv().textc_n(x + 3.0, y + 20.0, w - 6.0, &format!("#{}", hex6(col))); self.setc(false); if clicked { self.kit().press = false; @@ -1487,7 +1763,7 @@ pub trait AppearanceUi<'c>: Widgets<'c> { 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]))); + self.cv().text_n(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 { @@ -1516,6 +1792,45 @@ pub trait AppearanceUi<'c>: Widgets<'c> { #[cfg(test)] mod tests { + /// START SCALE: unset = each plug-in's factory size; set = every plug-in's new instances open at it; cleared again = factory. + /// A look default written before it existed (with its own `scale`) still loads, and its scale plays no part. + #[test] + fn the_start_scale_sizes_new_instances_and_old_defaults_still_load() { + let dir = std::env::temp_dir().join(format!("satcomp-prefs-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + std::env::set_var("SATCOMP_DATA_DIR", &dir); + save_start_scale(None); + assert_eq!(load_start_scale(), None); + assert_eq!(start_size((560.0, 336.0), 1.25), (700, 420), "factory size while unset"); + assert_eq!(start_size((316.0, 578.0), 1.0), (316, 578)); + save_start_scale(Some(1.5)); + assert_eq!(load_start_scale(), Some(1.5)); + assert_eq!(start_size((560.0, 336.0), 1.25), (840, 504), "one scale for every plug-in"); + assert_eq!(start_size((316.0, 578.0), 1.0), (474, 867)); + save_start_scale(None); + assert_eq!(start_size((316.0, 578.0), 1.0), (316, 578), "cleared: factory again"); + let old = r#"{"pal": 3, "theme": "", "light": true, "face": 2, "fill_solid": false, "scale": 2.0}"#; + std::fs::write(dir.join("defaults.json"), old).unwrap(); + let d = load_defaults().expect("an old defaults file still loads"); + assert_eq!((d.pal, d.light, d.face), (3, true, 2)); + assert_eq!(start_size((560.0, 336.0), 1.25), (700, 420), "its scale is ignored"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_projects_random_scheme_wins_over_the_sessions_and_is_never_saved() { + let mut a = AppState { themes: Vec::new(), ..AppState::new() }; + let mine = UserTheme { name: RANDOM_NAME.into(), dark: [0.1; 9], light: [0.9; 9] }; + a.themes.push(UserTheme { name: RANDOM_NAME.into(), dark: [0.5; 9], light: [0.5; 9] }); // rolled in this session + let i = a.restore_custom(0, &encode(&mine)); + assert_eq!(i, PALETTES.len()); + assert_eq!(a.themes.len(), 1); + assert_eq!(a.themes[0].dark[0], decode(&encode(&mine)).unwrap().dark[0], "the project's copy replaces the session's"); + // the filter the themes file goes through drops it + let kept: Vec<&UserTheme> = a.themes.iter().filter(|t| t.name != RANDOM_NAME).collect(); + assert!(kept.is_empty()); + } + use super::*; #[test] diff --git a/rust/satcomp-ui/src/bench.rs b/rust/satcomp-ui/src/bench.rs new file mode 100644 index 0000000..8817f05 --- /dev/null +++ b/rust/satcomp-ui/src/bench.rs @@ -0,0 +1,55 @@ +//! Editor cost for the multi-instance audit: every open editor of every plug-in draws on the host's one UI thread, so the +//! frame time of one editor times the editors a session keeps open is the budget that matters. The plug-ins' headless test +//! rigs call `timing()` after `ctx.run`: while a measurement runs they tessellate the frame like a real one (instead of +//! hashing it for the golden checks) and skip the rest. + +use std::cell::Cell; +use std::time::Instant; + +thread_local! { + static TIMING: Cell = const { Cell::new(false) }; +} + +/// Set while `frame_cost` measures (per thread, so tests running alongside are not affected). +pub fn timing() -> bool { + TIMING.with(|t| t.get()) +} + +/// Resident memory of this process in KiB (from `ps`). +pub fn rss_kib() -> f64 { + let o = std::process::Command::new("ps").args(["-o", "rss=", "-p", &std::process::id().to_string()]).output(); + o.ok().and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()).unwrap_or(0.0) +} + +/// Median / p95 milliseconds of an idle frame (UI pass + tessellation) after a warm-up, and the memory one more open editor +/// costs (8 editors built and drawn, the RSS growth divided by 8). Prints one table row and returns (median, p95, MiB). +pub fn frame_cost(name: &str, mut make: impl FnMut() -> R, mut frame: impl FnMut(&mut R)) -> (f64, f64, f64) { + TIMING.with(|t| t.set(true)); + let mut r = make(); + for _ in 0..30 { + frame(&mut r); + } + // SATCOMP_BENCH_FRAMES: more frames, for running the measurement under a sampling profiler + let frames: usize = std::env::var("SATCOMP_BENCH_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(300); + let mut ms: Vec = (0..frames) + .map(|_| { + let t0 = Instant::now(); + frame(&mut r); + t0.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + ms.sort_by(|a, b| a.partial_cmp(b).unwrap()); + let (med, p95) = (ms[ms.len() / 2], ms[ms.len() * 95 / 100]); + let r0 = rss_kib(); + let mut many: Vec = (0..8).map(|_| make()).collect(); + for _ in 0..20 { + for e in many.iter_mut() { + frame(e); + } + } + let mib = (rss_kib() - r0) / 1024.0 / 8.0; + drop(many); + TIMING.with(|t| t.set(false)); + println!("| {name} | {med:.2} | {p95:.2} | {mib:.1} | {:.0} |", 16.7 / med); + (med, p95, mib) +} diff --git a/rust/satcomp-ui/src/canvas.rs b/rust/satcomp-ui/src/canvas.rs index de38215..dd209fc 100644 --- a/rust/satcomp-ui/src/canvas.rs +++ b/rust/satcomp-ui/src/canvas.rs @@ -50,14 +50,62 @@ pub const PALETTES: [(&str, [f32; 9], [f32; 9]); 30] = [ ]; /// Selectable UI fonts (index persisted as `ui-font`: append, do not reorder). All are SIL OFL 1.1. -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"]; +/// 0..SANS_START are monospace, the rest sans-serif (the UI font of the sans mode, see `font_pack`). +pub const FONT_NAMES: [&str; 18] = [ + "Fira Code", "JetBrains Mono", "Geist Mono", "Roboto Mono", "Oxygen Mono", "Doto", "DM Mono", "Victor Mono", "Anonymous Pro", "Inconsolata", "Courier Prime", + "Hanken Grotesk", "Overpass", "Questrial", "DM Sans", "Figtree", "Lexend", "Fira Sans", +]; + +/// First sans-serif face in `FONT_NAMES`. +pub const SANS_START: usize = 11; +/// The sans faces whose default figures are tabular (equal width), so they can set numbers: Hanken Grotesk, Questrial. (egui +/// cannot switch on the `tnum` feature, so only fonts whose plain digits are already tabular qualify.) +pub const NUM_SANS: [usize; 2] = [11, 13]; + +pub fn is_sans(face: usize) -> bool { + face >= SANS_START && face < FONT_NAMES.len() +} + +/// Faces that may set numbers in the sans mode: the two tabular sans faces, then every monospace face. +pub fn num_faces() -> Vec { + NUM_SANS.iter().copied().chain(0..SANS_START).collect() +} + +/// The persisted font value (`ui-font`): the UI face in the low byte; in the sans mode the numerals face + 1 in the next byte +/// (0 = none: the mono mode, one face for everything). Values written before the sans mode (0..10) read as the mono mode. +pub fn font_pack(ui: usize, num: usize) -> usize { + if is_sans(ui) { + ui | ((num + 1) << 8) + } else { + ui.min(SANS_START - 1) + } +} + +/// (UI face, numerals face) of a persisted font value, made valid: the mono mode sets numbers in the UI face; a sans UI face +/// with no or an unusable numerals face falls back to Fira Code. +pub fn font_unpack(v: i64) -> (usize, usize) { + let v = v.max(0) as usize; + let ui = (v & 0xff).min(FONT_NAMES.len() - 1); + if !is_sans(ui) { + return (ui, ui); + } + let n = (v >> 8) & 0xff; + let num = if n >= 1 && num_faces().contains(&(n - 1)) { n - 1 } else { 0 }; + (ui, num) +} + +/// A persisted font value made valid and canonical (what the plug-ins keep in their state). +pub fn font_sanitize(v: i32) -> usize { + let (ui, num) = font_unpack(v as i64); + font_pack(ui, num) +} /// 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] = [ +pub const FONT_TUNE: [(f32, f32); 18] = [ (1.00, 0.0), // Fira Code (0.97, 0.0), // JetBrains Mono (1.00, 0.0), // Geist Mono @@ -69,12 +117,40 @@ pub const FONT_TUNE: [(f32, f32); 11] = [ (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) + // sans faces: matched to Fira Code's cap height (OS/2 capHeight), then held down where a label would outgrow Fira Code's width + // (see `sans_labels_fit_where_fira_code_fits`) + (1.013, 0.0), // Hanken Grotesk + (1.009, 0.0), // Overpass + (1.0, 0.0), // Questrial (cap-height match 1.067; held down so its values are no wider than Fira Code's) + (1.009, 0.0), // DM Sans + (1.009, 0.0), // Figtree + (0.975, 0.0), // Lexend (cap-height match 1.009; held down to fit SatComp's RNGE row) + (1.025, 0.0), // Fira Sans ]; pub fn font_family(i: usize) -> FontFamily { FontFamily::Name(format!("f{i}").into()) } +/// `s` split into runs of digits and of everything else: (is digits, run). +fn digit_runs(s: &str) -> Vec<(bool, &str)> { + let mut v = Vec::new(); + let mut start = 0; + let mut cur: Option = None; + for (i, ch) in s.char_indices() { + let d = ch.is_ascii_digit(); + if cur.is_some_and(|c| c != d) { + v.push((cur.unwrap(), &s[start..i])); + start = i; + } + cur = Some(d); + } + if let Some(c) = cur { + v.push((c, &s[start..])); + } + v +} + pub struct Canvas<'a> { pub p: &'a Painter, /// pixels_per_point @@ -90,8 +166,10 @@ pub struct Canvas<'a> { pub dk: f32, pub col: Color32, pub font: u8, - /// index into FONT_NAMES + /// index into FONT_NAMES: the UI face (labels, buttons, titles) pub face: usize, + /// the face numbers are set in (`text_n` and friends): the UI face in the mono mode, the numerals face in the sans mode + pub num_face: usize, } fn lum(c: [f32; 3]) -> f32 { @@ -145,7 +223,9 @@ fn rgb(c: [f32; 3]) -> Color32 { } impl<'a> Canvas<'a> { - pub fn new(p: &'a Painter, ppp: f32, ox: f32, oy: f32, s: f32, a: [f32; 9], face: usize) -> Self { + /// `font` is the persisted font value (see `font_pack`). + pub fn new(p: &'a Painter, ppp: f32, ox: f32, oy: f32, s: f32, a: [f32; 9], font: usize) -> Self { + let (face, num_face) = font_unpack(font as i64); let mut c = Self { p, ppp, @@ -158,7 +238,8 @@ impl<'a> Canvas<'a> { dk: 1.0, col: Color32::WHITE, font: 1, - face: face.min(FONT_NAMES.len() - 1), + face, + num_face, }; c.setc(false); c @@ -201,6 +282,17 @@ impl<'a> Canvas<'a> { self.p.rect_filled(egui::Rect::from_min_max(Pos2::new(x0, y0), Pos2::new(x1, y1)), 0.0, self.col); } + /// Fill with the background colour at opacity `a` (0..1): a translucent plate behind text drawn over a busy viewport. + pub fn fill_bg_alpha(&self, x: f32, y: f32, w: f32, h: f32, a: f32) { + let c = rgb(self.bk); + let col = Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), (a.clamp(0.0, 1.0) * 255.0) as u8); + let x0 = self.snap(self.ox + x * self.s); + let y0 = self.snap(self.oy + y * self.s); + let x1 = self.snap(self.ox + (x + w) * self.s).max(x0 + 1.0 / self.ppp); + let y1 = self.snap(self.oy + (y + h) * self.s).max(y0 + 1.0 / self.ppp); + self.p.rect_filled(egui::Rect::from_min_max(Pos2::new(x0, y0), Pos2::new(x1, y1)), 0.0, col); + } + pub fn boxr(&self, x: f32, y: f32, w: f32, h: f32) { self.fill(x, y, w, 1.0); self.fill(x, y + h - 1.0, w, 1.0); @@ -208,15 +300,26 @@ impl<'a> Canvas<'a> { self.fill(x + w - 1.0, y, 1.0, h); } + /// Switch to the persisted font value `font` (see `font_pack`). + pub fn set_face(&mut self, font: usize) { + let (f, n) = font_unpack(font as i64); + self.face = f; + self.num_face = n; + } + fn fid(&self) -> FontId { + self.fid_of(self.face) + } + + fn fid_of(&self, face: usize) -> FontId { let sz = match self.font { 1 => 12.0, 2 => 14.0, 4 => 18.5, // header title (cap height 11.3 units: 17 px at 150 %) 5 => 10.0, // header version (digits 6 units high) _ => 18.0, - } * self.s * FONT_SCALE * FONT_TUNE[self.face].0; - FontId::new(sz.max(5.0), font_family(self.face)) + } * self.s * FONT_SCALE * FONT_TUNE[face].0; + FontId::new(sz.max(5.0), font_family(face)) } pub fn set_font(&mut self, f: u8) { @@ -224,19 +327,54 @@ impl<'a> Canvas<'a> { } pub fn text_w(&self, s: &str) -> f32 { - let g = self.p.layout_no_wrap(s.to_string(), self.fid(), self.col); + self.text_w_of(self.face, s) + } + + fn text_w_of(&self, face: usize, s: &str) -> f32 { + let g = self.p.layout_no_wrap(s.to_string(), self.fid_of(face), self.col); g.size().x / self.s } pub fn text(&self, x: f32, y: f32, s: &str) { - 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, - s, - self.fid(), - self.col, - ); + self.text_of(self.face, x, y, s); + } + + fn text_of(&self, face: usize, x: f32, y: f32, s: &str) { + let fid = self.fid_of(face); + let lift = (TEXT_LIFT_EM - FONT_TUNE[face].1) * 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, s, fid, self.col); + } + + /// A number (a value, a readout, a scale mark): set in the numerals face, the same as `text` in the mono mode. A sans + /// numerals face has tabular digits but not tabular signs, dots or units (+ and - differ in width, so a value would jump as + /// its sign flips): with one, only the digits take it, everything else stays in Fira Code. + pub fn text_n(&self, x: f32, y: f32, s: &str) { + if !is_sans(self.num_face) { + return self.text_of(self.num_face, x, y, s); + } + let mut cx = x; + for (digits, run) in digit_runs(s) { + let f = if digits { self.num_face } else { 0 }; + self.text_of(f, cx, y, run); + cx += self.text_w_of(f, run); + } + } + + pub fn text_w_n(&self, s: &str) -> f32 { + if !is_sans(self.num_face) { + return self.text_w_of(self.num_face, s); + } + digit_runs(s).iter().map(|&(digits, run)| self.text_w_of(if digits { self.num_face } else { 0 }, run)).sum() + } + + pub fn textc_n(&self, x: f32, y: f32, w: f32, s: &str) { + let tw = self.text_w_n(s); + self.text_n(x + (w - tw) * 0.5, y, s); + } + + pub fn textr_n(&self, x: f32, y: f32, w: f32, s: &str) { + let tw = self.text_w_n(s); + self.text_n(x + w - tw, y, s); } /// Vertical extent of the ink of `ch` in the current font, in units relative to the `y` that `text` is given (so the y that @@ -303,13 +441,15 @@ impl<'a> Canvas<'a> { } /// The plug-in icon, drawn in the current colour inside the 20 x 20 plate whose top left is (x, y) (0 SatComp, 1 SatXComp, - /// 2 SatLim, 3 SatDiff). The shapes are the filled paths of the logo SVGs (see `logo_art`, generated by tools/gen_logo.py), + /// 2 SatLim, 3 SatDiff, 4 SatEQ, 5 SatFilt). The shapes are the filled paths of the logo SVGs (see `logo_art`, generated by tools/gen_logo.py), /// scaled from the SVG's 30 units to the plate, so the icon scales cleanly with the window. pub fn logo_art(&self, kind: u8, x: f32, y: f32) { let quads: &[[f32; 8]] = match kind { 0 => &crate::logo_art::LOGO_COMP, 1 => &crate::logo_art::LOGO_XCOMP, 2 => &crate::logo_art::LOGO_LIM, + 4 => &crate::logo_art::LOGO_EQ, + 5 => &crate::logo_art::LOGO_FILT, _ => &crate::logo_art::LOGO_DIFF, }; let k = 20.0 / 30.0; @@ -319,6 +459,14 @@ impl<'a> Canvas<'a> { } } + /// The dice (shown in place of the plug-in icon while shift is held: a click rolls colour and font): the five pips of a die in + /// the 20 x 20 plate, in the current colour. + pub fn dice_art(&self, x: f32, y: f32) { + for (px, py) in [(0.0, 0.0), (2.0, 0.0), (1.0, 1.0), (0.0, 2.0), (2.0, 2.0)] { + self.fill(x + 3.0 + px * 5.0, y + 3.0 + py * 5.0, 4.0, 4.0); + } + } + pub fn textc(&self, x: f32, y: f32, w: f32, s: &str) { let tw = self.text_w(s); self.text(x + (w - tw) * 0.5, y, s); @@ -367,3 +515,122 @@ mod gain_colour_tests { assert!(is_grey_scheme([a.1[0]; 3], [a.1[3]; 3], [a.1[6]; 3])); } } + +/// The sans mode against the layouts, which were drawn for monospace faces. Overall the sans faces are narrower than Fira Code, +/// but capitals like D, W and M are wider, so the check is made where it matters: the tightest real cases of the six plug-ins, +/// each a label in its box (the box width less its padding, less the value sharing the row, measured in Fira Code). Every case +/// must fit in every sans UI face at its `FONT_TUNE` size, and the tabular numerals faces must set values no wider than Fira +/// Code. The test prints each face's tightest case; a face that does not fit is held down in `FONT_TUNE`. +#[cfg(test)] +mod font_fit_tests { + use super::*; + use nih_plug_egui::egui; + + /// (label, box width, value in the same row ("" = none), centred button). Widths in logical units at font 1 (12 px). + const CASES: &[(&str, f32, &str, bool)] = &[ + // SatComp: 62-wide cells, buttons, the KNEE / SHPE / RNGE rows, the sidechain row + ("RELEASE", 62.0, "", false), ("PEAK>RMS", 62.0, "", false), ("SAT GAIN", 62.0, "", false), ("OUT GAIN", 62.0, "", false), + ("L.AHEAD", 62.0, "", false), ("GR DIST", 62.0, "", false), ("LOW CUT", 62.0, "", false), ("SAT MIX", 62.0, "", false), + ("SIDECHAIN", 76.0, "", true), ("DWNWARD", 62.0, "", true), ("UP/DWN", 62.0, "", true), ("GAIN MATCH", 86.0, "", true), + ("KNEE", 62.0, "24.0", false), ("SHPE", 62.0, "100%", false), ("RNGE", 62.0, "24.0", false), ("SC", 71.0, "+24.0dB", false), + ("POST-COMP", 132.0, "", true), ("MAKEUP", 86.0, "", false), + // SatXComp: 74-wide cells and rows, the crossover rows (the slope button takes 34) + ("COMP MIX", 74.0, "", false), ("CMP GAIN", 74.0, "", false), ("K.SHAPE", 74.0, "0%", false), ("RANGE", 74.0, "12.0", false), + ("ASYM", 74.0, "100%", false), ("XOV1", 87.0, "20000Hz", false), ("L.AHEAD", 120.0, "10.0ms", false), ("EQ GAIN", 80.0, "", false), + // SatLim: the 98-wide limiter column + ("LOOKAHEAD OFF", 98.0, "", true), ("CLIP", 98.0, "+6.0dB", false), ("RELEASE", 64.0, "", false), ("OVERSAMPLE", 78.0, "", true), + ("CEIL", 98.0, "-24.0dB", false), ("THRESH", 98.0, "-30.0dB", false), ("HARD CLIP", 86.0, "", false), ("KNEE", 98.0, "-24.0dB", false), + // SatDiff: 72-wide cells, 62-wide right column + ("COLOR MIX", 72.0, "", false), ("POST-SAT", 72.0, "", true), ("IN GAIN", 62.0, "", false), ("OUT GAIN", 62.0, "", false), + ("INIT B", 60.0, "", true), ("STAGES", 72.0, "", false), ("PHASE", 72.0, "-180", false), ("FREQ SHIFT", 112.0, "", false), + ("HPF", 72.0, "2000Hz", false), ("SPEED", 62.0, "", false), ("DEPTH", 62.0, "", false), + // SatEQ: the 108-wide sidebar, the 116-wide right column, the header row + ("EQ7 SATURATE", 89.0, "", true), ("EQ7 BANDPASS", 89.0, "", true), ("EQ7 DYNAMIC", 89.0, "", true), ("SIDECHAIN SRC", 108.0, "", true), + ("DYNAMIC MODE", 108.0, "", true), ("DOWNWARD", 80.0, "", true), ("THRES", 91.0, "-60.0dB", false), ("SAT Q", 108.0, "-4.0", false), + ("OVRDRV", 108.0, "36.0dB", false), ("DRVE", 69.0, "100%", false), ("OD", 69.0, "36.0dB", false), ("SLP", 55.0, "48dB", false), + ("SIDE GAIN", 116.0, "", false), ("OUT MIX", 116.0, "100%", false), ("B.SOLO", 59.0, "", true), ("RESET A", 74.0, "", true), + ("LO-SHELF", 80.0, "", true), + // SatFilt: 79.5-wide cells, the 93-wide LFO rows, the 62-wide strip + ("DIFFUSION", 79.5, "", false), ("POLARITY", 79.5, "", false), ("HOLD-DIFF-GLIDE", 163.0, "100", false), ("MODE LP-BP-HP", 163.0, "100", false), + ("PHASE", 93.0, "360", false), ("WIDTH", 93.0, "100%", false), ("LFO MOD", 66.0, "", true), ("PARALLEL", 62.0, "", true), + ("FB TAP", 79.5, "", false), ("2 BARS", 65.0, "", true), + ]; + + const VALUES: [&str; 12] = ["+00.0dB", "-----dB", "-24.0dB", "20.0k", "20000Hz", "2000ms", "100%", "4.0:1", "-0.00", "1/32T", "8/20 PTS", "+12"]; + + /// Width in logical units, measured at 4x (egui rounds advances to whole pixels: at 1x, ~10 px text, that is too coarse; the + /// editor draws at the window scale times the display density, so 4x is close to what it shows at 200 % on a Retina screen). + fn w(ctx: &egui::Context, face: usize, t: &str) -> f32 { + const K: f32 = 4.0; + let id = FontId::new(12.0 * FONT_SCALE * FONT_TUNE[face].0 * K, font_family(face)); + ctx.fonts(|f| f.layout_no_wrap(t.to_string(), id, Color32::WHITE).size().x) / K + } + + /// Room for the label of a case, measured with Fira Code's value width. + fn room(ctx: &egui::Context, (_, bw, val, centred): (&str, f32, &str, bool)) -> f32 { + let pad = if centred { 4.0 } else { 6.0 }; + bw - pad - if val.is_empty() { 0.0 } else { w(ctx, 0, val) + 1.0 } + } + + #[test] + fn sans_labels_fit_their_boxes_and_numerals_fit_like_fira_code() { + let ctx = egui::Context::default(); + crate::init_ctx(&ctx); + let _ = ctx.run(Default::default(), |_| {}); + let mut bad = Vec::new(); + let off: Vec = CASES.iter().filter(|&&c| w(&ctx, 0, c.0) > room(&ctx, c)).map(|&c| format!("{:?} {:.1} in {:.1}", c.0, w(&ctx, 0, c.0), room(&ctx, c))).collect(); + assert!(off.is_empty(), "the case list is off (these do not fit in Fira Code): {off:?}"); + for face in SANS_START..FONT_NAMES.len() { + // the tightest case: the largest share of its room the label takes + let (fill, l) = CASES.iter().map(|&c| (w(&ctx, face, c.0) / room(&ctx, c), c.0)).fold((0.0, ""), |m, x| if x.0 > m.0 { x } else { m }); + eprintln!("UI {:<15} size x{:.3} tightest {:>5.1} % of its room ({l:?})", FONT_NAMES[face], FONT_TUNE[face].0, fill * 100.0); + if fill > 1.0 { + bad.push(format!("{} overflows on {l:?} ({:.1} %)", FONT_NAMES[face], fill * 100.0)); + } + } + for face in NUM_SANS { + let r = VALUES.iter().map(|v| w(&ctx, face, v) / w(&ctx, 0, v)).fold(0.0f32, f32::max); + eprintln!("NUM {:<15} widest value {:.3} x Fira Code", FONT_NAMES[face], r); + // (1 % of slack: short values like "+12" land on the pixel grid even at 4x, a size step below that does not move them) + if r > 1.01 { + bad.push(format!("{} values {:.3} x Fira Code", FONT_NAMES[face], r)); + } + } + assert!(bad.is_empty(), "{bad:?}"); + } +} + +#[cfg(test)] +mod font_pack_tests { + use super::*; + + #[test] + fn the_font_value_packs_both_faces_and_old_values_read_as_mono() { + // a value saved before the sans mode: one face for everything + for f in 0..SANS_START { + assert_eq!(font_unpack(f as i64), (f, f)); + assert_eq!(font_sanitize(f as i32), f); + } + // sans: UI face + numerals face + let v = font_pack(13, 7); + assert_eq!(font_unpack(v as i64), (13, 7)); + assert_eq!(font_unpack(font_pack(11, 13) as i64), (11, 13), "a tabular sans face can set the numbers"); + // a sans UI face cannot set numbers that are not tabular: back to Fira Code; nor can a missing one + assert_eq!(font_unpack((11 | ((14 + 1) << 8)) as i64), (11, 0), "DM Sans digits are proportional"); + assert_eq!(font_unpack(12), (12, 0)); + // a mono UI face ignores a numerals byte; junk is clamped + assert_eq!(font_unpack((3 | (5 << 8)) as i64), (3, 3)); + assert_eq!(font_unpack(-4), (0, 0)); + assert_eq!(font_unpack(0xff), (FONT_NAMES.len() - 1, 0)); + assert_eq!(font_pack(3, 9), 3, "the mono mode stores the UI face alone"); + assert!(num_faces().iter().all(|&f| !is_sans(f) || NUM_SANS.contains(&f))); + } + + #[test] + fn a_value_splits_into_digit_runs_and_the_rest() { + assert_eq!(digit_runs("+12.5dB"), vec![(false, "+"), (true, "12"), (false, "."), (true, "5"), (false, "dB")]); + assert_eq!(digit_runs("-----dB"), vec![(false, "-----dB")]); + assert_eq!(digit_runs("100"), vec![(true, "100")]); + assert!(digit_runs("").is_empty()); + } +} diff --git a/rust/satcomp-ui/src/help.rs b/rust/satcomp-ui/src/help.rs new file mode 100644 index 0000000..a50a355 --- /dev/null +++ b/rust/satcomp-ui/src/help.rs @@ -0,0 +1,135 @@ +//! Help overlay: with help mode on (the `?` button in the preset field), hovering a control shows a bubble with its title and +//! a short description. Widgets report what is under the pointer through `Kit::help_hit` (see `kit::Widgets::help_slot` / +//! `help_id`); each plug-in maps that key to its copy (shared entries live in `common` here) and calls `Canvas::help_bubble` +//! at the end of its frame. The copy is drafted in docs/internal/helpcopy/ (style rules in its README). + +use crate::canvas::Canvas; +use nih_plug_egui::egui::{text::LayoutJob, Align, Color32, FontFamily, FontId, Pos2, TextFormat}; + +/// What the pointer is over: a parameter slot, or a named widget (button label or an id the page gives a non-parameter area). +#[derive(Clone, Debug, PartialEq)] +pub enum HelpKey { + Slot(usize), + Id(String), +} + +/// One bubble: the title (the label as the UI prints it) and the body. Body lines are literal (`\n` = new line); long lines wrap. +#[derive(Clone, Copy, Debug)] +pub struct Help { + pub title: &'static str, + pub body: &'static str, +} + +pub const fn h(title: &'static str, body: &'static str) -> Help { + Help { title, body } +} + +/// The egui family the bubbles use (Fira Sans, registered in `init_ctx`). +pub fn help_family() -> FontFamily { + FontFamily::Name("help".into()) +} + +/// Bubble text size, line height (both in logical units), widest text line and the padding around the text. +const SIZE: f32 = 11.5; +const LINE: f32 = 15.0; +const TEXT_W: f32 = 240.0; +const PAD: f32 = 8.0; + +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) +} + +impl Canvas<'_> { + /// Draw the help bubble for `help` next to the pointer at (`mx`, `my`) (logical units) on a `cw` x `ch` canvas: below right + /// of the pointer, flipped to the other side where it would leave the window. Background colour plate, UI-colour border and + /// text, never dimmed. + pub fn help_bubble(&self, mx: f32, my: f32, help: &Help, cw: f32, ch: f32) { + #[allow(non_snake_case)] + let (W, H) = (cw, ch); + let (fg, bk) = (rgb(self.fg), rgb(self.bk)); + let text = format!("{}\n------\n{}", help.title, help.body); + let text_w = TEXT_W.min(W - 8.0 - 2.0 * PAD); + let mut job = LayoutJob::simple(text, FontId::new(SIZE * self.s, help_family()), fg, text_w * self.s); + job.halign = Align::LEFT; + for sec in job.sections.iter_mut() { + sec.format = TextFormat { line_height: Some(LINE * self.s), ..sec.format.clone() }; + } + let galley = self.p.layout_job(job); + let (tw, th) = (galley.size().x / self.s, galley.size().y / self.s); + let (bw, bh) = ((tw + 2.0 * PAD).ceil(), (th + 2.0 * PAD).ceil()); + let mut x = mx + 12.0; + if x + bw > W - 4.0 { + x = mx - 12.0 - bw; + } + let mut y = my + 16.0; + if y + bh > H - 4.0 { + y = my - 8.0 - bh; + } + let (x, y) = (x.clamp(4.0, (W - 4.0 - bw).max(4.0)).floor(), y.clamp(4.0, (H - 4.0 - bh).max(4.0)).floor()); + let mut c = Canvas { p: self.p, ppp: self.ppp, ox: self.ox, oy: self.oy, s: self.s, bk: self.bk, fg: self.fg, ac: self.ac, dk: 1.0, col: bk, font: self.font, face: self.face, num_face: self.num_face }; + c.fill(x, y, bw, bh); + c.col = fg; + c.boxr(x, y, bw, bh); + let snap = |v: f32| (v * self.ppp).round() / self.ppp; + self.p.galley(Pos2::new(snap(self.ox + (x + PAD) * self.s), snap(self.oy + (y + PAD - 1.0) * self.s)), galley, fg); + } +} + +/// Copy shared by the family (docs/internal/helpcopy/common.md). A plug-in uses these where its control matches. +pub mod common { + use super::{h, Help}; + + pub const HELP: Help = h("HELP", "Toggles the help overlay. While it is on, hovering over any control shows a tooltip about it."); + pub const COLOR_SWITCHER: Help = h( + "COLOR SWITCHER", + "[Click] Cycles through the plugin's color schemes\n[Right-click] Shows the color scheme list\n[Double-click] Switches between dark and light mode\n[Shift+Click] Randomizes the color scheme and UI font. To keep a random scheme, create a [NEW THEME] from [RANDOM] in [PREFERENCES].", + ); + pub const TITLE: Help = h("ABOUT", "Opens the About page: a quick guide, preferences (colors, fonts, display) and the changelog.\n[Click] Opens / closes the About page"); + pub const UI_SCALE: Help = h("UI SCALE", "Sets the plugin UI scale.\n[Click] Shows the size list\n[Drag bottom-right corner] Resizes the window"); + pub const BYPASS: Help = h("BYPASS", "Bypasses the plugin processing. The original signal stays latency-compensated, so A/B comparisons line up."); + pub const DELTA: Help = h("DELTA", "Allows listening to the difference between the original and the processed signal. Turn it off before rendering."); + + pub const SAVE: Help = h("SAVE PRESET", "Saves the current settings as a user preset."); + pub const PRESET: Help = h("PRESET", "Shows the preset in use.\n[Click] Browses factory and user presets, or loads one from a file"); + pub const PREV_NEXT: Help = h("PREV / NEXT", "Steps to the previous or next preset in the list."); + + pub const SHAPE: Help = h( + "SHAPE", + "Selects the saturation curve, which sets its character.\nSmooth and warm: [Tube], [Soft], [Rational], [Atan].\nHarder and more destructive: [Hard], [Tri Fold], [Sine Fold], [Asym Fold], [Wrap], [Rectify], [Bitcrush].\n[Custom] is a user-drawn curve.\n[Click] Shows the shaper list\n[Click arrows] Steps through the shapers", + ); + pub const TRANSFER: Help = h( + "TRANSFER PLOT", + "Shows the saturation curve as heard, with the live input moving along it. The flatter the curve where the signal reaches, the harder it is being squashed.\n[Click SAT value] Matches the level to where it was before the saturator", + ); + pub const DRAW: Help = h( + "DRAW", + "Draws a custom saturation curve.\n[FREE] (pencil) draws freely.\n[ODD] mirrors the curve through the center: a symmetric shape with odd harmonics.\n[EVEN] mirrors it left to right: a rectifier-like shape with even harmonics.\n[Click] Adds a point\n[Drag] Moves a point\n[Double-click] Removes a point", + ); + pub const DRIVE: Help = h("DRIVE", "Sets how hard the signal is pushed into the saturation. Low settings add warmth, high settings add grit and distortion."); + pub const BIAS: Help = h("BIAS", "Pushes the signal off-center so one side of the wave saturates harder than the other. This adds a warmer, thicker color, like an overdriven tube."); + pub const ASYM: Help = h("ASYM", "Sets how much of the lopsided (even) color from [BIAS] is kept. 100% keeps all of it; lower it to clean that color out and make the saturation symmetric again."); + pub const SAT_HP_LP: Help = h("HP / LP", "Filters the input before the saturation stage. Raise [HP] to keep the low end clean, lower [LP] to keep the top end from getting harsh."); + pub const TONE: Help = h("TONE", "Softens the top end after the saturator. Turn it down if the distortion sounds fizzy or harsh."); + pub const SAT_MIX: Help = h("SAT MIX", "Blends the saturated signal with the clean one. Lower it to add color while keeping the original punch."); + pub const SAT_GAIN: Help = h("SAT GAIN", "Sets the level after the saturator.\n[Click SAT value] Matches it automatically (on the plot)"); + pub const OVERSAMPLING: Help = h("OVERSAMPLING", "Runs the processing at a higher rate so heavy distortion sounds cleaner in the top end, with fewer harsh, metallic artifacts. Higher settings use more CPU."); + + pub const SCOPE_ICON: Help = h("SCOPE", "Switches the display to a scrolling waveform scope (transient view)."); + pub const SCOPE_VIEW: Help = h( + "SCOPE", + "Shows the output waveform, with gain reduction drawn on top in the accent color and gain lift in the inverted accent color.\n[Drag up/down] Zooms in or out ([CEIL])\n[Drag left/right] Sets the time window ([WIN])", + ); + pub const SRC: Help = h("SRC", "Selects what the scope shows: [OUT+GR] the output with the gain reduction or lift on top, [OUT] the output alone, [GR] only the gain reduction or lift.\n[Click] Cycles the sources"); + pub const WAVE: Help = h("WAVE", "[HALF] folds the wave so only its height shows, which makes peaks easy to read. [FULL] shows the whole wave, top and bottom."); + pub const WIN: Help = h("WIN", "Sets how much time the scope shows across its width. Short for single hits, long for whole phrases."); + pub const CEIL: Help = h("CEIL", "Zooms the scope in or out: the level at the top of the view. Lower it to inspect peaks on quiet material."); + + pub const LIM: Help = h("LIM", "Enables a safety limiter on the output that catches stray peaks before they clip. The [LIM] readout shows its gain reduction."); + pub const OUT_METER: Help = h("OUTPUT METER", "Shows the output level, left and right."); + pub const READOUTS: Help = h("LIM / PK / RMS", "[LIM] shows the output limiter's gain reduction. [PK] shows the loudest peak and lights up above 0 dB. [RMS] shows the average level, closer to how loud it feels."); + pub const GAIN_MATCH: Help = h( + "GAIN MATCH", + "Evens out the output level to match the input level. The readout above shows [MEAS] while listening, [LOCK] once the trim is set, [TRIM] while off.\n[Click] Listens for 3 seconds while the audio plays, then sets a level trim and locks it\n[Click while locked] Turns it off", + ); + pub const IN_OUT: Help = h("IN>OUT", "Shows how much louder or quieter the output is than the input."); +} diff --git a/rust/satcomp-ui/src/kit.rs b/rust/satcomp-ui/src/kit.rs index 9653536..36086f6 100644 --- a/rust/satcomp-ui/src/kit.rs +++ b/rust/satcomp-ui/src/kit.rs @@ -6,6 +6,7 @@ //! `Kit` (so widget code and page code both read `self.mx`, `self.press`, ...). use crate::canvas::Canvas; +use crate::help::{Help, HelpKey}; use nih_plug::prelude::{GuiContext, ParamPtr}; /// Bipolar-log taper: `|v|` in 0..max -> 0..1, fine near zero (the knee sits at 1 % of max), coarse towards the ends. @@ -61,6 +62,13 @@ pub struct Kit { pub now: f64, /// 1 = normal, 0.5 = dimmed (modules dimmed while bypassed) pub dk: f32, + /// help mode (the `?` button): widgets report what is under the pointer in `help_hit` + pub help_on: bool, + /// per slot: the live modulated value (NaN = not modulated). A modulated cell draws its value bar in the accent colour with + /// a UI-colour mark at the live value (SatFilt's modulators; the other plug-ins never set it) + pub modv: Vec, + /// the help target under the pointer this frame (cleared by `set_input`; the last widget drawn there wins) + pub help_hit: Option, } /// how long a written value is shown in place of the parameter (the host answers within a few blocks; this covers PulseAudio's @@ -106,6 +114,9 @@ impl Kit { shift: false, now: 0.0, dk: 1.0, + help_on: false, + help_hit: None, + modv: vec![f32::NAN; slots], } } @@ -121,6 +132,7 @@ impl Kit { self.rpress = rdown && !self.last_rdown; self.last_rdown = rdown; self.shift = shift; + self.help_hit = None; let restarted = now < self.now; if restarted { self.last_clk_t = now; @@ -262,6 +274,41 @@ pub trait Widgets<'c> { k.mx >= x && k.mx < x + w && k.my >= y && k.my < y + h } + /// Help mode: report parameter slot `n` as the help target when the pointer is over (x, y, w, h). + fn help_slot(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32) { + if self.kit_ref().help_on && self.hit(x, y, w, h) { + self.kit().help_hit = Some(HelpKey::Slot(n)); + } + } + + /// Help mode: report the named widget `id` (a button label, or an id the page gives an area) when the pointer is over it. + fn help_id(&mut self, id: &str, x: f32, y: f32, w: f32, h: f32) { + if self.kit_ref().help_on && !id.is_empty() && self.hit(x, y, w, h) { + self.kit().help_hit = Some(HelpKey::Id(id.to_string())); + } + } + + /// The help mode toggle (`?` in the preset field): lit while help is on. + fn help_btn(&mut self, x: f32, y: f32, s: f32) { + let on = self.kit_ref().help_on; + if self.btn(x, y, s, s, "?", on as u8) { + self.kit().help_on = !on; + } + } + + /// End of frame: the bubble for whatever the pointer is over (`copy` maps the target to its text) on a `cw` x `ch` canvas, + /// while help mode is on and nothing else owns the pointer (`busy`: an open menu, a resize, the theme editor; a drag counts + /// on its own). + fn help_overlay(&mut self, busy: bool, cw: f32, ch: f32, copy: fn(&HelpKey) -> Option) { + let k = self.kit_ref(); + if !k.help_on || busy || k.act != 0 { + return; + } + let Some(help) = k.help_hit.as_ref().and_then(copy) else { return }; + let (mx, my) = (k.mx, k.my); + self.cv().help_bubble(mx, my, &help, cw, ch); + } + 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; @@ -324,6 +371,7 @@ pub trait Widgets<'c> { // ------------------------------------------------------------------ widgets fn cell(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str) { + self.help_slot(n, x, y, w, h); let hv = self.hit(x, y, w, h); if hv && self.kit().press && self.kit().act == 0 { self.begin_drag(n); @@ -341,12 +389,30 @@ pub trait Widgets<'c> { 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); + cv.textc_n(x, y + (h * 0.4 + 1.0).floor(), w, &s); + self.value_bar(n, x + 2.0, y + h - 4.0, w - 4.0, 2.0, t, isact); + } + + /// A cell's value bar: the plain fill, or, while the slot is modulated (`Kit::modv`), the fill in the accent colour and a + /// UI-colour mark at the live value. + fn value_bar(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, t: f32, isact: bool) { + let mv = self.kit_ref().modv.get(n).copied().unwrap_or(f32::NAN); + if mv.is_nan() { + self.cv().fill(x, y, ((t * w).floor()).max(1.0), h); + return; + } + let tm = self.n2t(n, mv); + self.setc(true); + self.cv().fill(x, y, ((t * w).floor()).max(1.0), h); + self.setc(false); + let mx = x + (tm * (w - 2.0)).floor(); + self.cv().fill(mx, y - 2.0, 2.0, h + 3.0); + self.setc(isact); } /// 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) { + self.help_slot(n, x, y, w, h); let hv = self.hit(x, y, w, h); if hv && self.kit().press && self.kit().act == 0 { self.begin_drag(n); @@ -366,7 +432,7 @@ pub trait Widgets<'c> { 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.textc_n(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); @@ -374,6 +440,7 @@ pub trait Widgets<'c> { /// 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) { + self.help_slot(n, x, y, w, h); let hv = self.hit(x, y, w, h); if hv && self.kit().press && self.kit().act == 0 { self.begin_drag(n); @@ -391,14 +458,16 @@ pub trait Widgets<'c> { 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); + cv.textr_n(x, ty, w - 3.0, &s); + self.value_bar(n, x + 2.0, y + h - 3.0, w - 4.0, 1.0, t, isact); 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(); + self.help_slot(na, x, y, w, hh); + self.help_slot(nb, x, y + hh, w, h - hh); 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 { @@ -426,7 +495,7 @@ pub trait Widgets<'c> { { let cv = self.cv(); cv.text(x + 3.0, y + 3.0, la); - cv.textr(x, y + 3.0, w - 3.0, &s); + cv.textr_n(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); @@ -436,24 +505,34 @@ pub trait Widgets<'c> { { 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.textr_n(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 + /// lit: 0 off, 1 white, 2 red. A lit button is a toggle: under the pointer it swaps colour (the click turns it off). fn btn(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8) -> bool { + self.btn_x(x, y, w, h, s, lit, true) + } + + /// A button of a choice group (tabs, mode buttons): lit = the current choice, so clicking it again changes nothing and the + /// hover does not recolour it. The others fill under the pointer like any button. + fn btn_sel(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8) -> bool { + self.btn_x(x, y, w, h, s, lit, false) + } + + /// `toggle`: whether a click on a lit button does something (then the hover shows it). + fn btn_x(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8, toggle: bool) -> bool { + self.help_id(s, x, y, w, h); let hv = self.hit(x, y, w, h); let clicked = hv && self.kit().press && self.kit().act == 0; - // hovering fills the button (a lit one gets an inner outline instead, so it still reads as on) if lit > 0 || hv { - self.setc(lit > 1); + // an off button fills with the UI colour under the pointer; a lit toggle is already that colour, so under the pointer + // it swaps to the accent (and a red one to the UI colour): the hover only shows where a click would do something + self.setc((lit > 1) != (toggle && lit > 0 && hv)); self.cv().fill(x, y, w, h); self.cv().setbg(); - if lit > 0 && hv { - self.cv().boxr(x + 1.0, y + 1.0, w - 2.0, h - 2.0); - } } else { self.setc(false); self.cv().boxr(x, y, w, h); diff --git a/rust/satcomp-ui/src/lib.rs b/rust/satcomp-ui/src/lib.rs index 6bb9317..bcc47ee 100644 --- a/rust/satcomp-ui/src/lib.rs +++ b/rust/satcomp-ui/src/lib.rs @@ -1,8 +1,11 @@ //! Shared egui UI toolkit for the SatComp plug-in family. pub mod appearance; +pub mod bench; +pub mod randtheme; pub mod canvas; pub mod fft; +pub mod help; pub mod kit; pub mod logo_art; pub mod meter; @@ -16,7 +19,7 @@ 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] = [ + let faces: [&'static [u8]; 18] = [ include_bytes!("../assets/fonts/FiraCode-Regular.ttf"), include_bytes!("../assets/fonts/JetBrainsMono-Regular.ttf"), include_bytes!("../assets/fonts/GeistMono-Regular.ttf"), @@ -28,11 +31,25 @@ pub fn init_ctx(ctx: &egui::Context) { include_bytes!("../assets/fonts/AnonymousPro-Regular.ttf"), include_bytes!("../assets/fonts/Inconsolata-Regular.ttf"), include_bytes!("../assets/fonts/CourierPrime-Regular.ttf"), + include_bytes!("../assets/fonts/HankenGrotesk-Regular.ttf"), + include_bytes!("../assets/fonts/Overpass-Regular.ttf"), + include_bytes!("../assets/fonts/Questrial-Regular.ttf"), + include_bytes!("../assets/fonts/DMSans-Regular.ttf"), + include_bytes!("../assets/fonts/Figtree-Regular.ttf"), + include_bytes!("../assets/fonts/Lexend-Regular.ttf"), + include_bytes!("../assets/fonts/FiraSans-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}")]); } + // help bubbles are always set in Fira Sans, whatever the UI font (owner's call: a proportional face reads easier in prose) + // (the same data as the Fira Sans UI face, f17: embedded once) + fonts.families.insert(help::help_family(), vec![format!("f{}", canvas::FONT_NAMES.len() - 1)]); + // egui's own default fonts are not built in (they were 1.4 MB per binary and nothing drew with them): its two built-in + // families point at ours, in case anything inside egui lays out text with them + fonts.families.insert(egui::FontFamily::Proportional, vec![format!("f{}", canvas::FONT_NAMES.len() - 1)]); + fonts.families.insert(egui::FontFamily::Monospace, vec!["f0".to_string()]); 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/logo_art.rs b/rust/satcomp-ui/src/logo_art.rs index 2d6188e..6c75e2c 100644 --- a/rust/satcomp-ui/src/logo_art.rs +++ b/rust/satcomp-ui/src/logo_art.rs @@ -52,3 +52,25 @@ pub const LOGO_DIFF: [[f32; 8]; 6] = [ [11.3306, 19.73, 5.0303, 26.0303, 3.9697, 24.9697, 10.27, 18.6694], [26.0303, 5.0303, 19.73, 11.3306, 18.6694, 10.27, 24.9697, 3.9697], ]; + +pub const LOGO_EQ: [[f32; 8]; 8] = [ + [4.7071, 3.2929, 3.2929, 4.7071, 9.2929, 10.7071, 10.7071, 9.2929], + [25.2929, 26.7071, 26.7071, 25.2929, 20.7071, 19.2929, 19.2929, 20.7071], + [9.0, 9.0, 21.0, 9.0, 21.0, 11.0, 9.0, 11.0], + [9.0, 19.0, 21.0, 19.0, 21.0, 21.0, 9.0, 21.0], + [9.0, 9.0, 11.0, 9.0, 11.0, 21.0, 9.0, 21.0], + [19.0, 9.0, 21.0, 9.0, 21.0, 21.0, 19.0, 21.0], + [25.0, 18.0, 27.0, 18.0, 27.0, 27.0, 25.0, 27.0], + [18.0, 25.0, 27.0, 25.0, 27.0, 27.0, 18.0, 27.0], +]; + +pub const LOGO_FILT: [[f32; 8]; 8] = [ + [3.2929, 25.2929, 4.7071, 26.7071, 10.7071, 20.7071, 9.2929, 19.2929], + [25.2929, 26.7071, 26.7071, 25.2929, 20.7071, 19.2929, 19.2929, 20.7071], + [9.0, 9.0, 21.0, 9.0, 21.0, 11.0, 9.0, 11.0], + [9.0, 19.0, 21.0, 19.0, 21.0, 21.0, 9.0, 21.0], + [9.0, 9.0, 11.0, 9.0, 11.0, 21.0, 9.0, 21.0], + [19.0, 9.0, 21.0, 9.0, 21.0, 21.0, 19.0, 21.0], + [25.0, 18.0, 27.0, 18.0, 27.0, 27.0, 25.0, 27.0], + [18.0, 25.0, 27.0, 25.0, 27.0, 27.0, 18.0, 27.0], +]; diff --git a/rust/satcomp-ui/src/randtheme.rs b/rust/satcomp-ui/src/randtheme.rs new file mode 100644 index 0000000..9d23a05 --- /dev/null +++ b/rust/satcomp-ui/src/randtheme.rs @@ -0,0 +1,220 @@ +//! The dice's random colour scheme: background, UI and accent for dark and light mode, picked in OKLCH (perceptual lightness, +//! chroma, hue) and re-rolled until every legibility check passes: +//! * UI on background: WCAG contrast >= `MIN_UI` (text and outlines everywhere); +//! * accent on background: >= `MIN_ACC` (red readouts, lit hover states); +//! * accent against UI (after the hues are known): a perceptual distance of at least `MIN_SEP` in OKLab, and when both carry +//! colour, hues at least `MIN_HUE` degrees apart, so a bright green UI never meets a bright cyan accent. +//! Both modes share the three hues; light mode swaps the lightness roles (light background, dark UI, a deeper accent). + +/// WCAG contrast of the UI colour on the background. +pub const MIN_UI: f32 = 7.0; +/// WCAG contrast of the accent on the background. +pub const MIN_ACC: f32 = 4.5; +/// OKLab distance between UI and accent. +pub const MIN_SEP: f32 = 0.2; +/// Hue gap (degrees) between UI and accent when both are chromatic. +pub const MIN_HUE: f32 = 60.0; +/// Share of rolls drawn from the vivid chroma ranges. +const VIVID: f32 = 0.4; +/// Chroma above which a colour counts as chromatic for the hue gap. +const CHROMATIC: f32 = 0.05; + +/// A tiny deterministic generator (xorshift64*), so a seed always gives the same scheme (tests) and the dice feeds it the clock. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> f32 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + ((self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 40) as f32) / (1u64 << 24) as f32 + } + fn range(&mut self, lo: f32, hi: f32) -> f32 { + lo + (hi - lo) * self.next() + } +} + +fn srgb_encode(c: f32) -> f32 { + if c <= 0.003_130_8 { + 12.92 * c + } else { + 1.055 * c.powf(1.0 / 2.4) - 0.055 + } +} + +fn srgb_decode(c: f32) -> f32 { + if c <= 0.040_45 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } +} + +/// OKLCH (L 0..1, C, hue degrees) to sRGB 0..1, with the chroma reduced until the colour fits the sRGB gamut. +pub fn oklch_to_srgb(l: f32, c: f32, h_deg: f32) -> [f32; 3] { + let h = h_deg.to_radians(); + let mut c = c; + for _ in 0..24 { + let (a, b) = (c * h.cos(), c * h.sin()); + let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b; + let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b; + let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b; + let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_); + let r = 4.076_741_7 * l3 - 3.307_711_6 * m3 + 0.230_969_94 * s3; + let g = -1.268_438 * l3 + 2.609_757_4 * m3 - 0.341_319_38 * s3; + let bl = -0.004_196_086_3 * l3 - 0.703_418_6 * m3 + 1.707_614_7 * s3; + if (-1e-4..=1.0001).contains(&r) && (-1e-4..=1.0001).contains(&g) && (-1e-4..=1.0001).contains(&bl) { + return [srgb_encode(r.clamp(0.0, 1.0)), srgb_encode(g.clamp(0.0, 1.0)), srgb_encode(bl.clamp(0.0, 1.0))]; + } + c *= 0.85; + } + let v = srgb_encode(l.clamp(0.0, 1.0).powi(3)); + [v, v, v] +} + +/// sRGB 0..1 to OKLab (L, a, b). +pub fn srgb_to_oklab(c: [f32; 3]) -> [f32; 3] { + let (r, g, b) = (srgb_decode(c[0]), srgb_decode(c[1]), srgb_decode(c[2])); + let l = (0.412_221_47 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt(); + let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt(); + let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt(); + [ + 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, + 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, + 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, + ] +} + +/// WCAG relative luminance. +fn lum(c: [f32; 3]) -> f32 { + 0.2126 * srgb_decode(c[0]) + 0.7152 * srgb_decode(c[1]) + 0.0722 * srgb_decode(c[2]) +} + +/// WCAG contrast ratio (1..21). +pub fn contrast(a: [f32; 3], b: [f32; 3]) -> f32 { + let (x, y) = (lum(a), lum(b)); + (x.max(y) + 0.05) / (x.min(y) + 0.05) +} + +/// Chroma and hue (degrees) of an sRGB colour. +fn chroma_hue(c: [f32; 3]) -> (f32, f32) { + let o = srgb_to_oklab(c); + ((o[1] * o[1] + o[2] * o[2]).sqrt(), o[2].atan2(o[1]).to_degrees().rem_euclid(360.0)) +} + +fn hue_gap(a: f32, b: f32) -> f32 { + let d = (a - b).rem_euclid(360.0); + d.min(360.0 - d) +} + +/// Whether a (background, UI, accent) triple passes every legibility check. +pub fn legible(bg: [f32; 3], ui: [f32; 3], acc: [f32; 3]) -> bool { + if contrast(ui, bg) < MIN_UI || contrast(acc, bg) < MIN_ACC { + return false; + } + let (ou, oa) = (srgb_to_oklab(ui), srgb_to_oklab(acc)); + let sep = ((ou[0] - oa[0]).powi(2) + (ou[1] - oa[1]).powi(2) + (ou[2] - oa[2]).powi(2)).sqrt(); + if sep < MIN_SEP { + return false; + } + let ((cu, hu), (ca, ha)) = (chroma_hue(ui), chroma_hue(acc)); + !(cu > CHROMATIC && ca > CHROMATIC && hue_gap(hu, ha) < MIN_HUE) +} + +fn flat(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 9] { + [a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]] +} + +/// A random scheme from `seed`: (dark, light), each [bg, ui, accent] as 9 floats. Every candidate goes through `legible` in +/// both modes; after 400 misses (practically never) it falls back to a fixed safe scheme. +pub fn random_scheme(seed: u64) -> ([f32; 9], [f32; 9]) { + let mut r = Rng(seed | 1); + // two moods, chosen once per roll (the retries stay in it, so the stricter vivid candidates are not crowded out): about + // 40 % vivid (saturated background, UI and accent, the UI a little less light so it can hold colour; sRGB caps what it + // can show), the rest pastel / midrange. The legibility checks are the same for both. + let vivid = r.next() < VIVID; + for _ in 0..400 { + let (hb, hu, ha) = (r.range(0.0, 360.0), r.range(0.0, 360.0), r.range(0.0, 360.0)); + let (cb, cu, ca) = if vivid { + (r.range(0.06, 0.14), r.range(0.12, 0.30), r.range(0.20, 0.37)) + } else { + (r.range(0.0, 0.07), r.range(0.0, 0.14), r.range(0.12, 0.26)) + }; + // lightness: vivid rolls sit where sRGB holds the most chroma (a less dark background, a less light UI, a deeper accent) + let (bg_l, ui_l, acc_l) = if vivid { (r.range(0.17, 0.31), r.range(0.76, 0.90), r.range(0.58, 0.76)) } else { (r.range(0.13, 0.30), r.range(0.82, 0.97), r.range(0.64, 0.82)) }; + // dark: a dark background, a light UI colour, a mid-light saturated accent + let d = (oklch_to_srgb(bg_l, cb, hb), oklch_to_srgb(ui_l, cu, hu), oklch_to_srgb(acc_l, ca, ha)); + // light: the same hues with the lightness roles swapped + let l = (oklch_to_srgb(r.range(0.90, 0.98), cb * 0.6, hb), oklch_to_srgb(r.range(0.18, 0.36), cu, hu), oklch_to_srgb(r.range(0.42, 0.58), ca, ha)); + if legible(d.0, d.1, d.2) && legible(l.0, l.1, l.2) { + return (flat(d.0, d.1, d.2), flat(l.0, l.1, l.2)); + } + } + ([0.08, 0.08, 0.1, 0.92, 0.92, 0.95, 1.0, 0.45, 0.2], [0.95, 0.95, 0.93, 0.12, 0.12, 0.15, 0.75, 0.25, 0.05]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tri(a: &[f32; 9]) -> ([f32; 3], [f32; 3], [f32; 3]) { + ([a[0], a[1], a[2]], [a[3], a[4], a[5]], [a[6], a[7], a[8]]) + } + + #[test] + fn every_roll_passes_the_checks_in_both_modes_and_is_in_range() { + let mut misses = 0; + for seed in 0..2000u64 { + let (d, l) = random_scheme(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + for m in [&d, &l] { + assert!(m.iter().all(|v| (0.0..=1.0).contains(v)), "seed {seed}: {m:?}"); + let (bg, ui, acc) = tri(m); + assert!(legible(bg, ui, acc), "seed {seed}: {m:?}"); + } + // the fallback is a fixed scheme: count how often it is hit + if d[0] == 0.08 && d[6] == 1.0 { + misses += 1; + } + } + assert!(misses < 5, "{misses} rolls fell back to the fixed scheme"); + } + + #[test] + fn a_good_share_of_rolls_is_vivid() { + // chroma of the dark-mode UI and accent: vivid rolls reach well past the pastel ranges + let chroma = |c: [f32; 3]| { + let o = srgb_to_oklab(c); + (o[1] * o[1] + o[2] * o[2]).sqrt() + }; + let vivid = (0..500u64) + .filter(|s| { + let (d, _) = random_scheme(s.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0x55); + // past the pastel ranges on at least one swatch (sRGB and the contrast checks cap how far a light UI colour goes) + chroma([d[0], d[1], d[2]]) > 0.07 || chroma([d[3], d[4], d[5]]) > 0.14 || chroma([d[6], d[7], d[8]]) > 0.2 + }) + .count(); + assert!(vivid > 125, "only {vivid} of 500 rolls are vivid"); + } + + #[test] + fn rolls_differ_and_a_seed_repeats() { + let a = random_scheme(11); + assert_eq!(a, random_scheme(11)); + let distinct: std::collections::HashSet = (0..50u64).map(|s| format!("{:?}", random_scheme(s * 7919 + 3).0)).collect(); + assert!(distinct.len() > 45, "{}", distinct.len()); + } + + #[test] + fn the_checks_reject_the_combinations_they_are_for() { + let black = [0.0, 0.0, 0.0]; + // bright green UI with a bright cyan accent: enough contrast on black, too close in hue + assert!(!legible(black, [0.3, 1.0, 0.3], [0.2, 1.0, 1.0])); + // dark grey UI on black: no contrast + assert!(!legible(black, [0.25, 0.25, 0.25], [1.0, 0.3, 0.1])); + // white UI, orange accent on near black: fine + assert!(legible([0.06, 0.06, 0.07], [0.95, 0.95, 0.95], [1.0, 0.5, 0.1])); + // gamut mapping keeps sRGB in range for a wild chroma + let c = oklch_to_srgb(0.7, 0.5, 145.0); + assert!(c.iter().all(|v| (0.0..=1.0).contains(v))); + } +} diff --git a/rust/satcomp-ui/src/spectrum.rs b/rust/satcomp-ui/src/spectrum.rs index e8aebe7..f18247d 100644 --- a/rust/satcomp-ui/src/spectrum.rs +++ b/rust/satcomp-ui/src/spectrum.rs @@ -8,8 +8,22 @@ pub struct Spectrum { /// smoothed magnitude per bin in dB (2049 bins) pub db: Vec, t: f64, + /// averaging speed (see the `SPEED_*` constants) + pub speed: u8, + /// what `columns` reads: `db` eased toward its latest analysis every frame, so the slow views glide instead of stepping + shown: Vec, + tick: f64, } +/// Master view: very slow, power-averaged, smoothed across a third of an octave (for judging the balance of a whole mix). +pub const SPEED_RMS: u8 = 0; +/// Slower refresh and fall than the default. +pub const SPEED_SLOW: u8 = 1; +/// The default. +pub const SPEED_MED: u8 = 2; +/// Quick fall, follows transients instead of averaging them. +pub const SPEED_FAST: u8 = 3; + impl Default for Spectrum { fn default() -> Self { Self::new() @@ -21,17 +35,45 @@ impl Spectrum { 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 } + Self { win, db: vec![-140.0; Self::N / 2 + 1], t: 0.0, speed: SPEED_MED, shown: vec![-140.0; Self::N / 2 + 1], tick: 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; + self.tick = now; } - /// Analyse at most every 30 ms. `head` = write position of the tap ring, `get(i)` reads sample `i` of it. + /// (minimum seconds between analyses, rise, fall) of the smoothing, per analysis, for the current speed. + fn timing(&self) -> (f64, f32, f32) { + match self.speed { + SPEED_RMS => (0.1, 0.06, 0.03), + SPEED_SLOW => (0.06, 0.3, 0.05), + SPEED_FAST => (0.03, 0.6, 0.5), + _ => (0.03, 0.6, 0.12), + } + } + + /// Analyse at most every 30 ms (slower views less often). `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 { + self.analyse(now, head, get); + // glide: the slow views analyse a few times a second, the picture follows every frame + let tau = match self.speed { + SPEED_RMS => 0.07, + SPEED_SLOW => 0.04, + _ => 0.0, + }; + let dt = (now - self.tick).clamp(0.0, 0.25); + self.tick = now; + let a = if tau > 0.0 { 1.0 - (-dt / tau).exp() as f32 } else { 1.0 }; + for (s, d) in self.shown.iter_mut().zip(&self.db) { + *s += (*d - *s) * a; + } + } + + fn analyse(&mut self, now: f64, head: usize, get: impl Fn(usize) -> f32) { + let (period, rise, fall) = self.timing(); + if now - self.t < period { return; } self.t = now; @@ -45,12 +87,33 @@ impl Spectrum { 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 }; + *sp += (db - *sp) * if db > *sp { rise } else { fall }; } } - /// Level in dB (tilt-compensated) for `n` log-spaced columns from 20 Hz to 20 kHz. + /// Level in dB (tilt-compensated) for `n` log-spaced columns from 20 Hz to 20 kHz. The RMS speed averages the power over a + /// third of an octave around each column, so the picture is a smooth tonal balance instead of single partials. pub fn columns(&self, n: usize, sample_rate: f32) -> Vec { + let c = self.columns_raw(n, sample_rate); + if self.speed != SPEED_RMS || n < 8 { + return c; + } + // 1/3 octave = n / 29.9 columns wide; a prefix sum of the power makes the box average cheap + let half = ((n as f32 / 29.9) * 0.5).round().max(1.0) as usize; + let mut pre = Vec::with_capacity(n + 1); + pre.push(0.0f64); + for v in &c { + pre.push(pre[pre.len() - 1] + 10f64.powf(*v as f64 * 0.1)); + } + (0..n) + .map(|i| { + let (a, b) = (i.saturating_sub(half), (i + half + 1).min(n)); + (10.0 * ((pre[b] - pre[a]) / (b - a) as f64).max(1e-14).log10()) as f32 + }) + .collect() + } + + fn columns_raw(&self, n: usize, sample_rate: f32) -> Vec { let bw = sample_rate / Self::N as f32; let top = (Self::N / 2) as f32; (0..n) @@ -63,13 +126,13 @@ impl Spectrum { 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; + v = self.shown[k] + (self.shown[k + 1] - self.shown[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]); + v = v.max(self.shown[k]); k += 1; cnt += 1; } @@ -108,6 +171,37 @@ mod tests { assert!((peak as i32 - expect).abs() <= 3, "{peak} vs {expect}"); } + #[test] + fn the_rms_speed_smooths_a_partial_over_a_third_of_an_octave_and_falls_slower_than_fast() { + let sr = 48000.0f32; + let sig: Vec = (0..8192).map(|i| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / sr).sin()).collect(); + let run = |speed: u8| { + let mut sp = Spectrum::new(); + sp.speed = speed; + for k in 0..80 { + sp.update(1.0 + k as f64 * 0.12, 8192, |i| sig[i % 8192]); + } + sp + }; + let (med, rms) = (run(SPEED_MED).columns(400, sr), run(SPEED_RMS).columns(400, sr)); + let width = |c: &[f32]| { + let pk = c.iter().cloned().fold(-999.0f32, f32::max); + c.iter().filter(|&&v| v > pk - 6.0).count() + }; + assert!(width(&rms) > width(&med), "{} vs {}", width(&rms), width(&med)); + // after the signal stops, FAST has fallen further than SLOW in the same time + let drop = |speed: u8| { + let mut sp = run(SPEED_MED); + let before = sp.db[85]; + sp.speed = speed; + for k in 0..10 { + sp.update(20.0 + k as f64 * 0.12, 8192, |_| 0.0); + } + before - sp.db[85] + }; + assert!(drop(SPEED_FAST) > drop(SPEED_SLOW)); + } + #[test] fn axis_mapping_round_trips() { for f in [20.0, 100.0, 1000.0, 20000.0] { diff --git a/rust/satdiff-dsp/Cargo.toml b/rust/satdiff-dsp/Cargo.toml index c1f57e2..c81d837 100644 --- a/rust/satdiff-dsp/Cargo.toml +++ b/rust/satdiff-dsp/Cargo.toml @@ -1,8 +1,12 @@ [package] name = "satdiff-dsp" -version = "0.1.0" +version = "0.1.1" edition = "2021" publish = false [dependencies] satcomp-dsp = { path = "../satcomp-dsp" } +# the preset format (preset.rs), shared with the plug-in and the CLI +serde = { version = "1", features = ["derive"] } +serde_json = "1" +include_dir = "0.7" diff --git a/rust/satdiff-plugin/presets/Amen_Hell.json b/rust/satdiff-dsp/presets/Amen_Hell.json similarity index 100% rename from rust/satdiff-plugin/presets/Amen_Hell.json rename to rust/satdiff-dsp/presets/Amen_Hell.json diff --git a/rust/satdiff-plugin/presets/Bump_Me_Up.json b/rust/satdiff-dsp/presets/Bump_Me_Up.json similarity index 100% rename from rust/satdiff-plugin/presets/Bump_Me_Up.json rename to rust/satdiff-dsp/presets/Bump_Me_Up.json diff --git a/rust/satdiff-plugin/presets/Burnt_Popcorn.json b/rust/satdiff-dsp/presets/Burnt_Popcorn.json similarity index 100% rename from rust/satdiff-plugin/presets/Burnt_Popcorn.json rename to rust/satdiff-dsp/presets/Burnt_Popcorn.json diff --git a/rust/satdiff-plugin/presets/README.md b/rust/satdiff-dsp/presets/README.md similarity index 100% rename from rust/satdiff-plugin/presets/README.md rename to rust/satdiff-dsp/presets/README.md diff --git a/rust/satdiff-plugin/presets/Shrooms.json b/rust/satdiff-dsp/presets/Shrooms.json similarity index 85% rename from rust/satdiff-plugin/presets/Shrooms.json rename to rust/satdiff-dsp/presets/Shrooms.json index 3a146e8..0ffc947 100644 --- a/rust/satdiff-plugin/presets/Shrooms.json +++ b/rust/satdiff-dsp/presets/Shrooms.json @@ -46,7 +46,8 @@ "tile": 0.0, "tile_b": 0.0, "tone": 20000.0, - "tone_b": 20000.0 + "tone_b": 20000.0, + "asym_b": 55.0 }, "curve_ext_b": [ 0.0, @@ -71,22 +72,5 @@ 1.0, 1.0 ] - ], - "asym_b": [ - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 100.0, - 55.0 ] } diff --git a/rust/satdiff-plugin/presets/Soft2Hard.json b/rust/satdiff-dsp/presets/Soft2Hard.json similarity index 100% rename from rust/satdiff-plugin/presets/Soft2Hard.json rename to rust/satdiff-dsp/presets/Soft2Hard.json diff --git a/rust/satdiff-plugin/presets/Tube2Brick.json b/rust/satdiff-dsp/presets/Tube2Brick.json similarity index 100% rename from rust/satdiff-plugin/presets/Tube2Brick.json rename to rust/satdiff-dsp/presets/Tube2Brick.json diff --git a/rust/satdiff-plugin/presets/You_Rang.json b/rust/satdiff-dsp/presets/You_Rang.json similarity index 100% rename from rust/satdiff-plugin/presets/You_Rang.json rename to rust/satdiff-dsp/presets/You_Rang.json diff --git a/rust/satdiff-plugin/presets/Zap.json b/rust/satdiff-dsp/presets/Zap.json similarity index 100% rename from rust/satdiff-plugin/presets/Zap.json rename to rust/satdiff-dsp/presets/Zap.json diff --git a/rust/satdiff-dsp/src/color.rs b/rust/satdiff-dsp/src/color.rs index 72ba804..b87512e 100644 --- a/rust/satdiff-dsp/src/color.rs +++ b/rust/satdiff-dsp/src/color.rs @@ -290,11 +290,14 @@ pub struct ColorFx { gate_c: f64, /// the last settings, so the diffusor can be re-armed after another type ran p: DiffParams, + /// HPF / LPF on the wet of every type, ahead of COLOR MIX (SatFilt's colour output stage); false = SatDiff's behaviour, + /// RINGMOD / FREQ SHIFT only + filter_all: bool, } impl ColorFx { pub fn new(sr: f64) -> Self { - let mut f = Self { sr, dif: Diffusor::new(sr), pha: Phaser::new(), fla: Flanger::new(sr), rm: RingMod::new(), fsh: FreqShift::new(sr), flt: FxFilter::new(sr), cur: FX_DIFFUSOR, want: FX_DIFFUSOR, on: false, gate: 0.0, mix: Smooth::new(1.0), sm_c: 0.0, gate_c: 0.0, p: DiffParams::default() }; + let mut f = Self { sr, dif: Diffusor::new(sr), pha: Phaser::new(), fla: Flanger::new(sr), rm: RingMod::new(), fsh: FreqShift::new(sr), flt: FxFilter::new(sr), cur: FX_DIFFUSOR, want: FX_DIFFUSOR, on: false, gate: 0.0, mix: Smooth::new(1.0), sm_c: 0.0, gate_c: 0.0, p: DiffParams::default(), filter_all: false }; f.set_sample_rate(sr); f } @@ -318,10 +321,17 @@ impl ColorFx { self.flt.reset(); } + /// SatFilt: HPF / LPF filter the wet of every type (the diffusor then runs fully wet and COLOR MIX is applied here, after + /// the filters). Off (the default) keeps SatDiff's behaviour exactly. + pub fn set_filter_all(&mut self, on: bool) { + self.filter_all = on; + } + fn arm_diffusor(&mut self, snap: bool) { let p = self.p; let on = self.on && self.cur == FX_DIFFUSOR && self.want == FX_DIFFUSOR; - self.dif.set(on, p.fx_freq, p.fx_q, p.fx_stages, p.fx_spread, p.fx_mix, snap); + let mix = if self.filter_all { 100.0 } else { p.fx_mix }; + self.dif.set(on, p.fx_freq, p.fx_q, p.fx_stages, p.fx_spread, mix, snap); } /// `snap` jumps every smoothed value to its target (a fresh engine starts at the host's settings). @@ -359,7 +369,8 @@ impl ColorFx { for s in [&mut self.pha.centre, &mut self.pha.depth, &mut self.pha.fb, &mut self.pha.width, &mut self.fla.delay, &mut self.fla.depth, &mut self.fla.fb, &mut self.fla.width, &mut self.rm.freq, &mut self.rm.amount, &mut self.fsh.shift, &mut self.fsh.fb, &mut self.fsh.delay, &mut self.fsh.width, &mut self.mix] { s.snap(); } - self.gate = 0.0; + // filter-all mode runs the diffusor through the gate too: start it where the diffusor itself snaps to (on) + self.gate = if self.filter_all && self.on && self.want == FX_DIFFUSOR { 1.0 } else { 0.0 }; } } @@ -383,23 +394,32 @@ impl ColorFx { self.arm_diffusor(false); // a diffusor that just became the running type starts fading in } } - if self.cur == FX_DIFFUSOR { + if self.cur == FX_DIFFUSOR && !self.filter_all { return self.dif.tick(x); } let target = if self.on && self.cur == self.want { 1.0 } else { 0.0 }; self.gate += (target - self.gate) * self.gate_c; if self.gate < 1e-6 && target == 0.0 { self.gate = 0.0; + if self.cur == FX_DIFFUSOR { + // keep the (fully wet) diffusor fading itself out, so a later engage starts from clean state + self.dif.tick(x); + } return x; } let m = self.mix.step(self.sm_c) * self.gate; + if self.cur == FX_DIFFUSOR { + // filter-all mode: the diffusor's own fade sits inside the wet; the gate and COLOR MIX come after the filters + let wet = self.flt.tick(self.dif.tick(x)); + return [x[0] + (wet[0] - x[0]) * m, x[1] + (wet[1] - x[1]) * m]; + } let wet = match self.cur { FX_PHASER => self.pha.tick(x, self.sr, self.sm_c), FX_FLANGER => self.fla.tick(x, self.sr, self.sm_c), FX_FSHIFT => self.fsh.tick(x, self.sr, self.sm_c), _ => self.rm.tick(x, self.sr, self.sm_c), }; - let wet = if self.cur == FX_RINGMOD || self.cur == FX_FSHIFT { self.flt.tick(wet) } else { wet }; + let wet = if self.filter_all || self.cur == FX_RINGMOD || self.cur == FX_FSHIFT { self.flt.tick(wet) } else { wet }; [x[0] + (wet[0] - x[0]) * m, x[1] + (wet[1] - x[1]) * m] } } @@ -438,6 +458,42 @@ mod tests { .collect() } + fn render_all(p: &DiffParams, x: &[f64]) -> Vec { + let mut f = ColorFx::new(SR); + f.set_filter_all(true); + f.set(p, true); + x.iter().map(|&v| f.tick([v, v])[0]).collect() + } + + /// SatFilt's filter-all mode: with HPF / LPF open it is SatDiff's colour FX (the diffusor's mix moves after the filters, + /// so it agrees to rounding); off stays an exact bypass. + #[test] + fn filter_all_with_open_filters_is_satdiffs_colour() { + let x = noise(24000, 9); + for ty in 0..5 { + for mix in [100.0, 40.0] { + let p = DiffParams { fx_mix: mix, ..params(ty) }; + let (a, b) = (render(&p, &x), render_all(&p, &x)); + let d = a.iter().zip(&b).map(|(u, v)| (u - v).abs()).fold(0.0, f64::max); + assert!(d < 1e-9, "type {ty} mix {mix}: {d}"); + } + let off = DiffParams { fx_on: false, ..params(ty) }; + assert_eq!(render_all(&off, &x), x, "type {ty} off"); + } + } + + /// Filter-all: HPF / LPF act on every type's wet (SatDiff filters only RINGMOD / FREQ SHIFT). + #[test] + fn filter_all_filters_every_type() { + let x = noise(24000, 11); + for ty in [0, 1, 2] { + let p = DiffParams { fx_hp: 1500.0, fx_lp: 3000.0, ..params(ty) }; + assert!(render(&p, &x) == render(¶ms(ty), &x), "type {ty}: SatDiff leaves it unfiltered"); + let (a, b) = (render_all(&p, &x), render_all(¶ms(ty), &x)); + assert!(rms(&a) < rms(&b) * 0.7, "type {ty}: {} vs {}", rms(&a), rms(&b)); + } + } + #[test] fn off_is_an_exact_bypass_for_every_type() { let x = noise(6000, 3); diff --git a/rust/satdiff-dsp/src/lib.rs b/rust/satdiff-dsp/src/lib.rs index 5bc609e..99cea26 100644 --- a/rust/satdiff-dsp/src/lib.rs +++ b/rust/satdiff-dsp/src/lib.rs @@ -7,6 +7,8 @@ pub mod engine; pub mod filters; pub mod follower; pub mod params; +pub mod preset; +pub mod spec; pub mod phase; pub use engine::DiffEngine; @@ -14,3 +16,6 @@ pub use params::DiffParams; /// samples between two steps of the shaper crossfade (the shared `satcomp_dsp::shapers::FADE_EVERY`) pub const MORPH_EVERY: u32 = satcomp_dsp::shapers::FADE_EVERY; + +/// This crate's version, the same as the plug-in's (reported by the CLI). +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/rust/satdiff-dsp/src/params.rs b/rust/satdiff-dsp/src/params.rs index a607a80..738e5e5 100644 --- a/rust/satdiff-dsp/src/params.rs +++ b/rust/satdiff-dsp/src/params.rs @@ -1,6 +1,6 @@ //! SatDiff 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::shapers::Curve; use satcomp_dsp::SatParams; #[derive(Clone, Copy, PartialEq, Debug)] @@ -8,8 +8,8 @@ pub struct DiffParams { // 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], + /// ASYM of scene A, 0..100 %, one value for every shaper (see `SatParams::asym`) + pub asym: f64, pub drive: f64, pub bias: f64, pub sat_hp: f64, @@ -37,7 +37,7 @@ pub struct DiffParams { pub shape_b: i32, pub curve_b: Curve, pub tile_b: i32, - pub asym_b: [f64; SHAPER_COUNT], + pub asym_b: f64, pub drive_b: f64, pub bias_b: f64, pub sat_hp_b: f64, @@ -93,7 +93,7 @@ impl Default for DiffParams { Self { shape: 0, curve: Curve::linear(), - asym: [100.0; SHAPER_COUNT], + asym: 100.0, drive: 0.0, bias: 0.0, sat_hp: 20.0, @@ -110,7 +110,7 @@ impl Default for DiffParams { shape_b: 0, curve_b: Curve::linear(), tile_b: 0, - asym_b: [100.0; SHAPER_COUNT], + asym_b: 100.0, drive_b: 0.0, bias_b: 0.0, sat_hp_b: 20.0, @@ -196,17 +196,17 @@ impl DiffParams { /// Scene A's saturator settings (the one that is heard when MORPH is off). pub fn sat(&self) -> SatParams { let (shape, curve) = self.scene_view(0); - self.sat_for(shape, curve, self.drive, self.bias, self.sat_hp, self.sat_lp, self.tone, &self.asym) + self.sat_for(shape, curve, self.drive, self.bias, self.sat_hp, self.sat_lp, self.tone, self.asym) } /// Scene B's saturator settings (blended in by MORPH). pub fn sat_b(&self) -> SatParams { let (shape, curve) = self.scene_view(1); - self.sat_for(shape, curve, self.drive_b, self.bias_b, self.sat_hp_b, self.sat_lp_b, self.tone_b, &self.asym_b) + self.sat_for(shape, curve, self.drive_b, self.bias_b, self.sat_hp_b, self.sat_lp_b, self.tone_b, self.asym_b) } #[allow(clippy::too_many_arguments)] - fn sat_for(&self, shape: i32, curve: Curve, drive: f64, bias: f64, hp: f64, lp: f64, tone: f64, asym: &[f64; SHAPER_COUNT]) -> SatParams { + fn sat_for(&self, shape: i32, curve: Curve, drive: f64, bias: f64, hp: f64, lp: f64, tone: f64, asym: f64) -> SatParams { SatParams { shape, curve, @@ -219,7 +219,7 @@ impl DiffParams { os: if self.tile_active() { self.os.max(2) } else { self.os }, mix: self.sat_mix, out_db: 0.0, - asym: Some(asym[(shape.max(0) as usize).min(SHAPER_COUNT - 1)]), + asym: Some(asym.clamp(0.0, 100.0)), steep: false, } } diff --git a/rust/satdiff-dsp/src/preset.rs b/rust/satdiff-dsp/src/preset.rs new file mode 100644 index 0000000..09e8fd4 --- /dev/null +++ b/rust/satdiff-dsp/src/preset.rs @@ -0,0 +1,243 @@ +//! SatDiff presets (the plug-in's and the CLI's shared format): JSON files of parameter values keyed by parameter id. +//! Factory bank = every `presets/*.json` embedded at build time (+ built-in INIT). User presets = `*.satdiff` files in +//! `user_dir()`: the plug-in lists them, the CLI loads them by name. + +use crate::spec::TABLE; +use satcomp_dsp::shapers::Curve; +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 = "satdiff"; +/// 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)>, + /// Curve handles / LINEAR | CURVE of the custom curve (`Curve::ext`; absent = plain). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curve_ext: Vec, + /// Same for scene B. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curve_ext_b: Vec, + /// Scene B's custom curve (absent = linear). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curve_b: 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, + /// Scene B's ASYM per waveshaper (absent / empty = all 100 %). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asym_b: Vec, +} + +impl Preset { + /// A preset of the current settings (the editor's SAVE, the CLI's --save-preset): every parameter presets keep, read + /// through `get(slot)`, and the drawn curves when any is not the plain line. + pub fn capture(name: &str, get: impl Fn(usize) -> f32, curves: &[Curve; 2]) -> Self { + let params = TABLE.iter().filter(|e| !EXCLUDED.contains(&e.1)).map(|e| (e.1.to_string(), get(e.0))).collect(); + let mut p = Self::new(name, params); + if curves[0] != Curve::linear() { + p.curve = curves[0].pts().to_vec(); + p.curve_ext = curves[0].ext(); + } + if curves[1] != Curve::linear() { + p.curve_b = curves[1].pts().to_vec(); + p.curve_ext_b = curves[1].ext(); + } + p + } + + /// What loading this preset writes, as (slot, plain value) per parameter it sets (clamped to the range; a parameter it + /// leaves alone is absent). The editor sends each one like a click; the CLI stores them with `spec::Values::set`. + pub fn writes(&self) -> Vec<(usize, f32)> { + TABLE + .iter() + .filter(|e| !EXCLUDED.contains(&e.1)) + .map(|&(n, id, mn, mx, df)| (n, self.params.get(id).copied().unwrap_or(df).clamp(mn, mx))) + .collect() + } + + /// The drawn curves a load stores (the editor keeps their points; the engine gets these). + pub fn drawn(&self) -> [Curve; 2] { + // absent curve = linear (a load never keeps the previous preset's curves) + [Curve::from_parts(&self.curve, &self.curve_ext), Curve::from_parts(&self.curve_b, &self.curve_ext_b)] + } + + pub fn new(name: &str, params: BTreeMap) -> Self { + Self { format: "satdiff-preset".into(), version: 1, name: name.into(), params, curve: Vec::new(), curve_ext: Vec::new(), curve_ext_b: Vec::new(), curve_b: Vec::new(), asym: Vec::new(), asym_b: 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 mut p: Preset = serde_json::from_str(s).ok()?; + if p.format != "satdiff-preset" { + return None; + } + // ASYM used to be one value per shaper and scene: each scene's value for its own shaper becomes its ASYM parameter + let legacy = [(std::mem::take(&mut p.asym), "asym", "shape"), (std::mem::take(&mut p.asym_b), "asym_b", "shape_b")]; + for (list, key, shape_key) in legacy { + if list.is_empty() || p.params.contains_key(key) { + continue; + } + let shape = p.params.get(shape_key).copied().unwrap_or(0.0).round().max(0.0) as usize; + if let Some(v) = list.get(shape).filter(|v| v.is_finite()) { + p.params.insert(key.into(), v.clamp(0.0, 100.0)); + } + } + 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/SatDiff/Presets (macOS), %APPDATA%\SatDiff\Presets (Windows), ~/.config/SatDiff/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("SatDiff").join("Presets")) +} + +/// (display name, path) of the user presets, sorted case-insensitively. +pub fn scan_user() -> Vec<(String, PathBuf)> { + let mut v = Vec::new(); + 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(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["lim_on"], 1.0); + assert_eq!(p.params["gain_match"], 0.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 the_curve_roundtrips_and_legacy_asym_lists_become_each_scenes_asym_parameter() { + let mut p = Preset::init(); + assert!(!p.to_json().contains("curve") && p.params["asym"] == 100.0 && p.params["asym_b"] == 100.0); + p.curve = vec![(-1.0, -1.0), (0.0, 0.3), (1.0, 1.0)]; + assert_eq!(Preset::from_json(&p.to_json()).unwrap().curve, p.curve); + // 0.1.x: one list per scene; each scene's value for its own shaper becomes its parameter + let old = r#"{"format":"satdiff-preset","version":1,"name":"x","params":{"shape_b":1.0},"asym":[40.0],"asym_b":[100.0,35.0]}"#; + let o = Preset::from_json(old).unwrap(); + assert_eq!((o.params["asym"], o.params["asym_b"]), (40.0, 35.0)); + assert!(o.asym.is_empty() && o.asym_b.is_empty() && !o.to_json().contains("[40")); + let both = r#"{"format":"satdiff-preset","version":1,"name":"x","params":{"asym":60.0},"asym":[10.0]}"#; + assert_eq!(Preset::from_json(both).unwrap().params["asym"], 60.0); + } + + #[test] + fn every_factory_value_is_in_range() { + for p in &factory() { + 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); + } + } + } + + #[test] + fn the_factory_bank_has_the_owners_eight_and_every_value_is_in_range() { + let f = factory(); + for want in ["Amen Hell", "Bump Me Up", "Burnt Popcorn", "Shrooms", "Soft2Hard", "Tube2Brick", "You Rang", "Zap"] { + 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); + } + } + // the drawn curves and their handles ride along + let n = |name: &str| f.iter().find(|p| p.name == name).unwrap(); + assert_eq!(n("Zap").curve.len(), 4); + assert_eq!(n("Burnt Popcorn").curve.len(), 6); + assert_eq!(n("Bump Me Up").curve_b.len(), 14); + assert_eq!(n("Shrooms").curve_ext_b.len(), n("Shrooms").curve_b.len()); + assert_eq!(n("Shrooms").params["asym_b"], 55.0, "its scene B ASYM (Custom) is a parameter now"); + } + + #[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/satdiff-dsp/src/spec.rs b/rust/satdiff-dsp/src/spec.rs new file mode 100644 index 0000000..8b4c266 --- /dev/null +++ b/rust/satdiff-dsp/src/spec.rs @@ -0,0 +1,367 @@ +// GENERATED by tools/gen_dparams.py (tools/specgen.py). Do not edit by hand. +//! The parameter layer shared by the plug-in and the CLI: table, metadata, plain values and the one mapping onto the +//! engine's settings. + +#![allow(clippy::excessive_precision, clippy::approx_constant)] + +use satcomp_dsp::paramspec::{Kind, ParamSpec}; +use crate::DiffParams; +use satcomp_dsp::shapers::Curve; + +/// Highest UI slot number + 1. +pub const SLOTS: usize = 64; + +/// (slot number, id, min, max, default) for every parameter. +pub const TABLE: &[(usize, &str, f32, f32, f32)] = &[ + (1, "shape", 0.0, 16.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, "in_gain", -24.0, 24.0, 0.0), + (22, "out_gain", -24.0, 12.0, 0.0), + (23, "gain_match", 0.0, 1.0, 0.0), + (24, "lim_on", 0.0, 1.0, 1.0), + (26, "bypass", 0.0, 1.0, 0.0), + (30, "phase", -180.0, 180.0, 0.0), + (31, "fx_on", 0.0, 1.0, 0.0), + (32, "fx_type", 0.0, 4.0, 0.0), + (33, "fx_pos", 0.0, 1.0, 0.0), + (34, "fx_freq", 20.0, 20000.0, 1000.0), + (35, "fx_q", 0.3, 8.0, 0.7), + (36, "fx_stages", 0.0, 100.0, 20.0), + (37, "fx_mix", 0.0, 100.0, 100.0), + (38, "tile", 0.0, 2.0, 0.0), + (39, "morph_dir", 0.0, 2.0, 2.0), + (40, "morph_depth", 0.0, 100.0, 0.0), + (41, "morph_speed", 0.0, 100.0, 50.0), + (42, "ab", 0.0, 1.0, 0.0), + (62, "asym", 0.0, 100.0, 100.0), + (63, "asym_b", 0.0, 100.0, 100.0), + (44, "shape_b", 0.0, 16.0, 0.0), + (45, "tile_b", 0.0, 2.0, 0.0), + (46, "fx_rate", 0.02, 20.0, 0.5), + (47, "fx_depth", 0.0, 100.0, 50.0), + (48, "fx_fb", -95.0, 95.0, 0.0), + (49, "fx_delay", 0.1, 10.0, 2.0), + (50, "fx_shape", 0.0, 3.0, 0.0), + (51, "drive_b", 0.0, 100.0, 0.0), + (52, "bias_b", -100.0, 100.0, 0.0), + (53, "sat_hp_b", 20.0, 2000.0, 20.0), + (54, "sat_lp_b", 200.0, 20000.0, 20000.0), + (55, "tone_b", 1000.0, 20000.0, 20000.0), + (56, "fx_shift", -1000.0, 1000.0, 0.0), + (57, "out_hp", 20.0, 2000.0, 20.0), + (58, "out_hp_m", 0.0, 1.0, 1.0), + (59, "out_hp_s", 0.0, 1.0, 1.0), + (60, "fx_hp", 20.0, 2000.0, 20.0), + (61, "fx_lp", 200.0, 20000.0, 20000.0), + (43, "fx_spread", 0.0, 100.0, 50.0), +]; + +/// Full metadata of every parameter, in the order of `TABLE`. +pub const SPECS: &[ParamSpec] = &[ + ParamSpec { slot: 1, id: "shape", name: "Shape", kind: Kind::Int, min: 0.0, max: 16.0, default: 0.0, step: 1.0, unit: "", choices: &satcomp_dsp::shapers::SHAPER_NAMES }, + ParamSpec { slot: 2, id: "drive", name: "Drive", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 3, id: "bias", name: "Bias", kind: Kind::Float, min: -100.0, max: 100.0, default: 0.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 4, id: "sat_hp", name: "Sat HP", kind: Kind::Float, min: 20.0, max: 2000.0, default: 20.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 5, id: "sat_lp", name: "Sat LP", kind: Kind::Float, min: 200.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 6, id: "tone", name: "Tone", kind: Kind::Float, min: 1000.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 7, id: "os", name: "Oversampling", kind: Kind::Int, min: 0.0, max: 3.0, default: 0.0, step: 1.0, unit: "", choices: &["x1", "x2", "x4", "x8"] }, + ParamSpec { slot: 25, id: "sat_mix", name: "Sat Mix", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 27, id: "in_gain", name: "In Gain", kind: Kind::Float, min: -24.0, max: 24.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 22, id: "out_gain", name: "Out Gain", kind: Kind::Float, min: -24.0, max: 12.0, default: 0.0, step: 0.1, unit: "dB", choices: &[] }, + ParamSpec { slot: 23, id: "gain_match", name: "Gain Match", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 24, id: "lim_on", name: "Limiter", kind: Kind::Bool, min: 0.0, max: 1.0, default: 1.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 26, id: "bypass", name: "Bypass", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 30, id: "phase", name: "Phase", kind: Kind::Float, min: -180.0, max: 180.0, default: 0.0, step: 1.0, unit: "deg", choices: &[] }, + ParamSpec { slot: 31, id: "fx_on", name: "FX On", kind: Kind::Bool, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 32, id: "fx_type", name: "FX Type", kind: Kind::Int, min: 0.0, max: 4.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 33, id: "fx_pos", name: "FX Pre/Post", kind: Kind::Int, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 34, id: "fx_freq", name: "FX Freq", kind: Kind::Float, min: 20.0, max: 20000.0, default: 1000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 35, id: "fx_q", name: "FX Q", kind: Kind::Float, min: 0.3, max: 8.0, default: 0.7, step: 0.01, unit: "", choices: &[] }, + ParamSpec { slot: 36, id: "fx_stages", name: "FX Stages", kind: Kind::Float, min: 0.0, max: 100.0, default: 20.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 37, id: "fx_mix", name: "Color Mix", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 38, id: "tile", name: "Tile", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 39, id: "morph_dir", name: "Morph Mode", kind: Kind::Int, min: 0.0, max: 2.0, default: 2.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 40, id: "morph_depth", name: "Morph Depth", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 41, id: "morph_speed", name: "Morph Speed", kind: Kind::Float, min: 0.0, max: 100.0, default: 50.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 42, id: "ab", name: "Scene A/B", kind: Kind::Int, min: 0.0, max: 1.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 62, id: "asym", name: "Asym", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 63, id: "asym_b", name: "Asym B", kind: Kind::Float, min: 0.0, max: 100.0, default: 100.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 44, id: "shape_b", name: "Shape B", kind: Kind::Int, min: 0.0, max: 16.0, default: 0.0, step: 1.0, unit: "", choices: &satcomp_dsp::shapers::SHAPER_NAMES }, + ParamSpec { slot: 45, id: "tile_b", name: "Tile B", kind: Kind::Int, min: 0.0, max: 2.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 46, id: "fx_rate", name: "FX Rate", kind: Kind::Float, min: 0.02, max: 20.0, default: 0.5, step: 0.01, unit: "Hz", choices: &[] }, + ParamSpec { slot: 47, id: "fx_depth", name: "FX Depth", kind: Kind::Float, min: 0.0, max: 100.0, default: 50.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 48, id: "fx_fb", name: "FX Feedback", kind: Kind::Float, min: -95.0, max: 95.0, default: 0.0, step: 1.0, unit: "%", choices: &[] }, + ParamSpec { slot: 49, id: "fx_delay", name: "FX Delay", kind: Kind::Float, min: 0.1, max: 10.0, default: 2.0, step: 0.01, unit: "ms", choices: &[] }, + ParamSpec { slot: 50, id: "fx_shape", name: "FX Shape", kind: Kind::Int, min: 0.0, max: 3.0, default: 0.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 51, id: "drive_b", name: "Drive B", kind: Kind::Float, min: 0.0, max: 100.0, default: 0.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 52, id: "bias_b", name: "Bias B", kind: Kind::Float, min: -100.0, max: 100.0, default: 0.0, step: 0.1, unit: "%", choices: &[] }, + ParamSpec { slot: 53, id: "sat_hp_b", name: "Sat HP B", kind: Kind::Float, min: 20.0, max: 2000.0, default: 20.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 54, id: "sat_lp_b", name: "Sat LP B", kind: Kind::Float, min: 200.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 55, id: "tone_b", name: "Tone B", kind: Kind::Float, min: 1000.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 56, id: "fx_shift", name: "FX Shift", kind: Kind::Float, min: -1000.0, max: 1000.0, default: 0.0, step: 0.1, unit: "Hz", choices: &[] }, + ParamSpec { slot: 57, id: "out_hp", name: "Out HP", kind: Kind::Float, min: 20.0, max: 2000.0, default: 20.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 58, id: "out_hp_m", name: "Out HP Mid", kind: Kind::Bool, min: 0.0, max: 1.0, default: 1.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 59, id: "out_hp_s", name: "Out HP Side", kind: Kind::Bool, min: 0.0, max: 1.0, default: 1.0, step: 1.0, unit: "", choices: &[] }, + ParamSpec { slot: 60, id: "fx_hp", name: "FX HP", kind: Kind::Float, min: 20.0, max: 2000.0, default: 20.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 61, id: "fx_lp", name: "FX LP", kind: Kind::Float, min: 200.0, max: 20000.0, default: 20000.0, step: 1.0, unit: "Hz", choices: &[] }, + ParamSpec { slot: 43, id: "fx_spread", name: "FX Spread", kind: Kind::Float, min: 0.0, max: 100.0, default: 50.0, step: 1.0, unit: "%", choices: &[] }, +]; + +/// Every parameter's plain value (the unit it is displayed in), named by its id. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Values { + pub shape: i32, + pub drive: f32, + pub bias: f32, + pub sat_hp: f32, + pub sat_lp: f32, + pub tone: f32, + pub os: i32, + pub sat_mix: f32, + pub in_gain: f32, + pub out_gain: f32, + pub gain_match: bool, + pub lim_on: bool, + pub bypass: bool, + pub phase: f32, + pub fx_on: bool, + pub fx_type: i32, + pub fx_pos: i32, + pub fx_freq: f32, + pub fx_q: f32, + pub fx_stages: f32, + pub fx_mix: f32, + pub tile: i32, + pub morph_dir: i32, + pub morph_depth: f32, + pub morph_speed: f32, + pub ab: i32, + pub asym: f32, + pub asym_b: f32, + pub shape_b: i32, + pub tile_b: i32, + pub fx_rate: f32, + pub fx_depth: f32, + pub fx_fb: f32, + pub fx_delay: f32, + pub fx_shape: i32, + pub drive_b: f32, + pub bias_b: f32, + pub sat_hp_b: f32, + pub sat_lp_b: f32, + pub tone_b: f32, + pub fx_shift: f32, + pub out_hp: f32, + pub out_hp_m: bool, + pub out_hp_s: bool, + pub fx_hp: f32, + pub fx_lp: f32, + pub fx_spread: f32, +} + +impl Default for Values { + /// Every parameter at its default (the plug-in's INIT). + fn default() -> Self { + Self { + shape: 0, + drive: 0.0f32, + bias: 0.0f32, + sat_hp: 20.0f32, + sat_lp: 20000.0f32, + tone: 20000.0f32, + os: 0, + sat_mix: 100.0f32, + in_gain: 0.0f32, + out_gain: 0.0f32, + gain_match: false, + lim_on: true, + bypass: false, + phase: 0.0f32, + fx_on: false, + fx_type: 0, + fx_pos: 0, + fx_freq: 1000.0f32, + fx_q: 0.7f32, + fx_stages: 20.0f32, + fx_mix: 100.0f32, + tile: 0, + morph_dir: 2, + morph_depth: 0.0f32, + morph_speed: 50.0f32, + ab: 0, + asym: 100.0f32, + asym_b: 100.0f32, + shape_b: 0, + tile_b: 0, + fx_rate: 0.5f32, + fx_depth: 50.0f32, + fx_fb: 0.0f32, + fx_delay: 2.0f32, + fx_shape: 0, + drive_b: 0.0f32, + bias_b: 0.0f32, + sat_hp_b: 20.0f32, + sat_lp_b: 20000.0f32, + tone_b: 20000.0f32, + fx_shift: 0.0f32, + out_hp: 20.0f32, + out_hp_m: true, + out_hp_s: true, + fx_hp: 20.0f32, + fx_lp: 20000.0f32, + fx_spread: 50.0f32, + } + } +} + +impl Values { + /// The value at UI slot `slot` as a plain number (switches 0 / 1). + pub fn get(&self, slot: usize) -> Option { + Some(match slot { + 1 => self.shape as f32, + 2 => self.drive, + 3 => self.bias, + 4 => self.sat_hp, + 5 => self.sat_lp, + 6 => self.tone, + 7 => self.os as f32, + 25 => self.sat_mix, + 27 => self.in_gain, + 22 => self.out_gain, + 23 => self.gain_match as i32 as f32, + 24 => self.lim_on as i32 as f32, + 26 => self.bypass as i32 as f32, + 30 => self.phase, + 31 => self.fx_on as i32 as f32, + 32 => self.fx_type as f32, + 33 => self.fx_pos as f32, + 34 => self.fx_freq, + 35 => self.fx_q, + 36 => self.fx_stages, + 37 => self.fx_mix, + 38 => self.tile as f32, + 39 => self.morph_dir as f32, + 40 => self.morph_depth, + 41 => self.morph_speed, + 42 => self.ab as f32, + 62 => self.asym, + 63 => self.asym_b, + 44 => self.shape_b as f32, + 45 => self.tile_b as f32, + 46 => self.fx_rate, + 47 => self.fx_depth, + 48 => self.fx_fb, + 49 => self.fx_delay, + 50 => self.fx_shape as f32, + 51 => self.drive_b, + 52 => self.bias_b, + 53 => self.sat_hp_b, + 54 => self.sat_lp_b, + 55 => self.tone_b, + 56 => self.fx_shift, + 57 => self.out_hp, + 58 => self.out_hp_m as i32 as f32, + 59 => self.out_hp_s as i32 as f32, + 60 => self.fx_hp, + 61 => self.fx_lp, + 43 => self.fx_spread, + _ => return None, + }) + } + + /// Store `v` at UI slot `slot` the way the plug-in holds a value the editor or a preset writes: clamped, sent as + /// `(v - min) / (max - min)`, unnormalised by nih-plug (ints rounded, switches above one half) and snapped to the + /// step. Returns false for an unknown slot. + pub fn set(&mut self, slot: usize, v: f32) -> bool { + match slot { + 1 => self.shape = (((v - 0.0) / (16.0 - 0.0)).clamp(0.0, 1.0) * (16 - 0) as f32).round() as i32 + 0, + 2 => self.drive = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 100.0), + 3 => self.bias = (((((v - -100.0) / (100.0 - -100.0)).clamp(0.0, 1.0) * (100.0 - -100.0) + -100.0) / 0.1).round() * 0.1).clamp(-100.0, 100.0), + 4 => self.sat_hp = (((((v - 20.0) / (2000.0 - 20.0)).clamp(0.0, 1.0) * (2000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 2000.0), + 5 => self.sat_lp = (((((v - 200.0) / (20000.0 - 200.0)).clamp(0.0, 1.0) * (20000.0 - 200.0) + 200.0) / 1.0).round() * 1.0).clamp(200.0, 20000.0), + 6 => self.tone = (((((v - 1000.0) / (20000.0 - 1000.0)).clamp(0.0, 1.0) * (20000.0 - 1000.0) + 1000.0) / 1.0).round() * 1.0).clamp(1000.0, 20000.0), + 7 => self.os = (((v - 0.0) / (3.0 - 0.0)).clamp(0.0, 1.0) * (3 - 0) as f32).round() as i32 + 0, + 25 => self.sat_mix = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 27 => self.in_gain = (((((v - -24.0) / (24.0 - -24.0)).clamp(0.0, 1.0) * (24.0 - -24.0) + -24.0) / 0.1).round() * 0.1).clamp(-24.0, 24.0), + 22 => self.out_gain = (((((v - -24.0) / (12.0 - -24.0)).clamp(0.0, 1.0) * (12.0 - -24.0) + -24.0) / 0.1).round() * 0.1).clamp(-24.0, 12.0), + 23 => self.gain_match = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 24 => self.lim_on = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 26 => self.bypass = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 30 => self.phase = (((((v - -180.0) / (180.0 - -180.0)).clamp(0.0, 1.0) * (180.0 - -180.0) + -180.0) / 1.0).round() * 1.0).clamp(-180.0, 180.0), + 31 => self.fx_on = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 32 => self.fx_type = (((v - 0.0) / (4.0 - 0.0)).clamp(0.0, 1.0) * (4 - 0) as f32).round() as i32 + 0, + 33 => self.fx_pos = (((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) * (1 - 0) as f32).round() as i32 + 0, + 34 => self.fx_freq = (((((v - 20.0) / (20000.0 - 20.0)).clamp(0.0, 1.0) * (20000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 20000.0), + 35 => self.fx_q = (((((v - 0.3) / (8.0 - 0.3)).clamp(0.0, 1.0) * (8.0 - 0.3) + 0.3) / 0.01).round() * 0.01).clamp(0.3, 8.0), + 36 => self.fx_stages = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 37 => self.fx_mix = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 38 => self.tile = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 39 => self.morph_dir = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 40 => self.morph_depth = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 41 => self.morph_speed = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 42 => self.ab = (((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) * (1 - 0) as f32).round() as i32 + 0, + 62 => self.asym = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 63 => self.asym_b = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 44 => self.shape_b = (((v - 0.0) / (16.0 - 0.0)).clamp(0.0, 1.0) * (16 - 0) as f32).round() as i32 + 0, + 45 => self.tile_b = (((v - 0.0) / (2.0 - 0.0)).clamp(0.0, 1.0) * (2 - 0) as f32).round() as i32 + 0, + 46 => self.fx_rate = (((((v - 0.02) / (20.0 - 0.02)).clamp(0.0, 1.0) * (20.0 - 0.02) + 0.02) / 0.01).round() * 0.01).clamp(0.02, 20.0), + 47 => self.fx_depth = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + 48 => self.fx_fb = (((((v - -95.0) / (95.0 - -95.0)).clamp(0.0, 1.0) * (95.0 - -95.0) + -95.0) / 1.0).round() * 1.0).clamp(-95.0, 95.0), + 49 => self.fx_delay = (((((v - 0.1) / (10.0 - 0.1)).clamp(0.0, 1.0) * (10.0 - 0.1) + 0.1) / 0.01).round() * 0.01).clamp(0.1, 10.0), + 50 => self.fx_shape = (((v - 0.0) / (3.0 - 0.0)).clamp(0.0, 1.0) * (3 - 0) as f32).round() as i32 + 0, + 51 => self.drive_b = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 0.1).round() * 0.1).clamp(0.0, 100.0), + 52 => self.bias_b = (((((v - -100.0) / (100.0 - -100.0)).clamp(0.0, 1.0) * (100.0 - -100.0) + -100.0) / 0.1).round() * 0.1).clamp(-100.0, 100.0), + 53 => self.sat_hp_b = (((((v - 20.0) / (2000.0 - 20.0)).clamp(0.0, 1.0) * (2000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 2000.0), + 54 => self.sat_lp_b = (((((v - 200.0) / (20000.0 - 200.0)).clamp(0.0, 1.0) * (20000.0 - 200.0) + 200.0) / 1.0).round() * 1.0).clamp(200.0, 20000.0), + 55 => self.tone_b = (((((v - 1000.0) / (20000.0 - 1000.0)).clamp(0.0, 1.0) * (20000.0 - 1000.0) + 1000.0) / 1.0).round() * 1.0).clamp(1000.0, 20000.0), + 56 => self.fx_shift = (((((v - -1000.0) / (1000.0 - -1000.0)).clamp(0.0, 1.0) * (1000.0 - -1000.0) + -1000.0) / 0.1).round() * 0.1).clamp(-1000.0, 1000.0), + 57 => self.out_hp = (((((v - 20.0) / (2000.0 - 20.0)).clamp(0.0, 1.0) * (2000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 2000.0), + 58 => self.out_hp_m = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 59 => self.out_hp_s = ((v - 0.0) / (1.0 - 0.0)).clamp(0.0, 1.0) > 0.5, + 60 => self.fx_hp = (((((v - 20.0) / (2000.0 - 20.0)).clamp(0.0, 1.0) * (2000.0 - 20.0) + 20.0) / 1.0).round() * 1.0).clamp(20.0, 2000.0), + 61 => self.fx_lp = (((((v - 200.0) / (20000.0 - 200.0)).clamp(0.0, 1.0) * (20000.0 - 200.0) + 200.0) / 1.0).round() * 1.0).clamp(200.0, 20000.0), + 43 => self.fx_spread = (((((v - 0.0) / (100.0 - 0.0)).clamp(0.0, 1.0) * (100.0 - 0.0) + 0.0) / 1.0).round() * 1.0).clamp(0.0, 100.0), + _ => return false, + } + true + } + + /// The UI slot of parameter `id`. + pub fn slot_of(id: &str) -> Option { + TABLE.iter().find(|e| e.1 == id).map(|e| e.0) + } +} + +/// The engine's settings for `v`: the one mapping (the plug-in calls it with its parameters' current values). +pub fn to_dsp(v: &Values, curves: [Curve; 2]) -> DiffParams { + DiffParams { + shape: v.shape, curve: curves[0], curve_b: curves[1], shape_b: v.shape_b, tile_b: v.tile_b, asym: v.asym as f64, asym_b: v.asym_b as f64, drive_b: v.drive_b as f64, bias_b: v.bias_b as f64, sat_hp_b: v.sat_hp_b as f64, sat_lp_b: v.sat_lp_b as f64, tone_b: v.tone_b as f64, drive: v.drive as f64, bias: v.bias as f64, + sat_hp: v.sat_hp as f64, sat_lp: v.sat_lp as f64, tone: v.tone as f64, + sat_mix: v.sat_mix as f64, in_gain: v.in_gain as f64, os: v.os, + out_gain: v.out_gain as f64, gain_match: v.gain_match, lim_on: v.lim_on, + bypass: v.bypass, ab: v.ab, phase: v.phase as f64, fx_on: v.fx_on, + fx_type: v.fx_type, fx_pos: v.fx_pos, fx_freq: v.fx_freq as f64, fx_q: v.fx_q as f64, + fx_stages: crate::diffuse::stages_from_pct(v.fx_stages as f64), fx_spread: v.fx_spread as f64, fx_rate: v.fx_rate as f64, fx_depth: v.fx_depth as f64, fx_fb: v.fx_fb as f64, fx_delay: v.fx_delay as f64, fx_shape: v.fx_shape, fx_shift: v.fx_shift as f64, fx_hp: v.fx_hp as f64, fx_lp: v.fx_lp as f64, out_hp: v.out_hp as f64, out_hp_m: v.out_hp_m, out_hp_s: v.out_hp_s, fx_mix: v.fx_mix as f64, tile: v.tile, morph_dir: v.morph_dir, + morph_depth: v.morph_depth as f64, morph_speed: v.morph_speed as f64, + } +} + +#[cfg(test)] +mod spec_tests { + /// ids / slots unique, ranges and defaults sane, every choice list exactly covers its range. + #[test] + fn the_table_is_consistent() { + satcomp_dsp::paramspec::check(super::SPECS).unwrap(); + assert_eq!(super::TABLE.len(), super::SPECS.len()); + let v = super::Values::default(); + for s in super::SPECS { + assert_eq!(v.get(s.slot), Some(s.default), "{}", s.id); + } + } +} diff --git a/rust/satdiff-plugin/Cargo.toml b/rust/satdiff-plugin/Cargo.toml index f7ba94d..bba7ba5 100644 --- a/rust/satdiff-plugin/Cargo.toml +++ b/rust/satdiff-plugin/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "satdiff" -version = "0.1.0" +version = "0.1.1" edition = "2021" license = "GPL-3.0-or-later" publish = false @@ -13,11 +13,8 @@ nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", features = ["v satcomp-dsp = { path = "../satcomp-dsp" } satdiff-dsp = { path = "../satdiff-dsp" } satcomp-ui = { path = "../satcomp-ui" } -nih_plug_egui = { path = "../vendor/nih_plug_egui" } -serde = { version = "1", features = ["derive"] } -serde_json = "1" +nih_plug_egui = { path = "../vendor/nih_plug_egui", default-features = false, features = ["opengl"] } parking_lot = "0.12" -include_dir = "0.7" [target.'cfg(any(target_os = "macos", windows))'.dependencies] rfd = { version = "0.15", default-features = false } diff --git a/rust/satdiff-plugin/src/gui/mod.rs b/rust/satdiff-plugin/src/gui/mod.rs index c478ef5..85d3879 100644 --- a/rust/satdiff-plugin/src/gui/mod.rs +++ b/rust/satdiff-plugin/src/gui/mod.rs @@ -9,7 +9,7 @@ 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::canvas::Canvas; use satcomp_ui::init_ctx; use std::sync::Arc; use std::time::Duration; @@ -17,12 +17,13 @@ use ui::{Env, Gui, State}; /// Logical grid (units); the window scales it in quarter steps. pub const W: f32 = 316.0; -pub const H: f32 = 556.0; +pub const H: f32 = 578.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: &SatDiffParams, shared: &Shared) { let screen = ctx.screen_rect(); - let s = ((screen.width() / W).min(screen.height() / H) * 4.0).floor() / 4.0; + // quarter steps; a window a pixel or two short of a step (a host rounding the size down) still gets that step + let s = ((screen.width() / W).min(screen.height() / H) * 4.0 + 0.02).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(); @@ -57,7 +58,7 @@ pub(crate) fn run_frame(ctx: &egui::Context, setter: &nih_plug::prelude::ParamSe 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 face = satcomp_ui::canvas::font_sanitize(params.font.load(std::sync::atomic::Ordering::Relaxed)); let state = State::new(pal, light, face, ¶ms); let editor_state = params.editor_state.clone(); let look_params = params.clone(); diff --git a/rust/satdiff-plugin/src/gui/smoke.rs b/rust/satdiff-plugin/src/gui/smoke.rs index c53475e..61561db 100644 --- a/rust/satdiff-plugin/src/gui/smoke.rs +++ b/rust/satdiff-plugin/src/gui/smoke.rs @@ -85,6 +85,10 @@ impl Rig { 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)); + if satcomp_ui::bench::timing() { + let _ = self.ctx.tessellate(full.shapes, full.pixels_per_point); + return; + } let mut fh: u64 = 0xcbf29ce484222325; for b in format!("{:?}", full.shapes).bytes() { self.hash ^= b as u64; @@ -147,21 +151,21 @@ fn script() -> (u64, Vec) { for _ in 0..4 { r.frame(vec![]); } - r.drag(46.0, 336.0, 46.0, 311.0); // DRIVE + r.drag(46.0, 358.0, 46.0, 333.0); // DRIVE r.click(275.0, 63.0); // LIMIT off - r.drag(275.0, 524.0, 275.0, 510.0); // OUT GAIN (under the meters) - r.click(50.0, 63.0); // scene B - r.click(18.0, 401.0); // fx on - r.click(120.0, 443.0); // POST-SAT - r.click(135.0, 378.0); // tile REPEAT - r.click(275.0, 86.0); // morph direction - r.drag(275.0, 130.0, 275.0, 118.0); // morph DEPTH - r.click(275.0, 41.0); // oversample dropdown - r.click(266.0, 100.0); // 8x + r.drag(275.0, 546.0, 275.0, 532.0); // OUT GAIN (under the meters) + r.click(45.0, 63.0); // scene B + r.click(18.0, 423.0); // fx on + r.click(120.0, 465.0); // POST-SAT + r.click(135.0, 400.0); // tile REPEAT + r.click(275.0, 108.0); // morph direction + r.drag(275.0, 152.0, 275.0, 140.0); // morph DEPTH + r.click(212.0, 63.0); // oversample dropdown (scene row) + r.click(211.0, 122.0); // 8x r.click(275.0, 16.0); // BYPASS on r.click(275.0, 16.0); // and off - r.click(150.0, 63.0); // shaper selector menu - r.click(150.0, 63.0); + r.click(150.0, 85.0); // shaper selector menu + r.click(150.0, 85.0); r.click(110.0, 41.0); // preset dropdown r.click(110.0, 41.0); r.click(60.0, 12.0); // About page on @@ -169,8 +173,8 @@ fn script() -> (u64, Vec) { r.frame(vec![]); } r.click(60.0, 12.0); // and off - r.rclick(308.0, 500.0); // grip: size menu - r.rclick(308.0, 500.0); + r.rclick(308.0, 522.0); // grip: size menu + r.rclick(308.0, 522.0); r.reopen_editor(); r.frame(vec![]); (r.hash, r.log()) @@ -214,7 +218,7 @@ fn clicking_the_sat_readout_requests_the_level_match_and_its_result_writes_out_g for _ in 0..3 { r.frame(vec![]); } - r.click(190.0, 290.0); // the SAT readout in the plot's bottom right corner + r.click(190.0, 312.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); @@ -229,7 +233,7 @@ fn clicking_the_output_bars_cycles_the_range_without_writing_parameters() { r.frame(vec![]); } for _ in 0..5 { - r.click(292.0, 400.0); + r.click(292.0, 422.0); } assert!(r.log().is_empty(), "{:?}", r.log()); } @@ -241,7 +245,7 @@ fn the_scope_outline_mode_draws_and_differs_from_solid() { for _ in 0..6 { r.frame(vec![]); } - r.rclick(275.0, 240.0); // the vertical viz starts as the oscilloscope: right-click for the spectrum, where the fill shows + r.rclick(275.0, 262.0); // the vertical viz starts as the oscilloscope: right-click for the spectrum, where the fill shows for _ in 0..6 { r.frame(vec![]); } @@ -320,17 +324,16 @@ fn preferences_defaults_are_per_plugin_with_a_global_one_behind_a_chevron() { } // 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 + r.click(90.0, 457.0); // SET AS DEFAULT let own = load_defaults_for("satdiff").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, "SatDiff 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(146.0, 435.0); // chevron + r.click(146.0, 457.0); // chevron assert!(r.st.app.def_menu == 1, "the chevron opens the menu"); - r.click(80.0, 449.0); // SET AS GLOBAL DEFAULT + r.click(80.0, 471.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); @@ -340,15 +343,15 @@ fn preferences_defaults_are_per_plugin_with_a_global_one_behind_a_chevron() { // 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(190.0, 435.0); + r.click(190.0, 457.0); assert!(!r.params.light.load(Relaxed), "back on the global look"); assert!(!load_defaults_for("satdiff").unwrap().light && load_defaults().is_some()); // RESET GLOBAL DEFAULT (its chevron): nothing left, the factory look - r.click(288.0, 435.0); - r.click(190.0, 449.0); + r.click(288.0, 457.0); + r.click(190.0, 471.0); assert!(load_defaults().is_none() && load_defaults_for("satdiff").is_none(), "everything cleared"); // a click outside an open menu only closes it - r.click(146.0, 435.0); + r.click(146.0, 457.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); @@ -364,13 +367,13 @@ fn the_font_dropdown_opens_over_the_page_and_picks_a_face() { r.frame(vec![]); } let pal = r.params.palette_v2.load(Relaxed); - r.click(150.0, 413.0); // the FONT dropdown + r.click(150.0, 435.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 + r.click(150.0, 372.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(150.0, 435.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); @@ -397,7 +400,7 @@ fn the_theme_editor_page_has_a_filled_scope_in_stacking_order() { } #[test] -fn the_dice_rolls_a_different_scheme_each_time_and_scrolls_the_list_to_it() { +fn the_dice_generates_a_random_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 @@ -405,22 +408,21 @@ fn the_dice_rolls_a_different_scheme_each_time_and_scrolls_the_list_to_it() { 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 n0 = r.st.app.n_schemes() as i32; let mut seen = std::collections::BTreeSet::new(); - let mut prev = r.params.palette_v2.load(Relaxed); - for _ in 0..12 { + let mut slot = None; + for _ in 0..8 { 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) + // every roll lands on the one throwaway RANDOM entry, appended once to the user list + assert_eq!(r.st.app.n_schemes() as i32, n0 + 1); + assert_eq!(r.st.app.scheme_name(now as usize), satcomp_ui::appearance::RANDOM_NAME); + assert_eq!(*slot.get_or_insert(now), now); 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!(now >= sc && now < sc + 15, "scheme {now} not visible with the list at {sc}"); + seen.insert(format!("{:?}", r.st.app.scheme_cols(now as usize, false))); } - assert!(seen.len() >= 4, "twelve rolls should land on several different schemes: {seen:?}"); + assert!(seen.len() >= 7, "eight rolls should give different colours: {}", seen.len()); assert!(r.log().is_empty(), "UI-only, no host writes"); } @@ -448,9 +450,9 @@ fn dragging_the_derived_half_of_an_odd_curve_moves_the_real_point_the_right_way( for _ in 0..3 { r.frame(vec![]); } - r.click(225.0, 87.0); // pencil: opens the draw view (odd tool for the linear start curve) + r.click(225.0, 109.0); // pencil: opens the draw view (odd tool for the linear start curve) // the derived end point sits at (-1, -1): lower-left corner of the inset domain; pull it up to y = -0.5 - r.drag(32.0, 279.0, 32.0, 232.0); + r.drag(32.0, 301.0, 32.0, 254.0); let c = satcomp_dsp::shapers::Curve::from_points(&r.params.custom_curve.lock()); assert!(c.is_odd(), "an odd curve must stay odd: {:?}", c.pts()); assert!((c.eval(1.0) - 0.5).abs() < 0.05 && (c.eval(-1.0) + 0.5).abs() < 0.05, "f(1) = {}, f(-1) = {}", c.eval(1.0), c.eval(-1.0)); @@ -463,7 +465,7 @@ fn tile_shows_in_the_plot_and_dims_on_the_periodic_shapers() { let mut r = Rig::with_params(|p| { p.drive = FloatParam::new("Drive", 50.0, FloatRange::Linear { min: 0.0, max: 100.0 }); p.tile = IntParam::new("Tile", tile, IntRange::Linear { min: 0, max: 2 }); - p.shape = IntParam::new("Shape", shape, IntRange::Linear { min: 0, max: 14 }); + p.shape = IntParam::new("Shape", shape, IntRange::Linear { min: 0, max: satcomp_dsp::shapers::LAST_SHAPER }); }); for _ in 0..4 { r.frame(vec![]); @@ -490,7 +492,7 @@ fn the_whole_fx_dropdown_button_opens_the_menu() { for _ in 0..3 { r.frame(vec![]); } - r.click(100.0, 401.0); // the middle of the button, not the arrow + r.click(100.0, 423.0); // the middle of the button, not the arrow r.frame(vec![]); assert_ne!(r.hash, base, "the menu did not open"); } @@ -502,7 +504,7 @@ fn speed_is_inert_in_mix_and_live_in_the_detector_modes() { for _ in 0..3 { r.frame(vec![]); } - r.drag(275.0, 160.0, 275.0, 140.0); + r.drag(275.0, 182.0, 275.0, 162.0); r.log().iter().any(|l| l.starts_with("Morph Speed")) }; assert!(!drag_speed(2.0), "SPEED should be greyed out in MIX"); @@ -517,9 +519,9 @@ fn the_ab_switch_sends_shape_and_tile_edits_to_the_scene_being_edited() { for _ in 0..3 { r.frame(vec![]); } - r.click(226.0, 63.0); // selector right arrow - r.click(135.0, 378.0); // tile REPEAT - r.drag(46.0, 336.0, 46.0, 311.0); // DRIVE + r.click(226.0, 85.0); // selector right arrow + r.click(135.0, 400.0); // tile REPEAT + r.drag(46.0, 358.0, 46.0, 333.0); // DRIVE r.log() }; let a = on_scene(0); @@ -537,23 +539,122 @@ fn the_curve_handle_bends_a_segment_and_linear_straightens_the_rest() { // the fake host never applies a write; a real one has set the shaper to CUSTOM within a block of the pencil click, and the // draw view closes when the shaper is no longer CUSTOM, so the rig starts with it set use nih_plug::prelude::{IntParam, IntRange}; - let mut r = Rig::with_params(|p| p.shape = IntParam::new("Shape", 14, IntRange::Linear { min: 0, max: 14 })); + let mut r = Rig::with_params(|p| p.shape = IntParam::new("Shape", 14, IntRange::Linear { min: 0, max: satcomp_dsp::shapers::LAST_SHAPER })); for _ in 0..3 { r.frame(vec![]); } - r.click(225.0, 87.0); // pencil: opens the draw view (odd tool) - r.click(171.0, 87.0); // free draw tool + r.click(225.0, 109.0); // pencil: opens the draw view (odd tool) + r.click(171.0, 109.0); // free draw tool // the linear start curve has one segment: its handle is on the curve at the middle of the inset domain - r.drag(122.0, 188.0, 122.0, 160.0); + r.drag(122.0, 210.0, 122.0, 182.0); let c = r.params.curve_snapshot(); assert!(c.bend[0] > 0.2 && c.bend[0] < 0.45, "bend {:?}", &c.bend[..2]); assert!(c.eval(0.0) > 0.2, "the curve passes through the handle: {}", c.eval(0.0)); assert!(r.params.custom_curve_ext.lock().len() == 2, "handles are persisted: {:?}", r.params.custom_curve_ext.lock()); // double click on the handle straightens it again - r.click(122.0, 160.0); - r.click(122.0, 160.0); + r.click(122.0, 182.0); + r.click(122.0, 182.0); assert_eq!(r.params.curve_snapshot().bend[0], 0.0); // LINEAR | CURVE writes the curve's own flag - r.click(30.0, 87.0); + r.click(30.0, 109.0); assert!(r.params.curve_snapshot().linear); } + +#[test] +fn the_scene_row_copies_the_edited_scene_and_resets_it() { + use nih_plug::prelude::{FloatParam, FloatRange, IntParam, IntRange}; + let mut r = Rig::with_params(|p| { + p.drive = FloatParam::new("Drive", 40.0, FloatRange::Linear { min: 0.0, max: 100.0 }); + p.shape = IntParam::new("Shape", 3, IntRange::Linear { min: 0, max: satcomp_dsp::shapers::LAST_SHAPER }); + }); + r.params.store_curve(0, &satcomp_dsp::shapers::Curve::from_points(&[(-1.0, -0.5), (0.0, 0.0), (1.0, 0.5)])); + for _ in 0..3 { + r.frame(vec![]); + } + r.click(89.0, 63.0); // A>B + let log = r.log(); + assert!(log.iter().any(|l| l.starts_with("Drive B 0.400")), "{log:?}"); + assert!(log.iter().any(|l| l.starts_with("Shape B")), "{log:?}"); + assert!(!log.iter().any(|l| l.starts_with("Drive 0") || l.starts_with("Shape 0")), "scene A is the source, untouched: {log:?}"); + assert_eq!(r.params.curve_snapshot_b(), r.params.curve_snapshot(), "the drawn curve goes along"); + r.host.log.lock().clear(); + r.click(154.0, 63.0); // INIT A + let log = r.log(); + assert!(log.iter().any(|l| l.starts_with("Drive 0") && l.ends_with("0.000")), "{log:?}"); + assert!(!log.iter().any(|l| l.contains(" B ")), "scene B is untouched: {log:?}"); + assert!((r.params.curve_snapshot().eval(1.0) - 1.0).abs() < 1e-6, "a straight curve again"); + assert!((r.params.curve_snapshot_b().eval(1.0) - 0.5).abs() < 1e-6, "B keeps the copy"); +} + +#[test] +fn the_scope_wipe_restarts_promptly_on_dense_material() { + // a steady sine never makes the trigger's "rise above the recent level": the wipe used to wait a whole window (2 s at the + // 2 s step) at the bottom before sweeping again + let mut r = Rig::new(); + r.st.set_viz_win(9); // 2 s + let mut n = 0usize; + let (mut held, mut longest, mut sweeps, mut was_waiting) = (0, 0, 0, false); + for _ in 0..260 { + for _ in 0..1440 { + r.shared.tap.push(0.5 * (n as f32 * 0.0262).sin()); // 200 Hz at 48 kHz, 30 ms per frame + n += 1; + } + r.frame(vec![]); + let (_, waiting) = r.st.wipe_state(); + held = if waiting { held + 1 } else { 0 }; + longest = longest.max(held); + if was_waiting && !waiting { + sweeps += 1; + } + was_waiting = waiting; + } + assert!(sweeps >= 2, "the wipe should keep sweeping: {sweeps} restarts"); + assert!(longest <= 3, "held at the bottom for {longest} frames of 30 ms"); +} + +/// Help mode: the ? button toggles it; hovering then reports the control under the pointer (the edited scene's slot, an FX +/// cell by its type and label) and every target has copy. +#[test] +fn help_mode_reports_what_is_under_the_pointer() { + use satcomp_ui::help::HelpKey; + let mut r = Rig::new(); + for _ in 0..3 { + r.frame(vec![]); + } + r.click(227.0, 41.0); // ? + assert!(r.st.kit.help_on); + let hover = |r: &mut Rig, x: f32, y: f32, want: HelpKey| { + r.frame(vec![Event::PointerMoved(Rig::at(x, y))]); + assert_eq!(r.st.kit.help_hit.as_ref(), Some(&want), "at ({x}, {y})"); + assert!(super::ui::help_copy(&want).is_some(), "{want:?} has no copy"); + }; + hover(&mut r, 46.0, 349.0, HelpKey::Slot(2)); // DRIVE, scene A + hover(&mut r, 84.0, 381.0, HelpKey::Slot(3)); // BIAS (top half of the tile) + hover(&mut r, 84.0, 400.0, HelpKey::Slot(38)); // TILE (bottom half) + hover(&mut r, 200.0, 455.0, HelpKey::Id("fx:0:FREQ".into())); // diffusor FREQ, keyed by type + label + hover(&mut r, 275.0, 108.0, HelpKey::Id("morph".into())); + hover(&mut r, 275.0, 465.0, HelpKey::Id("in_out".into())); // I>O, between the meters and IN GAIN + hover(&mut r, 260.0, 400.0, HelpKey::Id("meters".into())); // the shortened meters + hover(&mut r, 275.0, 140.0, HelpKey::Slot(40)); // DEPTH / MIX + hover(&mut r, 120.0, 200.0, HelpKey::Id("plot".into())); + hover(&mut r, 275.0, 16.0, HelpKey::Id("BYPASS".into())); + hover(&mut r, 89.0, 63.0, HelpKey::Id("A>B".into())); + hover(&mut r, 19.0, 41.0, HelpKey::Id("save".into())); + hover(&mut r, 110.0, 41.0, HelpKey::Id("preset".into())); + hover(&mut r, 196.0, 41.0, HelpKey::Id("prev_next".into())); + hover(&mut r, 200.0, 545.0, HelpKey::Slot(57)); // output HPF (with its M / S switches) + r.click(45.0, 63.0); // edit scene B: the scene cells report B's slots + hover(&mut r, 46.0, 349.0, HelpKey::Slot(51)); + r.click(227.0, 41.0); + assert!(!r.st.kit.help_on); + r.frame(vec![Event::PointerMoved(Rig::at(46.0, 349.0))]); + assert_eq!(r.st.kit.help_hit, None); +} + +/// Multi-instance audit: idle frame cost and memory of one more open editor (`cargo test -p editor_frame_cost --release +/// -- --ignored --nocapture`). +#[test] +#[ignore] +fn editor_frame_cost() { + satcomp_ui::bench::frame_cost("satdiff", Rig::new, |r| r.frame(vec![])); +} diff --git a/rust/satdiff-plugin/src/gui/ui.rs b/rust/satdiff-plugin/src/gui/ui.rs index 2b70ea8..d426cd9 100644 --- a/rust/satdiff-plugin/src/gui/ui.rs +++ b/rust/satdiff-plugin/src/gui/ui.rs @@ -11,7 +11,7 @@ use crate::Shared; use super::{H, W}; use satcomp_ui::spectrum::Spectrum; use nih_plug::prelude::*; -use satcomp_dsp::shapers::{Curve, ShaperLut, CUSTOM, MAX_BEND, MIN_GAP, PT_CAP, SHAPER_NAMES}; +use satcomp_dsp::shapers::{shaper_name, shaper_step, shaper_step_clamped, Curve, ShaperLut, CUSTOM, MAX_BEND, MENU_ORDER, MIN_GAP, PT_CAP, SHAPER_NAMES}; /// Points the drawn curve may have (15 per half in the odd / even views). const DRAW_PTS: usize = PT_CAP; @@ -48,7 +48,6 @@ const FX_NAMES: [&str; 5] = ["DIFFUSOR", "PHASER", "FLANGER", "RINGMOD", "FREQ S const VIZ_WIN_MS: [u32; 11] = [5, 10, 20, 40, 80, 160, 250, 500, 1000, 2000, 4000]; /// 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,8 +72,12 @@ pub enum Dlg { } #[allow(dead_code)] // the horizontal transient scope is not part of the pass-1 layout; kept for later +mod help; mod scope; +#[cfg(test)] +pub(crate) use help::copy as help_copy; + pub struct State { /// widget interaction state (satcomp-ui); `State` derefs to it pub kit: Kit, @@ -89,7 +92,6 @@ pub struct State { meter_t: 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, @@ -138,6 +140,8 @@ pub struct State { // pass-1 layout state /// input meter (left of the plot): decaying levels, peak holds, clip lamp time ivl: f32, + /// I>O as displayed (eased) + io_disp: f32, ivr: f32, ihl_l: f32, ihl_r: f32, @@ -276,7 +280,6 @@ impl State { meter: satcomp_ui::meter::MeterReader::new(vec![satcomp_ui::meter::Kind::Peak(0.15), satcomp_ui::meter::Kind::State]), meter_t: 0.0, scope_t: 0.0, - asym_drag: (0.0, 0.0), app: AppState::new(), dummy_params: Arc::new(SatDiffParams::from_defaults(None)), dummy_shared: Arc::new(Shared::new()), @@ -309,6 +312,7 @@ impl State { rd_rms: 0.0, rd_sat: 0.0, ivl: 0.0, + io_disp: 0.0, ivr: 0.0, ihl_l: 0.0, ihl_r: 0.0, @@ -355,6 +359,17 @@ impl State { } } +#[cfg(test)] +impl State { + /// smoke tests: pick the vertical scope's window step, and read (wipe row, armed and waiting at the bottom) + pub(super) fn set_viz_win(&mut self, i: usize) { + self.viz_win = i; + } + pub(super) fn wipe_state(&self) -> (usize, bool) { + (self.sc_row, self.sc_wait) + } +} + impl State { /// Colours the canvas draws with: the editor preview while editing, else the active scheme. pub fn colors(&self) -> [f32; 9] { @@ -367,7 +382,7 @@ impl State { 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.face = satcomp_ui::canvas::font_sanitize(params.font.load(Ordering::Relaxed)); self.scope_cfg = params.scope.load(Ordering::Relaxed); self.restore_custom(params); } @@ -493,22 +508,13 @@ impl<'a> AppearanceUi<'a> for Gui<'a> { 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; + self.cv.set_face(face); } fn fft_solid(&self) -> Option { Some(self.env.params.fft_solid.load(Ordering::Relaxed)) @@ -522,14 +528,17 @@ impl<'a> AppearanceUi<'a> for Gui<'a> { fn about_paras(&self) -> &'static [&'static [&'static str]] { ABOUT_TEXT } + fn about_misc(&self) -> &'static [&'static str] { + ABOUT_MISC + } 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 + // the file must exist for the crate's current version (docs/manual/tools/build.py), or the plug-in does not compile Some(( concat!("SatDiff-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf"), - include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/manual/SatDiff-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf")), + include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/manual/SatDiff/SatDiff-Manual-v", env!("CARGO_PKG_VERSION"), ".pdf")), )) } fn draw_flow(&mut self, r: Rect, byp: bool) { @@ -556,17 +565,20 @@ 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 waveshaper saturator with phase coloration effects.", "Dedicated to sweet saturated sounds :>"], - &["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."], - &["Draw up to 30 points and drag the hollow handles to bend a segment. Pick LINEAR or CURVE, and mirror the curve odd or even with the tools at the top right of the plot. TILE folds or repeats the curve so BIAS walks through copies of it."], - &["A | B holds two complete saturators, each with its own shape, drive, bias, filters and tone. MORPH blends them: XFADE is a static crossfade, A>B and B>A let the input level move it, and SPEED sets how fast it follows."], - &["PHASE rotates the signal before the saturator. The colour slot adds a diffusor, phaser, flanger, ring mod or frequency shifter before (PRE-SAT) or after (POST-SAT) the saturator, and COLOR MIX sets how much of it you hear."], - &["LIMIT is a true-peak output limiter. GAIN MATCH trims the output back to the input level."], - &["Transient/GR meter: solid = limiter 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"], + &["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"], + &["Draw up to 30 points and drag the hollow handles to bend a segment. Pick [LINEAR] or [CURVE], and mirror the curve with [ODD] or [EVEN] at the top right of the plot. [TILE] folds or repeats the curve so [BIAS] walks through copies of it."], + &["[A | B] holds two complete saturators, each with its own shape, drive, bias, filters and tone. [A>B] ([B>A]) copies the scene you are editing over the other one, [INIT A] ([INIT B]) resets it."], + &["[MORPH] blends them: [XFADE] is a static crossfade, the detect modes let the input level move it, and [SPEED] sets how fast it follows."], + &["[PHASE] rotates the signal before the saturator. The color slot adds a [DIFFUSOR], [PHASER], [FLANGER], [RINGMOD] or [FREQ SHIFT] before ([PRE-SAT]) or after ([POST-SAT]) the saturator, and [COLOR MIX] sets how much of it you hear."], + &["[LIMIT] is a true-peak output limiter, the box under it shows its gain reduction. The output [HPF] cleans up the low end, on the mid, the side or both."], + &["== Meters ==", "[IN] hatched, [OUT] solid"], ]; +/// Lines under the shared Misc Controls block on the About page. +const ABOUT_MISC: &[&str] = &["[Click] a meter to cycle its range", "[Right-click] the view under [MORPH] to switch between spectrum and scope"]; /// Changelog, newest first. Keep each entry to two short sentences or fewer. const CHANGELOG: &[(&str, &[&str])] = &[ + ("v0.1.1", &["A scene row: A | B, A>B (copies the edited scene over the other), INIT A / B and the oversampling dropdown, with LIMIT beside them.", "Two new shapers, Ratio 2:1 and Ratio 4:1, and an ASYM per scene that evens out lopsided saturation.", "The vertical scope no longer stalls at the bottom on dense material.", "An I>O readout under the meters: the output level against the input.", "A help overlay: click ? at the end of the preset bar, then point at any control for a short description of it.", "Preferences: a sans-serif mode for the UI font (FONT MONO | SANS) with its own face for the numbers, and a STARTUP SCALE every new instance opens at. Shift + click on the logo rolls a random colour scheme and font.", "The draw view shows the stretch of the curve the signal reaches."]), ("v0.1", &["First version: a waveshaper saturator with two scenes (A | B) and MORPH, a drawable curve with handles, TILE, a phase rotator and a colour slot (diffusor, phaser, flanger, ring mod, frequency shifter).", "Output HPF, a true-peak limiter and GAIN MATCH come with it."]), ]; @@ -628,6 +640,15 @@ impl<'a> Gui<'a> { } } + /// Slot of the edited scene's ASYM: scene A's (62) or scene B's (63). + fn sc_asym(&self) -> usize { + if self.ab() == 1 { + 63 + } else { + 62 + } + } + fn sc_tile(&self) -> usize { if self.ab() == 1 { 45 @@ -636,12 +657,36 @@ impl<'a> Gui<'a> { } } + /// The scene parameters as (scene A slot, scene B slot): shaper, tile, drive, bias, HPF, LPF, tone, ASYM. + const SCENE_SLOTS: [(usize, usize); 8] = [(1, 44), (38, 45), (2, 51), (3, 52), (4, 53), (5, 54), (6, 55), (62, 63)]; + + /// A>B / B>A: copy scene `from` (its parameters and drawn curve) over the other scene. + fn copy_scene(&mut self, from: i32) { + for (a, b) in Self::SCENE_SLOTS { + let (src, dst) = if from == 1 { (b, a) } else { (a, b) }; + let v = self.sget(src); + self.click_set(dst, v); + } + let c = self.env.params.curve_of(from); + self.env.params.store_curve(1 - from, &c); + } + + /// INIT A / INIT B: scene `ab` back to the defaults (and a straight drawn curve); the other scene is untouched. + fn init_scene(&mut self, ab: i32) { + for (a, b) in Self::SCENE_SLOTS { + let n = if ab == 1 { b } else { a }; + let d = self.meta[n].def; + self.click_set(n, d); + } + self.env.params.store_curve(ab, &Curve::from_parts(&[(-1.0, -1.0), (1.0, 1.0)], &[])); + } + // ------------------------------------------------------------------ formatting fn fmt_slot(&self, n: usize, v: f32) -> String { // scene B's module settings read like scene A's let n = if (51..=55).contains(&n) { n - 49 } else if (60..=61).contains(&n) { n - 56 } else if n == 57 { 4 } else { n }; match n { - 2 | 25 | 11 | 36 | 37 | 40 | 41 | 43 | 47 => format!("{:.0}%", v), + 2 | 25 | 11 | 36 | 37 | 40 | 41 | 43 | 47 | 62 | 63 => format!("{:.0}%", v), 30 => format!("{:+.0}\u{b0}", v), 34 => { if v >= 10000.0 { @@ -692,19 +737,20 @@ impl<'a> Gui<'a> { fn selector(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32) { let aw = 20.0; let cy = y + h * 0.5; + self.help_slot(n, x, y, w, h); 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); + self.click_set(n, shaper_step_clamped(sel, if self.wheel > 0 { -1 } else { 1 }) 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 }); + self.click_set(n, shaper_step(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 }); + self.click_set(n, shaper_step(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); + let items = MENU_ORDER.iter().map(|&i| MItem { label: SHAPER_NAMES[i as usize].to_string(), kind: 0, id: i }).collect(); + self.menu = Some(Menu { kind: MenuKind::Shape, x, y: y + h, items, checked: sel, scroll: 0 }); } self.press = false; } @@ -723,7 +769,7 @@ impl<'a> Gui<'a> { 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(); + let name = shaper_name(sel).to_uppercase(); self.cv.textc(x + aw, y + ((h - 8.0) * 0.5).floor(), w - 2.0 * aw, &name); } @@ -731,6 +777,12 @@ impl<'a> Gui<'a> { /// header logo: left click = next colour scheme, right click = scheme dropdown fn logo(&mut self, x: f32, y: f32) { let hv = self.hit(x, y, 20.0, 20.0); + if hv && self.shift && self.press && self.act == 0 { + // shift + click: the dice, a random colour scheme and font + self.roll_dice(); + self.logo_pend = -1.0; + self.press = false; + } 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 { @@ -756,14 +808,19 @@ impl<'a> Gui<'a> { // 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 { + // (the dice plate is always the filled one: a die face in the background colour) + if self.light != hv || self.shift { self.cv.fill(x, y, 20.0, 20.0); self.cv.setbg(); } else { self.cv.boxr(x, y, 20.0, 20.0); self.setc(false); } - self.cv.logo_art(3, x, y); + if self.shift { + self.cv.dice_art(x, y); + } else { + self.cv.logo_art(3, x, y); + } self.setc(false); } @@ -778,6 +835,27 @@ impl<'a> Gui<'a> { /// Dry input level, vertical, hatched (every other row) so it reads apart from the solid output meter. Same ranges as the /// output meter (click the bars to cycle them); the IN lamp on top lights for 1 s after any sample over 0 dBFS. + /// I>O: output level against input level (slow), in dB, with a bar either side of the centre (full = 12 dB). + fn in_out(&mut self, x: f32, y: f32, w: f32, h: f32) { + let io = self.env.shared.io_db.load(Ordering::Relaxed); + self.io_disp += (io - self.io_disp) * 0.25; + let io = self.io_disp; + self.setc(false); + self.cv.boxr(x, y, w, h); + self.cv.set_font(1); + self.cv.text(x + 3.0, y + 3.0, "I>O"); + self.cv.textr_n(x, y + 3.0, w - 3.0, &format!("{:+.1}", if io.abs() < 0.05 { 0.0 } else { io })); + let cx = x + (w * 0.5).floor(); + let bl = ((io.clamp(-12.0, 12.0) / 12.0).abs() * (w * 0.5 - 3.0)).floor(); + if io >= 0.0 { + self.cv.fill(cx, y + h - 4.0, bl, 2.0); + } else { + self.cv.fill(cx - bl, y + h - 4.0, bl, 2.0); + } + self.cv.fill(cx, y + h - 6.0, 1.0, 5.0); + self.help_area("in_out", x, y, w, h); + } + fn in_vu(&mut self, x: f32, y: f32, w: f32, h: f32) { let sh = self.env.shared; let pa = sh.ipk[0].swap(0.0, Ordering::Relaxed); @@ -906,7 +984,7 @@ impl<'a> Gui<'a> { 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)); + self.cv.text_n(x + 2.0, (ty - 4.0).min(by + bh - 11.0), &format!("{}", -db)); } let clip = self.clip_lat; self.setc(clip); @@ -952,48 +1030,7 @@ impl<'a> Gui<'a> { self.setc(false); } self.cell1(57, x, y + hh - 1.0, w, h - hh + 1.0, ""); - } - - fn asym_cell(&mut self, x: f32, y: f32, w: f32, h: f32) { - let shape = ((self.sget(self.sc_shape()) + 0.5).floor() as i32).clamp(0, CUSTOM) as usize; - let cell = self.env.params.asym_cell(self.ab()).clone(); - let get = || cell.lock().get(shape).copied().unwrap_or(100.0); - let set = |v: f32| { - let mut g = cell.lock(); - if g.len() <= shape { - g.resize(SHAPER_NAMES.len(), 100.0); - } - g[shape] = v.clamp(0.0, 100.0); - }; - let hb = self.hit(x, y, w, h); - 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 on = self.act == ACT_ASYM; - self.setc(on); - self.cv.boxr(x, y, w, h); - self.cv.set_font(1); - self.cv.text(x + 3.0, y + 3.0, "ASYM"); - self.cv.set_font(2); - let v = get(); - self.cv.textc(x, y + (h * 0.4 + 1.0).floor(), w, &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); + self.help_slot(57, x, y, w, h); } /// BIAS slider (top half) with the three tile icons under it (bottom half): OFF (diagonal), MIRROR (triangle), REPEAT @@ -1001,6 +1038,9 @@ impl<'a> Gui<'a> { fn bias_tile(&mut self, x: f32, y: f32, w: f32, h: f32) { let bs = self.sc(3); let hh = (h * 0.5).floor(); + let ts = self.sc_tile(); + self.help_slot(bs, x, y, w, hh); + self.help_slot(ts, x, y + hh, w, h - hh); let ha = self.hit(x, y, w, hh); if ha && self.press && self.act == 0 { self.begin_drag(bs); @@ -1019,7 +1059,7 @@ impl<'a> Gui<'a> { let sb = self.fmt(bs, vb); let tb = self.n2t(bs, vb); self.cv.text(x + 3.0, y + 3.0, "BIAS"); - self.cv.textr(x, y + 3.0, w - 3.0, &sb); + self.cv.textr_n(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(false); // tile segments: dimmed and inert on the periodic shapers (Tri Fold, Sine Fold, Wrap, Asym Fold already tile themselves) @@ -1072,6 +1112,7 @@ impl<'a> Gui<'a> { /// Accent-filled cell (the MORPH block: DEPTH and SPEED); `on` false = outlined, background fill (depth 0). fn cell_acc(&mut self, n: usize, x: f32, y: f32, w: f32, h: f32, lbl: &str, on: bool, centred: bool) { + self.help_slot(n, x, y, w, h); let hv = self.hit(x, y, w, h); if hv && self.press && self.act == 0 { self.begin_drag(n); @@ -1094,7 +1135,7 @@ impl<'a> Gui<'a> { 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, &s); + self.cv.textc_n(x, y + (h * 0.4 + 1.0).floor(), w, &s); if centred { // centre-tapped: the bar grows from the middle (left = scene A, right = scene B) and a notch marks the centre let (cx, half) = (x + 2.0 + ((w - 4.0) * 0.5).floor(), (w - 4.0) * 0.5); @@ -1111,15 +1152,20 @@ impl<'a> Gui<'a> { /// Button with a hover effect (filled while the pointer is over it); lit: 0 off, 1 UI colour, 2 accent. fn hbtn(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8) -> bool { + self.hbtn_x(x, y, w, h, s, lit, true) + } + + /// `toggle`: false for a choice group's buttons (a lit one is the current choice: no hover recolour). + fn hbtn_x(&mut self, x: f32, y: f32, w: f32, h: f32, s: &str, lit: u8, toggle: bool) -> bool { + self.help_id(s, x, y, w, h); let hv = self.hit(x, y, w, h); let clicked = hv && self.press && self.act == 0; if lit > 0 || hv { - self.setc(lit > 1); + // an off button fills with the UI colour under the pointer; a lit one is already that colour, so under the pointer it + // swaps to the accent (and a red one to the UI colour): the hover always shows + self.setc((lit > 1) != (toggle && lit > 0 && hv)); self.cv.fill(x, y, w, h); self.cv.setbg(); - if lit > 0 && hv { - self.cv.boxr(x + 1.0, y + 1.0, w - 2.0, h - 2.0); - } } else { self.setc(false); self.cv.boxr(x, y, w, h); @@ -1138,7 +1184,7 @@ impl<'a> Gui<'a> { let bx = x + (w * i as f32 / n as f32).floor(); let bx2 = x + (w * (i + 1) as f32 / n as f32).floor(); let wi = bx2 - bx + if i + 1 < n { 1.0 } else { 0.0 }; - if self.hbtn(bx, y, wi, h, l, (sel == i) as u8) { + if self.hbtn_x(bx, y, wi, h, l, (sel == i) as u8, false) { res = Some(i); } } @@ -1257,7 +1303,7 @@ impl<'a> Gui<'a> { let pos = (self.sget(33) + 0.5).floor() as usize; let bh = ((h - 2.0) * 0.5).floor(); for (i, lab) in ["PRE-SAT", "POST-SAT"].iter().enumerate() { - if self.hbtn(x, y + i as f32 * (bh + 2.0), w, bh, lab, (pos == i) as u8) { + if self.hbtn_x(x, y + i as f32 * (bh + 2.0), w, bh, lab, (pos == i) as u8, false) { self.click_set(33, i as f32); } } @@ -1528,7 +1574,9 @@ impl<'a> Gui<'a> { let spr = (VIZ_WIN_MS[self.viz_win] as f64 * 0.001 * sr as f64 / rows as f64).max(1.0); let span = satcomp_dsp::TapRing::LEN - 256; let from = if head.wrapping_sub(self.sc_head) > span { head.wrapping_sub(span) } else { self.sc_head }; - let win_n = VIZ_WIN_MS[self.viz_win] as f64 * 0.001 * sr as f64; + // the armed wait gives up after one window or 50 ms, whichever is shorter: a trigger keeps the short windows steady, + // but waiting a whole long window (2 s at 2 s) for a rise that dense material never makes held the cursor at the bottom + let win_n = (VIZ_WIN_MS[self.viz_win] as f64 * 0.001).min(0.05) * sr as f64; for k in 0..head.wrapping_sub(from) { let v = tap.get(from.wrapping_add(k)); let av = v.abs(); @@ -1547,7 +1595,7 @@ impl<'a> Gui<'a> { continue; } if self.sc_wait { - // armed: start the next sweep on a rise well above the recent level, or after one window of nothing + // armed: start the next sweep on a rise well above the recent level, or after `win_n` of nothing let hit = av > 0.05 && av > self.sc_env * 2.2 + 0.02; self.sc_env += (av - self.sc_env) * 0.0007; self.sc_wait_n += 1.0; @@ -1609,7 +1657,7 @@ impl<'a> Gui<'a> { self.cv.set_font(1); self.cv.textc(x, y + 2.0, w, &l1); if let Some(l2) = l2 { - self.cv.textc(x, y + 12.0, w, &l2); + self.cv.textc_n(x, y + 12.0, w, &l2); } } self.setc(false); @@ -1643,7 +1691,7 @@ impl<'a> Gui<'a> { // each scene has its own drive, bias and ASYM: the plot draws the edited one, the underlay the other let (ab, ab2) = (self.ab(), 1 - self.ab()); let tuning = |a: i32| if a == 1 { (dsp.drive_b, dsp.bias_b, dsp.asym_b) } else { (dsp.drive, dsp.bias, dsp.asym) }; - let (drive, bias_pc, asym_arr) = tuning(ab); + let (drive, bias_pc, asym_v) = tuning(ab); let sat_on = drive > 0.0 || bias_pc != 0.0; let pre = (drive * 0.01 * 36.0 * 0.11512925).exp() as f32; let bias = (bias_pc * 0.01) as f32; @@ -1651,11 +1699,13 @@ impl<'a> Gui<'a> { self.lut.sync(shape, &curve); let (shape2, curve2) = dsp.scene_view(1 - self.ab()); self.lut2.sync(shape2, &curve2); - // static curve as heard: the shaper minus the part of its even half that ASYM removes - let ak = asym_arr[(shape.max(0) as usize).min(asym_arr.len() - 1)] * 0.01; + // static curve as heard: the shaper minus the share of its even part about the operating point (the bias) that ASYM + // removes, y = f(v) - (1 - k) (f(v) + f(2b - v)) / 2 (the DSP's high-passes pass the whole audio band) + let ak = asym_v.clamp(0.0, 100.0) * 0.01; + let b2 = 2.0 * bias_pc * 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) + l.eval(v) * (1.0 - r) - r * l.eval(b2 - 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 - 19.0, y + 3.0, 16.0, 16.0); @@ -1716,7 +1766,8 @@ impl<'a> Gui<'a> { let (drive2, bias_pc2, asym2) = tuning(ab2); let (pre2, bias2) = ((drive2 * 0.01 * 36.0 * 0.11512925).exp() as f32, (bias_pc2 * 0.01) as f32); if drive2 > 0.0 || bias_pc2 != 0.0 { - let ak2 = asym2[(shape2.max(0) as usize).min(asym2.len() - 1)] * 0.01; + let ak2 = asym2.clamp(0.0, 100.0) * 0.01; + let b22 = 2.0 * bias_pc2 * 0.01; let r2 = 0.5 * (1.0 - ak2); let prev = self.dk; self.set_dk(prev * 0.35); @@ -1726,7 +1777,7 @@ impl<'a> Gui<'a> { for i in 0..=un { let vx = -1.0 + 2.0 * i as f32 / un as f32; let v = (vx * pre2 + bias2) as f64; - let vy = ((self.lut2.eval(v) * (1.0 - r2) - r2 * self.lut2.eval(-v)) as f32).clamp(-1.0, 1.0); + let vy = ((self.lut2.eval(v) * (1.0 - r2) - r2 * self.lut2.eval(b22 - v)) as f32).clamp(-1.0, 1.0); let (qx, qy) = (x + (vx + 1.0) * 0.5 * (w - 1.0), y + (1.0 - (vy + 1.0) * 0.5) * (h - 1.0)); if i > 0 { self.cv.line(lx, ly, qx, qy); @@ -1774,14 +1825,14 @@ impl<'a> Gui<'a> { self.setc(false); self.cv.set_font(1); let s = format!("IN {:+.1}dB", tot); - self.cv.text(x + 3.0, y + 3.0, &s); + self.cv.text_n(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.cv.textr_n(x, y + h - 14.0, w - 3.0, &s); self.setc(false); } @@ -2065,6 +2116,31 @@ impl<'a> Gui<'a> { lx = qx; ly = qy; } + // the signal as it reaches the shaper: the stretch of the curve it covers at the current drive and bias (input peak + // x drive around the bias point), redrawn as a dimmed accent line over the curve (a line only: a dot would sit on the + // handles). It shows how much of a detailed curve a low drive actually uses. + { + let (g, b, pk, on): (f64, f64, f64, bool) = { let d = self.env.dsp; let (dr, bi) = if self.ab() == 1 { (d.drive_b, d.bias_b) } else { (d.drive, d.bias) }; ((dr * 0.01 * 36.0 * 0.11512925).exp(), bi * 0.01, self.mval(0).min(1.0) as f64, dr > 0.0 || bi != 0.0) }; + if on && pk > 0.0005 { + let (lo, hi) = ((b - pk * g).max(-1.0) as f32, (b + pk * g).min(1.0) as f32); + if hi > lo { + let keep = self.dk; + self.set_dk(keep * 0.6); + self.setc(true); + let m = ((hi - lo) * 48.0).ceil().max(2.0) as i32; + let (mut ax, mut ay) = (px(lo), py(c.eval(lo as f64) as f32)); + for j in 1..=m { + let vx = lo + (hi - lo) * j as f32 / m as f32; + let (qx, qy) = (px(vx), py(c.eval(vx as f64) as f32)); + self.cv.line(ax, ay, qx, qy); + ax = qx; + ay = qy; + } + self.set_dk(keep); + self.setc(false); + } + } + } self.setc(false); let hot = if self.act == 160 { Some(self.cpt) } else { pick(self, &hv) }; let nh = hv.len(); @@ -2138,7 +2214,7 @@ impl<'a> Gui<'a> { let _ = (hp, hs, he); let tool = if !sym { "FREE" } else if self.even { "EVEN" } else { "ODD" }; self.cv.text(x + 3.0, y + h - 11.0, &format!("DRAW {tool}")); - self.cv.textr(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, DRAW_PTS)); + self.cv.textr_n(x, y + h - 11.0, w - 3.0, &format!("{}/{} PTS", c.n, DRAW_PTS)); } fn cur_scale(&self) -> f32 { @@ -2329,18 +2405,13 @@ impl<'a> Gui<'a> { /// 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); + // the shared layer decides what a load writes (the CLI applies the same list) + for (n, v) in p.writes() { self.click_set(n, v); } - // absent curve = linear (deterministic: loading a preset never keeps the previous preset's curve) - self.env.params.store_curve(0, &Curve::from_parts(&p.curve, &p.curve_ext)); - self.env.params.store_curve(1, &Curve::from_parts(&p.curve_b, &p.curve_ext_b)); - *self.env.params.asym.lock() = satcomp_dsp::shapers::asym_from(&p.asym).iter().map(|&v| v as f32).collect(); - *self.env.params.asym_b.lock() = satcomp_dsp::shapers::asym_from(&p.asym_b).iter().map(|&v| v as f32).collect(); + let [a, b] = p.drawn(); + self.env.params.store_curve(0, &a); + self.env.params.store_curve(1, &b); self.set_preset_name(&p.name); self.base = None; self.hold_until = self.now + 0.6; @@ -2372,35 +2443,13 @@ impl<'a> Gui<'a> { return true; } } - Curve::from_parts(&b.curve, &b.curve_ext) != self.env.params.curve_snapshot() || Curve::from_parts(&b.curve_b, &b.curve_ext_b) != self.env.params.curve_snapshot_b() || satcomp_dsp::shapers::asym_from(&b.asym) != self.env.params.asym_snapshot() || satcomp_dsp::shapers::asym_from(&b.asym_b) != self.env.params.asym_snapshot_b() + Curve::from_parts(&b.curve, &b.curve_ext) != self.env.params.curve_snapshot() || Curve::from_parts(&b.curve_b, &b.curve_ext_b) != self.env.params.curve_snapshot_b() } 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(); - p.curve_ext = c.ext(); - } - let cb = self.env.params.curve_snapshot_b(); - if cb != Curve::linear() { - p.curve_b = cb.pts().to_vec(); - p.curve_ext_b = cb.ext(); - } - 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(); - } - let ab_ = self.env.params.asym_snapshot_b(); - if ab_.iter().any(|&v| v != 100.0) { - p.asym_b = ab_.iter().map(|&v| v as f32).collect(); - } - p + // the shared layer decides what a preset keeps (the CLI's --save-preset writes the same) + let curves = [self.env.params.curve_snapshot(), self.env.params.curve_snapshot_b()]; + Preset::capture(name, |n| self.sget(n), &curves) } fn preset_count(&self) -> usize { @@ -2547,22 +2596,24 @@ impl<'a> Gui<'a> { /// Preset bar: save icon | name dropdown | prev next (INIT lives in the preset list). fn preset_bar(&mut self, y: f32, h: f32) { + // the bar spans 10..236: save 18 | name 150 | prev 18 | next 18 | gap 4 | ? 18 + let (sx, nx, nw, ax, qx) = (10.0, 28.0, 150.0, 178.0, 218.0); // save icon - if self.hbtn(10.0, y, 28.0, h, "", 0) { + if self.hbtn(sx, y, h, h, "", 0) { self.pending = 2; } - let hv = self.hit(10.0, y, 28.0, h); + self.help_area("save", sx, y, h, h); + let hv = self.hit(sx, y, h, h); if hv { self.cv.setbg(); } else { self.setc(false); } - self.cv.boxr(18.0, y + 3.0, 11.0, 11.0); - self.cv.fill(21.0, y + 3.0, 5.0, 4.0); - self.cv.boxr(20.0, y + 8.0, 7.0, 6.0); + self.cv.boxr(sx + 4.0, y + 3.0, 11.0, 11.0); + self.cv.fill(sx + 7.0, y + 3.0, 5.0, 4.0); + self.cv.boxr(sx + 6.0, y + 8.0, 7.0, 6.0); self.setc(false); // name -> dropdown - let (nx, nw) = (38.0, 154.0); let name = self.preset_name(); let shown = if name.is_empty() || name == "INIT" { "-- INIT --".to_string() } else { name }; let hv = self.hit(nx, y, nw, h); @@ -2570,6 +2621,7 @@ impl<'a> Gui<'a> { self.open_preset_menu(nx, y + h); self.press = false; } + self.help_area("preset", nx, y, nw, h); self.setc(false); self.cv.boxr(nx, y, nw, h); self.cv.set_font(2); @@ -2582,18 +2634,20 @@ impl<'a> Gui<'a> { t = format!("*{t}*"); } self.cv.textc(nx, y + ((h - 8.0) * 0.5).floor(), nw, &t); + self.help_btn(qx, y, h); // prev / next for (i, dir) in [(0, -1), (1, 1)] { - let (x, bw) = if i == 0 { (192.0, 22.0) } else { (214.0, 22.0) }; - if self.hbtn(x, y, bw, h, "", 0) { + let x = ax + i as f32 * h; + if self.hbtn(x, y, h, h, "", 0) { self.step_preset(dir); } - if self.hit(x, y, bw, h) { + self.help_area("prev_next", x, y, h, h); + if self.hit(x, y, h, h) { self.cv.setbg(); } else { self.setc(false); } - let (cx, cy) = (x + bw * 0.5, y + h * 0.5); + let (cx, cy) = (x + h * 0.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 { @@ -2627,7 +2681,7 @@ impl<'a> Gui<'a> { self.cv.set_font(2); // TILE on the drawn curve runs at x4 at least: show what is actually running let forced = self.env.dsp.tile_active(); - self.cv.textc(x, y + ((h - 8.0) * 0.5).floor(), w, &format!("{}x{}", 1 << if forced { os.max(2) } else { os }, if forced && os < 2 { "*" } else { "" })); + self.cv.textc_n(x, y + ((h - 8.0) * 0.5).floor(), w, &format!("{}x{}", 1 << if forced { os.max(2) } else { os }, if forced && os < 2 { "*" } else { "" })); self.setc(false); } @@ -2698,7 +2752,7 @@ impl<'a> Gui<'a> { } 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.textc_n(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; } @@ -2761,7 +2815,7 @@ impl<'a> Gui<'a> { let lim_on = self.sget(24) > 0.5; self.gr_update(); - // ---------- header row: logo, title, size, BYPASS + // ---------- header row: logo, title, BYPASS self.set_dk(1.0); self.logo(10.0, 6.0); self.setc(false); @@ -2776,80 +2830,106 @@ impl<'a> Gui<'a> { } // hovering highlights the lockup (a UI-coloured plate behind it, the text in the background colour): it opens About self.cv.header_title(34.0, 16.0, 20.0, "SATDIFF", &ver, 152.0, over); + self.help_area("logo", 10.0, 6.0, 20.0, 20.0); + self.help_area("title", 31.0, 6.0, tw + 6.0, 20.0); self.setc(false); - let label = format!("{:.0}%", self.cur_scale() * 100.0); - // right edge on 236 like the preset arrows and the shape selector below it - if self.hbtn(190.0, 6.0, 46.0, 20.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, 190.0, 26.0, items, cur); - } if self.hbtn(244.0, 6.0, 62.0, 20.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) + // ---------- preset row, the UI scale beside it (the About tabs take the preset bar's place while the About page is open) let ab = self.app.about > 0; if !ab { self.preset_bar(32.0, 18.0); - self.os_dropdown(244.0, 32.0, 62.0, 18.0); + } + if !ab { + let label = format!("{:.0}%", self.cur_scale() * 100.0); + if self.hbtn(244.0, 32.0, 62.0, 18.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, 244.0, 50.0, items, cur); + } + self.help_area("ui_scale", 244.0, 32.0, 62.0, 18.0); } self.set_dk(if byp { 0.5 } else { 1.0 }); if ab { - self.draw_about(Rect::new(10.0, 54.0, 296.0, 438.0), byp); + self.draw_about(Rect::new(10.0, 54.0, 296.0, 460.0), byp); } if !ab { let bd = if byp { 0.5 } else { 1.0 }; - // ---------- scene row: A | B, shape selector, LIMIT + // ---------- scene row: A | B (the edited scene), copy it to the other scene, reset it, oversampling; LIMIT self.set_dk(bd); let abi = (self.sget(42) + 0.5).floor() as usize; - if let Some(i) = self.seg(10.0, 54.0, 52.0, 18.0, &["A", "B"], abi) { + if let Some(i) = self.seg(10.0, 54.0, 44.0, 18.0, &["A", "B"], abi) { self.click_set(42, i as f32); self.press = false; } - let sl = self.sc_shape(); - self.selector(sl, 70.0, 54.0, 166.0, 18.0); - let gr = self.rd_gr; - let lim_lab = if lim_on && gr > 0.1 { format!("-{:.1}", gr) } else { "LIMIT".to_string() }; - if self.hbtn(244.0, 54.0, 62.0, 18.0, &lim_lab, lim_on as u8) { + self.help_area("ab", 10.0, 54.0, 44.0, 18.0); + let (me, other) = if abi == 1 { ("B", "A") } else { ("A", "B") }; + if self.hbtn(59.0, 54.0, 60.0, 18.0, &format!("{me}>{other}"), 0) { + self.copy_scene(abi as i32); + } + if self.hbtn(124.0, 54.0, 60.0, 18.0, &format!("INIT {me}"), 0) { + self.init_scene(abi as i32); + } + self.os_dropdown(189.0, 54.0, 47.0, 18.0); + self.help_area("os", 189.0, 54.0, 47.0, 18.0); + if self.hbtn(244.0, 54.0, 62.0, 18.0, "LIMIT", lim_on as u8) { self.click_set(24, if lim_on { 0.0 } else { 1.0 }); } + // ---------- shape row: the edited scene's shaper; the limiter's gain reduction under LIMIT (as SatFilt) + let sl = self.sc_shape(); + self.selector(sl, 10.0, 76.0, 226.0, 18.0); + self.setc(false); + self.cv.boxr(244.0, 76.0, 62.0, 18.0); + self.cv.set_font(1); + let t = if lim_on { format!("-{:.1}", self.rd_gr) } else { "---".into() }; + self.cv.textc_n(244.0, 81.0, 62.0, &t); + self.help_area("gr_box", 244.0, 76.0, 62.0, 18.0); + // ---------- plot (the sat plot / draw view); right column: MORPH, then the viz down to the plot's bottom - self.draw_plot(10.0, 76.0, 226.0, 226.0); - self.morph_block(244.0, 76.0, 62.0); - self.vviz(244.0, 191.0, 62.0, 111.0); + self.draw_plot(10.0, 98.0, 226.0, 226.0); + self.help_area(if self.curve_edit { "draw" } else { "plot" }, 10.0, 98.0, 226.0, 226.0); + self.help_area("draw", 217.0, 101.0, 16.0, 16.0); + self.morph_block(244.0, 98.0, 62.0); + self.help_area("morph", 244.0, 98.0, 62.0, 36.0); + self.vviz(244.0, 213.0, 62.0, 111.0); + self.help_area("viz", 244.0, 213.0, 62.0, 111.0); // ---------- sat cells: three columns of 72 (just wide enough for the longest label + value pair) if editing { self.theme_cells(CellGrid { x0: 10.0, y0: 308.0, cw: 72.0, ch: 38.0, px: 77.0, py: 42.0 }); } else { let (s2, s4, s5, s6) = (self.sc(2), self.sc(4), self.sc(5), self.sc(6)); - self.cell(s2, 10.0, 308.0, 72.0, 38.0, "DRIVE"); - self.asym_cell(87.0, 308.0, 72.0, 38.0); - self.cell2(s4, s5, 164.0, 308.0, 72.0, 38.0, "HPF", "LPF"); - self.bias_tile(10.0, 350.0, 149.0, 38.0); - self.cell(s6, 164.0, 350.0, 72.0, 38.0, "TONE"); + self.cell(s2, 10.0, 330.0, 72.0, 38.0, "DRIVE"); + self.cell(self.sc_asym(), 87.0, 330.0, 72.0, 38.0, "ASYM"); + self.cell2(s4, s5, 164.0, 330.0, 72.0, 38.0, "HPF", "LPF"); + self.bias_tile(10.0, 372.0, 149.0, 38.0); + self.cell(s6, 164.0, 372.0, 72.0, 38.0, "TONE"); } // ---------- colour section: fx row (enable box + type) with PHASE beside it, viewport + PRE-SAT / POST-SAT + COLOR #1, a row // of COLOR #2..#4, then (below a divider) COLOR MIX and SAT MIX. IN GAIN and OUT GAIN sit under the meters. - self.fx_row(10.0, 392.0, 149.0, 18.0); + self.fx_row(10.0, 414.0, 149.0, 18.0); + self.help_area("fx_type", 10.0, 414.0, 149.0, 18.0); let fx_on = self.sget(31) > 0.5; self.set_dk(if fx_on { bd } else { bd * 0.5 }); - self.fx_viz(10.0, 414.0, 72.0, 38.0); - self.fx_pos_btns(87.0, 414.0, 72.0, 38.0); + self.fx_viz(10.0, 436.0, 72.0, 38.0); + self.help_area("fx_viz", 10.0, 436.0, 72.0, 38.0); + self.fx_pos_btns(87.0, 436.0, 72.0, 38.0); self.set_dk(bd); if !editing { - self.cell1(30, 164.0, 392.0, 72.0, 18.0, "PHASE"); + self.cell1(30, 164.0, 414.0, 72.0, 18.0, "PHASE"); self.set_dk(if fx_on { bd } else { bd * 0.5 }); // four slots, each a normal cell or a dual one. Diffusor: FREQ, Q, STAGES, SPREAD. Phaser: FREQ | RATE, DEPTH | STAGES, // FDBK, WIDTH. Flanger: DELAY | RATE, DEPTH, FDBK, WIDTH. Ringmod: FREQ, SHAPE, AMOUNT, HPF | LPF. Freq shift: SHIFT, // DELAY | FDBK, WIDTH, HPF | LPF (the last two trim the wide-band wet signal) - let slots = [(164.0, 414.0), (10.0, 456.0), (87.0, 456.0), (164.0, 456.0)]; + let slots = [(164.0, 436.0), (10.0, 478.0), (87.0, 478.0), (164.0, 478.0)]; type C = (usize, &'static str, Option<(usize, &'static str)>); - let cells: &[C] = match (self.sget(32) + 0.5).floor() as i32 { + let fx_ty = (self.sget(32) + 0.5).floor() as i32; + let cells: &[C] = match fx_ty { 1 => &[(34, "FREQ", Some((46, "RATE"))), (47, "DEPTH", Some((36, "STAGES"))), (48, "FDBK", None), (43, "WIDTH", None)], 2 => &[(49, "DLY", Some((46, "RATE"))), (47, "DEPTH", None), (48, "FDBK", None), (43, "WIDTH", None)], 3 => &[(34, "FREQ", None), (50, "SHAPE", None), (47, "AMOUNT", None), (60, "HPF", Some((61, "LPF")))], @@ -2859,31 +2939,43 @@ impl<'a> Gui<'a> { for (i, c) in cells.iter().enumerate() { let (x, y) = slots[i]; match c.2 { - Some(b) => self.cell2(c.0, b.0, x, y, 72.0, 38.0, c.1, b.1), - None => self.cell(c.0, x, y, 72.0, 38.0, c.1), + Some(b) => { + self.cell2(c.0, b.0, x, y, 72.0, 38.0, c.1, b.1); + self.help_fx(fx_ty, c.1, x, y, 72.0, 19.0); + self.help_fx(fx_ty, b.1, x, y + 19.0, 72.0, 19.0); + } + None => { + self.cell(c.0, x, y, 72.0, 38.0, c.1); + self.help_fx(fx_ty, c.1, x, y, 72.0, 38.0); + } } } // divider between the colour section and the mix / gain stage, with a little more air around it self.set_dk(bd); self.setc(false); - self.cv.fill(10.0, 499.0, 226.0, 1.0); + self.cv.fill(10.0, 521.0, 226.0, 1.0); self.set_dk(if fx_on { bd } else { bd * 0.5 }); - self.cell(37, 10.0, 505.0, 72.0, 38.0, "COLOR MIX"); + self.cell(37, 10.0, 527.0, 72.0, 38.0, "COLOR MIX"); self.set_dk(bd); - self.cell(25, 87.0, 505.0, 72.0, 38.0, "SAT MIX"); - self.out_hp_cell(164.0, 505.0, 72.0, 38.0); - self.cell(27, 244.0, 456.0, 62.0, 38.0, "IN GAIN"); - self.cell_o(22, 244.0, 505.0, 62.0, 38.0, "OUT GAIN"); + self.cell(25, 87.0, 527.0, 72.0, 38.0, "SAT MIX"); + self.out_hp_cell(164.0, 527.0, 72.0, 38.0); + self.cell(27, 244.0, 478.0, 62.0, 38.0, "IN GAIN"); + self.cell_o(22, 244.0, 527.0, 62.0, 38.0, "OUT GAIN"); } // ---------- meters (input hatched, output solid) down the right column beside the cell rows - self.in_vu(244.0, 308.0, 27.0, 144.0); - self.out_vu(279.0, 308.0, 27.0, 144.0); + self.in_vu(244.0, 330.0, 27.0, 121.0); + self.out_vu(279.0, 330.0, 27.0, 121.0); + self.help_area("meters", 244.0, 330.0, 62.0, 121.0); + // I>O between the meters and IN GAIN (SatFilt's readout) + self.in_out(244.0, 455.0, 62.0, 20.0); } self.set_dk(1.0); self.resize_grip(); + self.help_area("ui_scale", W - 16.0, H - 16.0, 16.0, 16.0); self.menu_draw(); + self.help_draw(); self.poll_dialog(); self.run_pending(); if editing { @@ -2892,10 +2984,10 @@ impl<'a> Gui<'a> { if osk { self.mask_in(); // picker stays visible underneath but inert } - self.theme_picker(Rect::new(10.0, 76.0, 296.0, 226.0)); + self.theme_picker(Rect::new(10.0, 98.0, 296.0, 226.0)); if osk { self.unmask_in(); - self.theme_osk(Rect::new(10.0, 76.0, 296.0, 226.0)); + self.theme_osk(Rect::new(10.0, 98.0, 296.0, 226.0)); } } } diff --git a/rust/satdiff-plugin/src/gui/ui/help.rs b/rust/satdiff-plugin/src/gui/ui/help.rs new file mode 100644 index 0000000..d6e6fa4 --- /dev/null +++ b/rust/satdiff-plugin/src/gui/ui/help.rs @@ -0,0 +1,186 @@ +//! Help overlay for SatDiff: maps what the pointer is over (`HelpKey`) to its bubble. Shared entries come from +//! `satcomp_ui::help::common`; the copy is drafted in docs/internal/helpcopy/satdiff.md and common.md. +//! Scene cells report the edited scene's slot (A or B), both map to the same bubble. The colour FX cells reuse one parameter +//! under different labels per FX type, so they report `fx::