diff --git a/.github/workflows/ast-grep.yml b/.github/workflows/ast-grep.yml new file mode 100644 index 00000000..6d407537 --- /dev/null +++ b/.github/workflows/ast-grep.yml @@ -0,0 +1,26 @@ +# Structural rules for the command-line code (RFC-0012): lint/ast-grep's rule tests, then a scan. +# Seconds, no Rust build. +name: ast-grep + +on: + push: + branches: [main] + paths: ["lint/ast-grep/**", "apps/soundcraft-cli/**", "crates/automation/src/args.rs", "apps/soundcraft/src/launch_args.rs", "apps/soundcraft/src/main.rs", ".github/workflows/ast-grep.yml"] + pull_request: + paths: ["lint/ast-grep/**", "apps/soundcraft-cli/**", "crates/automation/src/args.rs", "apps/soundcraft/src/launch_args.rs", "apps/soundcraft/src/main.rs", ".github/workflows/ast-grep.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ast-grep-${{ github.ref }} + cancel-in-progress: true + +jobs: + scan: + # Tracked at @main like the other shared workflows. + uses: storytold/craft-common-actions/.github/workflows/ast-grep.yml@main + with: + config: lint/ast-grep/sgconfig.yml + paths: apps/soundcraft-cli crates/automation/src/args.rs apps/soundcraft/src/launch_args.rs apps/soundcraft/src/main.rs diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index f54b0538..ea61d843 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -21,3 +21,27 @@ jobs: lint: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + + windows-install-policy: + timeout-minutes: 10 + name: Windows installation policy (no app build) + runs-on: windows-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install the pinned packaging toolchain + shell: pwsh + run: | + $tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix' + dotnet tool install --tool-path $tools wix --version 5.0.2 + if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' } + $tools >> $env:GITHUB_PATH + $policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json + foreach ($extension in @($policy.extensions)) { + & (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2" + if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." } + } + - name: Build and check non-executable installer fixtures + shell: pwsh + run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index d389f4d1..eae50d1a 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -26,8 +26,10 @@ permissions: jobs: windows-arm64: - # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main + # Immutable supporting workflow revision until the new install contract lands upstream. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f with: app-name: soundcraft app-dir: SoundCraft + install-relative-path: Programs/ArtCraft/SoundCraft + install-scope: perUser diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index e6010d2a..00927097 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -55,3 +55,4 @@ here. The subset uses default_fonts; the parent face uses monochrome_emoji_fonts | `assets/app-icon/soundcraft.ico` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 | | `assets/app-icon/hicolor/` | SoundCraft contributors | original, rendered from `icon.svg` (16–512 px PNGs and the scalable SVG) | MIT OR Apache-2.0 | | `docs/images/` | SoundCraft contributors | screenshots of SoundCraft rendered from the synthesised demo session | MIT OR Apache-2.0 | +| `crates/audio-io/tests/fixtures/` | SoundCraft contributors | original test tones and silence generated with ffmpeg (sine) or by hand; commands in `crates/audio-io/tests/fixtures/README.md` | MIT OR Apache-2.0 | diff --git a/CLAUDE.md b/CLAUDE.md index b5c917a3..9559f795 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1 +1,5 @@ Read `AGENTS.md`: it is the entry point for agents in this repo. + +New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit +`[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes +before modules or other crate items; crate-level `//!` documentation may precede them. diff --git a/Cargo.lock b/Cargo.lock index 159f4438..b25f84b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -200,6 +200,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -738,12 +788,71 @@ dependencies = [ "libloading 0.8.9", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + [[package]] name = "clap-sys" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a76abbdb2907f6fd97fb6bc0b7be96b77d328f2dd9669d1075cc03369ed22154" +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clap_mangen" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "211d617eaa4b735c96c9e0228fcbdb5120ef623f2b8cb67ffb84c3e02dbc28a4" +dependencies = [ + "clap", + "roff", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -753,6 +862,15 @@ dependencies = [ "error-code", ] +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -773,6 +891,12 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "colored" version = "2.2.0" @@ -934,12 +1058,40 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=db19c373c8d59a545972ca340987aecfb3611a4b#db19c373c8d59a545972ca340987aecfb3611a4b" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" + +[[package]] +name = "craft-fonts-build" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" + +[[package]] +name = "craft-i18n" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "fixed_decimal", + "icu_decimal", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_plurals", + "icu_properties", + "icu_provider", + "icu_provider_adapters", + "icu_provider_blob", + "log", + "objc2-foundation 0.3.2", + "sys-locale", + "unicode-bidi", + "windows-registry", + "writeable", +] [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=db19c373c8d59a545972ca340987aecfb3611a4b#db19c373c8d59a545972ca340987aecfb3611a4b" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "thiserror 2.0.21", ] @@ -947,20 +1099,28 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=db19c373c8d59a545972ca340987aecfb3611a4b#db19c373c8d59a545972ca340987aecfb3611a4b" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ + "craft-fonts-build", + "craft-i18n", "egui", + "epaint", + "js-sys", "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "serde", + "skrifa", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", ] [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=db19c373c8d59a545972ca340987aecfb3611a4b#db19c373c8d59a545972ca340987aecfb3611a4b" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "chrono", "dunce", @@ -1460,6 +1620,17 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "smallvec", + "writeable", +] + [[package]] name = "fixedbitset" version = "0.5.7" @@ -1857,6 +2028,12 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -1887,9 +2064,9 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "icu_collections" -version = "2.4.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", @@ -1900,43 +2077,110 @@ dependencies = [ ] [[package]] -name = "icu_locale_core" -version = "2.4.0" +name = "icu_decimal" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +checksum = "9eb8f655bba2d0c0459e43a5b0e6cd3cd388109898fb3d85d048165e8b0abd08" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "serde", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] [[package]] -name = "icu_normalizer" -version = "2.4.0" +name = "icu_locale_fallback" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" dependencies = [ "icu_collections", "icu_normalizer_data", "icu_properties", "icu_provider", "smallvec", + "utf16_iter", + "utf8_iter", + "write16", "zerovec", ] [[package]] name = "icu_normalizer_data" -version = "2.4.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_pattern" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc43ce0e76ee8cb0482dc6e2dbb9b76278e8038f45daabf2a2877577e2ceb18f" +dependencies = [ + "displaydoc", + "either", + "serde", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_plurals" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e475e6766ef87b1d3c1f97be6363995b0bfaeddbc789671615df598a97ff0593" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_provider", + "serde", + "zerovec", +] [[package]] name = "icu_properties" -version = "2.4.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" dependencies = [ "displaydoc", "icu_collections", @@ -1949,18 +2193,21 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.4.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" [[package]] name = "icu_provider" -version = "2.4.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", + "postcard", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -1968,6 +2215,30 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_provider_adapters" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df887bc4f55dbc773c7c45a0c7dfa75be886f7b7812830a71ab7271cc1801820" +dependencies = [ + "icu_locale_fallback", + "icu_provider", +] + +[[package]] +name = "icu_provider_blob" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5916b44fac319d3f58e4d8d805a627df19e27937b582cd99fcde3bb6b7ce1b0e" +dependencies = [ + "icu_provider", + "postcard", + "serde", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "idna" version = "1.1.0" @@ -2034,6 +2305,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.13.0" @@ -2259,6 +2536,9 @@ name = "litemap" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +dependencies = [ + "serde_core", +] [[package]] name = "litrs" @@ -2906,6 +3186,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "open" version = "5.4.5" @@ -3188,12 +3474,24 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -3518,6 +3816,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roff" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3975,9 +4279,10 @@ dependencies = [ [[package]] name = "soundcraft" -version = "0.13.1" +version = "0.14.0" dependencies = [ "chrono", + "clap", "craft-update", "eframe", "egui", @@ -3987,6 +4292,8 @@ dependencies = [ "objc2-app-kit 0.3.2", "rfd", "serde_json", + "soundcraft-audio-io", + "soundcraft-automation", "soundcraft-engine", "soundcraft-playback", "soundcraft-ui-egui", @@ -3996,7 +4303,7 @@ dependencies = [ [[package]] name = "soundcraft-au-host" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "serde", @@ -4006,7 +4313,7 @@ dependencies = [ [[package]] name = "soundcraft-audio-io" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "proptest", @@ -4018,17 +4325,20 @@ dependencies = [ [[package]] name = "soundcraft-automation" -version = "0.13.1" +version = "0.14.0" dependencies = [ + "clap", "log", "serde_json", + "soundcraft-audio-io", "soundcraft-engine", "soundcraft-time", + "thiserror 2.0.21", ] [[package]] name = "soundcraft-clap-host" -version = "0.13.1" +version = "0.14.0" dependencies = [ "clap-sys", "libloading 0.9.0", @@ -4041,18 +4351,24 @@ dependencies = [ [[package]] name = "soundcraft-cli" -version = "0.13.1" +version = "0.14.0" dependencies = [ + "clap", + "clap_complete", + "clap_mangen", + "same-file", + "serde", "serde_json", "soundcraft-audio-io", "soundcraft-automation", "soundcraft-dsp", "soundcraft-engine", + "thiserror 2.0.21", ] [[package]] name = "soundcraft-dsp" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "proptest", @@ -4063,7 +4379,7 @@ dependencies = [ [[package]] name = "soundcraft-engine" -version = "0.13.1" +version = "0.14.0" dependencies = [ "craft-docpath", "log", @@ -4086,7 +4402,7 @@ dependencies = [ [[package]] name = "soundcraft-midi" -version = "0.13.1" +version = "0.14.0" dependencies = [ "proptest", "serde", @@ -4096,7 +4412,7 @@ dependencies = [ [[package]] name = "soundcraft-mix" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "rayon", @@ -4112,7 +4428,7 @@ dependencies = [ [[package]] name = "soundcraft-model" -version = "0.13.1" +version = "0.14.0" dependencies = [ "proptest", "serde", @@ -4125,7 +4441,7 @@ dependencies = [ [[package]] name = "soundcraft-playback" -version = "0.13.1" +version = "0.14.0" dependencies = [ "cpal", "log", @@ -4140,7 +4456,7 @@ dependencies = [ [[package]] name = "soundcraft-time" -version = "0.13.1" +version = "0.14.0" dependencies = [ "proptest", "serde", @@ -4150,7 +4466,7 @@ dependencies = [ [[package]] name = "soundcraft-ui-egui" -version = "0.13.1" +version = "0.14.0" dependencies = [ "craft-ui", "craft-update", @@ -4179,7 +4495,7 @@ dependencies = [ [[package]] name = "soundcraft-video" -version = "0.13.1" +version = "0.14.0" dependencies = [ "craft-media", "image", @@ -4191,7 +4507,7 @@ dependencies = [ [[package]] name = "soundcraft-vst3-host" -version = "0.13.1" +version = "0.14.0" dependencies = [ "libloading 0.9.0", "log", @@ -4207,7 +4523,7 @@ dependencies = [ [[package]] name = "soundcraft-web" -version = "0.13.1" +version = "0.14.0" dependencies = [ "eframe", "egui", @@ -4215,6 +4531,7 @@ dependencies = [ "log", "rfd", "serde_json", + "soundcraft-audio-io", "soundcraft-engine", "soundcraft-model", "soundcraft-playback", @@ -4251,6 +4568,12 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -4487,6 +4810,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "tar" version = "0.4.46" @@ -4610,6 +4945,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -4847,6 +5183,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + [[package]] name = "utf8-zero" version = "0.8.1" @@ -4859,6 +5201,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.29.0" @@ -5473,6 +5821,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -5700,11 +6059,20 @@ dependencies = [ "wayland-protocols-wlr", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + [[package]] name = "writeable" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +dependencies = [ + "either", +] [[package]] name = "x11-dl" @@ -5771,7 +6139,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde_json", ] @@ -5959,8 +6327,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", + "litemap", + "serde_core", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -5969,6 +6340,7 @@ version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", diff --git a/Cargo.toml b/Cargo.toml index 9237b585..043ad467 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/*", "xtask"] [workspace.package] -version = "0.13.1" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.90" @@ -29,30 +29,35 @@ soundcraft-ui-egui = { path = "crates/ui-egui" } # foundation thiserror = "2" +clap = { version = "4", features = ["derive", "env"] } +clap_complete = "4.6.11" +clap_mangen = { version = "0.3.3", features = ["env"] } serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } log = "0.4" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } rayon = "1" +# Whether an output path is one of the inputs (the CLI refuses to replace an input unless asked). +same-file = "1" proptest = "1" # audio -symphonia = { version = "0.6", default-features = false, features = ["mp3", "flac", "vorbis", "ogg", "wav", "pcm", "aiff", "isomp4", "aac", "alac", "adpcm", "caf", "mkv"] } +symphonia = { version = "0.6", default-features = false, features = ["mp1", "mp2", "mp3", "flac", "vorbis", "ogg", "wav", "pcm", "aiff", "isomp4", "aac", "alac", "adpcm", "caf", "mkv"] } rustfft = "6" # Session bundles (one file holding a session and its audio, for the browser): stored entries only. zip = { version = "9", default-features = false } cpal = "0.18" # Which file paths stored in a session may be opened. -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "db19c373c8d59a545972ca340987aecfb3611a4b" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } # Video containers and bitstreams, shared with the other craft apps. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "db19c373c8d59a545972ca340987aecfb3611a4b" } -craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "db19c373c8d59a545972ca340987aecfb3611a4b", features = ["egui"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } # ui -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "db19c373c8d59a545972ca340987aecfb3611a4b", features = ["serde"] } +craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } egui = { version = "0.37" } eframe = { version = "0.37", default-features = false } # Monotonic clock on native and the browser (the `web_time::Instant` panics-free equivalent). @@ -65,9 +70,11 @@ image = { version = "0.25", default-features = false, features = ["png"] } unsafe_code = "forbid" [workspace.lints.clippy] +cognitive_complexity = "deny" +wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" -too_many_arguments = "allow" +too_many_arguments = "deny" type_complexity = "allow" [profile.dev.package."*"] diff --git a/README.md b/README.md index 8578e95c..1024eba0 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ error only. | Variable | Effect | |---|---| | `RUST_LOG` | Log levels for standard error and the log file. Default: `info` for SoundCraft's own crates, `warn` for everything else. env_logger-style directives replace that, e.g. `RUST_LOG=debug`, `RUST_LOG=warn,soundcraft_mix=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`soundcraft*=debug`). | -| `SOUNDCRAFT_NO_PREFS` | No preferences read or written and no log file (agents' test runs). | +| `SOUNDCRAFT_NO_PREFS` | `1`: no preferences read or written and no log file (agents' test runs). | The realtime audio thread never writes a record itself: the logger keeps the first one it logs (without waiting or allocating), counts the rest, and the UI thread writes them. The logger is @@ -216,8 +216,9 @@ claude mcp add soundcraft -- soundcraft-cli mcp --demo soundcraft-cli mcp --automation-read-root DIR --automation-write-root DIR ``` -See [`docs/control-protocol.md`](docs/control-protocol.md) and [`docs/mcp.md`](docs/mcp.md). -`soundcraft-cli commands` lists every command. +See [`docs/cli.md`](docs/cli.md) for the command-line tool (subcommands, exit codes, environment +variables, man pages and completions), [`docs/control-protocol.md`](docs/control-protocol.md) and +[`docs/mcp.md`](docs/mcp.md). `soundcraft-cli commands` lists every command. Open **SoundCraft › Session Audio Health** to check loaded audio availability, sample-rate mismatches and clip source bounds across all playlists, including alternate takes. The report diff --git a/apps/soundcraft-cli/Cargo.toml b/apps/soundcraft-cli/Cargo.toml index fad22e19..9316b5b8 100644 --- a/apps/soundcraft-cli/Cargo.toml +++ b/apps/soundcraft-cli/Cargo.toml @@ -6,6 +6,10 @@ edition.workspace = true license.workspace = true publish = false +[lib] +name = "soundcraft_cli" +path = "src/lib.rs" + [[bin]] name = "soundcraft-cli" path = "src/main.rs" @@ -18,4 +22,12 @@ soundcraft-engine.workspace = true soundcraft-automation.workspace = true soundcraft-audio-io.workspace = true soundcraft-dsp.workspace = true +serde.workspace = true serde_json.workspace = true +thiserror.workspace = true +clap.workspace = true +same-file.workspace = true + +[dev-dependencies] +clap_complete.workspace = true +clap_mangen.workspace = true diff --git a/apps/soundcraft-cli/examples/man-and-completions.rs b/apps/soundcraft-cli/examples/man-and-completions.rs new file mode 100644 index 00000000..396a62ec --- /dev/null +++ b/apps/soundcraft-cli/examples/man-and-completions.rs @@ -0,0 +1,42 @@ +//! Writes soundcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish, +//! PowerShell) and man pages ([`clap_mangen`]: `soundcraft-cli.1` and one per subcommand, such as +//! `soundcraft-cli-convert.1`) into a directory. The Linux and FreeBSD packages ship them +//! (`packaging/linux/package.sh`, `packaging/freebsd/package.sh`): +//! +//! ```sh +//! cargo run -p soundcraft-cli --example man-and-completions -- +//! ``` + +use std::path::Path; +use std::process::ExitCode; + +use clap::ValueEnum; +use clap_complete::Shell; + +fn main() -> ExitCode { + let mut args = std::env::args_os().skip(1); + let (Some(dir), None) = (args.next(), args.next()) else { + eprintln!("usage: man-and-completions "); + return ExitCode::from(2); + }; + let dir = Path::new(&dir); + match generate(dir) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {}: {e}", dir.display()); + ExitCode::FAILURE + } + } +} + +/// Also run by `tests/it/man_and_completions.rs`. +pub(crate) fn generate(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let mut cmd = soundcraft_cli::command(); + for &shell in Shell::value_variants() { + clap_complete::generate_to(shell, &mut cmd, "soundcraft-cli", dir)?; + } + // A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand, + // which `clap_mangen` would otherwise give pages of its own (`soundcraft-cli-help-convert.1`). + clap_mangen::generate_to(soundcraft_cli::command(), dir) +} diff --git a/apps/soundcraft-cli/src/app.rs b/apps/soundcraft-cli/src/app.rs new file mode 100644 index 00000000..32807189 --- /dev/null +++ b/apps/soundcraft-cli/src/app.rs @@ -0,0 +1,72 @@ +use super::args::AppArgs; +use super::error::CliError; +use super::output::print_json; +use serde_json::{Value, json}; +use soundcraft_automation::Remote; +use std::io::Write; + +/// Control-channel methods. Every other dotted id is an engine command. +fn is_control_method(method: &str) -> bool { + matches!( + method, + "engine.execute" + | "command" + | "engine.commands" + | "engine.parity" + | "session.inspect" + | "document.inspect" + | "ui.inspect" + | "ui.menu.list" + | "ui.menu.invoke" + | "ui.set" + | "ui.move" + | "ui.click" + | "ui.drag" + | "ui.key" + | "ui.text" + | "ui.screenshot" + | "app.quit" + ) +} + +/// A command id is shorthand for `engine.execute`. Documented control methods stay methods. +fn app_request(method: &str, params: Value) -> (String, Value) { + if is_control_method(method) || !method.contains('.') { + (method.to_string(), params) + } else { + ("engine.execute".to_string(), json!({"command": method, "params": params})) + } +} + +pub(crate) fn app(args: &AppArgs, out: &mut dyn Write) -> Result<(), CliError> { + let method = &args.method; + let params = args.json.clone().unwrap_or_else(|| json!({})); + let mut r = Remote::new(&args.control.port); + // A bare command id is shorthand for engine.execute. Control-channel methods stay methods. + let (m, p) = app_request(method, params); + let v = r.request(&m, p)?; + print_json(out, &v, args.compact); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn command_ids_are_execute_shorthand_and_control_methods_stay_methods() { + let (m, p) = app_request("engine.history", json!({})); + assert_eq!(m, "engine.execute"); + assert_eq!(p["command"], "engine.history"); + let (m, p) = app_request("ui.theme", json!({"mode": "light"})); + assert_eq!(m, "engine.execute"); + assert_eq!(p["params"]["mode"], "light"); + let (m, _) = app_request("session.new", json!({"name": "Session A"})); + assert_eq!(m, "engine.execute"); + let (m, _) = app_request("track.new", json!({})); + assert_eq!(m, "engine.execute"); + for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] { + assert_eq!(app_request(method, json!({})).0, method); + } + } +} diff --git a/apps/soundcraft-cli/src/args.rs b/apps/soundcraft-cli/src/args.rs new file mode 100644 index 00000000..40351779 --- /dev/null +++ b/apps/soundcraft-cli/src/args.rs @@ -0,0 +1,459 @@ +//! The command line, as clap types. A flag a subcommand doesn't take is a usage error (exit 2), so +//! a typo such as `--bounces` can't be silently ignored (#549), and so is a value flag without its +//! value: a following flag is never taken as the value. + +use std::borrow::Cow; +use std::ffi::OsString; +use std::num::NonZeroU32; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use clap::builder::NonEmptyStringValueParser; +use clap::error::ErrorKind; +use clap::{ArgAction, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; +use serde_json::{Value, json}; +use soundcraft_audio_io::FileFormat; +use soundcraft_automation::ControlTarget; +use soundcraft_automation::args::{AutomationArgs, ControlClientArgs, blank_env_is_unset, control_target, long_version, name_env_vars}; + +/// Help text that names the extensions `list` gives, built once from +/// [`FileFormat::readable_extensions`] or [`FileFormat::writable_extensions`] so it can't drift +/// from what the code accepts. +fn with_formats(cell: &'static OnceLock, before: &str, list: fn() -> Vec<&'static str>, after: &str) -> &'static str { + cell.get_or_init(|| format!("{before}({}){after}", list().join(", "))) +} + +fn info_file_help() -> &'static str { + static C: OnceLock = OnceLock::new(); + with_formats(&C, "An audio file ", FileFormat::readable_extensions, " or a .scraft session") +} + +fn read_help() -> &'static str { + static C: OnceLock = OnceLock::new(); + with_formats(&C, "The audio file to read ", FileFormat::readable_extensions, "") +} + +fn write_help() -> &'static str { + static C: OnceLock = OnceLock::new(); + with_formats(&C, "The audio file to write; its extension picks the format ", FileFormat::writable_extensions, "") +} + +/// soundcraft-cli: SoundCraft without a window +#[derive(Parser)] +#[command(name = "soundcraft-cli", version = long_version(), arg_required_else_help = true)] +pub(crate) struct Cli { + #[command(subcommand)] + pub(crate) command: Command, +} + +#[derive(Subcommand)] +pub(crate) enum Command { + Info(InfoArgs), + Convert(ConvertArgs), + Run(RunArgs), + Script(ScriptArgs), + Commands(CommandsArgs), + Describe(DescribeArgs), + App(AppArgs), + Mcp(McpArgs), + Parity(ParityArgs), + /// List the built-in plugins + Plugins, +} + +/// Print an audio file's format as JSON, or a .scraft session's summary +#[derive(Args)] +pub(crate) struct InfoArgs { + #[arg(help = info_file_help())] + pub(crate) file: PathBuf, + /// One line of JSON instead of pretty-printed (a .scraft summary is text and ignores it) + #[arg(long)] + pub(crate) compact: bool, +} + +/// Convert an audio file: resample, change the bit depth, normalize +/// +/// Dithers only when the output loses resolution, unless --dither or --no-dither says otherwise. +#[derive(Args)] +pub(crate) struct ConvertArgs { + #[arg(value_name = "IN", help = read_help())] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT", help = write_help())] + pub(crate) output: PathBuf, + /// The output's bit depth + #[arg(long, value_enum, value_name = "16|24|32f", default_value = "24")] + pub(crate) bit_depth: BitDepthArg, + /// Resample to this sample rate + #[arg(long, value_name = "HZ")] + pub(crate) rate: Option, + /// Normalize the peak to -0.1 dBFS + #[arg(long)] + pub(crate) normalize: bool, + /// Always dither + #[arg(long, conflicts_with = "no_dither")] + pub(crate) dither: bool, + /// Never dither + #[arg(long)] + pub(crate) no_dither: bool, + /// Allow an that is the file, replacing the original + #[arg(long)] + pub(crate) in_place: bool, +} + +/// Where `run` and `script` start, and what they do with the result. +#[derive(Args)] +pub(crate) struct EngineArgs { + /// Open this session first + #[arg(long = "in", value_name = "S.scraft", conflicts_with = "demo")] + pub(crate) input: Option, + /// Start from the demo session + #[arg(long, visible_alias = "sample")] + pub(crate) demo: bool, + /// Bounce the mix to this file at the end; without --start and --end, the whole session + #[arg(long, value_name = "OUT")] + pub(crate) bounce: Option, + /// Where the bounce starts: seconds (12.5) or a time string + #[arg(long, value_name = "T", allow_negative_numbers = true, requires = "bounce", value_parser = time_arg)] + pub(crate) start: Option, + /// Where the bounce ends: seconds (12.5) or a time string + #[arg(long, value_name = "T", allow_negative_numbers = true, requires = "bounce", value_parser = time_arg)] + pub(crate) end: Option, + /// Save the session to this file at the end, replacing it + #[arg(long, value_name = "S.scraft")] + pub(crate) save: Option, + /// Print the session as JSON at the end + #[arg(long)] + pub(crate) inspect: bool, + /// Print the --inspect JSON on one line instead of pretty-printed + #[arg(long, requires = "inspect")] + pub(crate) compact: bool, + /// Allow a --save that is the --in session, replacing the original + #[arg(long, requires = "input")] + pub(crate) in_place: bool, +} + +/// Run engine commands on a new, demo or saved session +/// +/// Prints each command's JSON result on one line, then bounces, saves and inspects, in that order. +/// The --inspect JSON is pretty-printed unless --compact is given. +#[derive(Args)] +pub(crate) struct RunArgs { + /// An engine command, with its JSON parameters after `=` (default {}); repeat for several, run + /// in order + #[arg(long, value_name = "ID[=JSON]", action = ArgAction::Append, value_parser = cmd_spec)] + pub(crate) cmd: Vec, + #[command(flatten)] + pub(crate) engine: EngineArgs, +} + +/// Run a file of engine commands, one `ID JSON` per line +/// +/// Blank lines and lines starting with # are skipped. A failing line stops the script unless +/// --keep-going is given. +#[derive(Args)] +pub(crate) struct ScriptArgs { + /// The script to run + pub(crate) file: PathBuf, + /// Report a failing line and go on with the next + #[arg(long)] + pub(crate) keep_going: bool, + #[command(flatten)] + pub(crate) engine: EngineArgs, +} + +/// List the engine commands +#[derive(Args)] +pub(crate) struct CommandsArgs { + /// Only the commands whose id, or label in any case, contains this text + #[arg(value_parser = NonEmptyStringValueParser::new())] + pub(crate) filter: Option, +} + +/// Print one engine command's details as JSON +#[derive(Args)] +pub(crate) struct DescribeArgs { + /// The command's id, such as file.bounce_mix + #[arg(value_parser = NonEmptyStringValueParser::new())] + pub(crate) id: String, + /// One line of JSON instead of pretty-printed + #[arg(long)] + pub(crate) compact: bool, +} + +/// Call a running app's control channel +/// +/// A dotted engine command id is shorthand for engine.execute; the control methods +/// (session.inspect, ui.screenshot, …) stay methods. Prints the reply as JSON. +#[derive(Args)] +pub(crate) struct AppArgs { + #[command(flatten)] + pub(crate) control: ControlClientArgs, + /// A control method or engine command id + #[arg(value_parser = NonEmptyStringValueParser::new())] + pub(crate) method: String, + /// Its parameters as JSON [default: {}] + #[arg(value_parser = json_value)] + pub(crate) json: Option, + /// One line of JSON instead of pretty-printed + #[arg(long)] + pub(crate) compact: bool, +} + +/// Serve MCP on stdin and stdout +/// +/// The automation roots confine every file the agent's commands read (open, import, presets) and +/// write (save, bounce, export) to those folders, links followed. Each root flag may be given more +/// than once, a path inside any of its folders being allowed, and a kind left out grants none of +/// its access. The roots confine the in-process server, so they, like --demo, conflict with --connect. +#[derive(Args)] +pub(crate) struct McpArgs { + /// Serve a running app's control channel at this port or host:port instead of an in-process + /// engine; conflicts with --demo, which starts only that engine + #[arg(long, value_name = "PORT", value_parser = control_target, conflicts_with_all = ["demo", "automation_read_root", "automation_write_root"])] + pub(crate) connect: Option, + /// Start the in-process engine from the demo session + #[arg(long)] + pub(crate) demo: bool, + #[command(flatten)] + pub(crate) automation: AutomationArgs, +} + +/// Print the parity report (markdown) +#[derive(Args)] +pub(crate) struct ParityArgs { + /// Write the report to this file instead + #[arg(long, value_name = "PATH")] + pub(crate) write: Option, +} + +impl Command { + /// The outputs clap can't check: one that is an input file, however it is spelt, or both of + /// `--bounce` and `--save` naming one file. The paths are compared before any work starts and + /// written later, so a link swapped in meanwhile goes unnoticed: this guards against mistakes, + /// it is not a security boundary. + fn check_outputs(&self) -> Result<(), OutputError> { + match self { + Self::Convert(a) if !a.in_place && same_file(&a.input, &a.output) => { + Err(OutputError::ReplacesInput { output: "", input: " file", path: a.output.clone() }) + } + Self::Run(a) => a.engine.check_outputs(None), + Self::Script(a) => a.engine.check_outputs(Some(&a.file)), + Self::Info(_) + | Self::Convert(_) + | Self::Commands(_) + | Self::Describe(_) + | Self::App(_) + | Self::Mcp(_) + | Self::Parity(_) + | Self::Plugins => Ok(()), + } + } +} + +impl ConvertArgs { + /// The file `convert` writes: , or the file it links to when it replaces in place. + pub(crate) fn write_path(&self) -> Cow<'_, Path> { + in_place_target(self.in_place, Some(&self.input), &self.output) + } +} + +impl EngineArgs { + /// The file --save writes: its path, or the file it links to when it replaces --in in place. + pub(crate) fn save_path(&self) -> Option> { + self.save.as_deref().map(|save| in_place_target(self.in_place, self.input.as_deref(), save)) + } + + /// `script` is the script file `script` runs, which no flag lets an output replace. --in-place + /// lets only --save replace the --in session: a bounce would turn it into audio. + fn check_outputs(&self, script: Option<&Path>) -> Result<(), OutputError> { + for (flag, path) in [("--bounce", &self.bounce), ("--save", &self.save)] { + let Some(path) = path else { continue }; + if script.is_some_and(|script| same_file(script, path)) { + return Err(OutputError::ReplacesScript { output: flag, path: path.clone() }); + } + } + let replaces_input = |path: &Path| self.input.as_ref().is_some_and(|input| same_file(input, path)); + if let Some(bounce) = &self.bounce + && replaces_input(bounce) + { + return Err(OutputError::BounceReplacesInput(bounce.clone())); + } + if let Some(save) = &self.save + && !self.in_place + && replaces_input(save) + { + return Err(OutputError::ReplacesInput { output: "--save", input: "--in session", path: save.clone() }); + } + match (&self.bounce, &self.save) { + (Some(bounce), Some(save)) if same_file(bounce, save) => Err(OutputError::SameOutputs(save.clone())), + _ => Ok(()), + } + } +} + +/// Whether `a` and `b` name one file, however spelt (`a.wav`, `./a.wav`, a symbolic or hard link). +/// When either exists, only two regular files can be one, compared by identity (device and inode); +/// a FIFO or device is never opened, so the check can't block. When neither exists yet, they are +/// one if they would be created at the same place. +fn same_file(a: &Path, b: &Path) -> bool { + if a.exists() || b.exists() { + return a.is_file() && b.is_file() && same_file::is_same_file(a, b).unwrap_or(false); + } + matches!((destination(a), destination(b)), (Some(a), Some(b)) if a == b) +} + +/// With `in_place`, an `output` that is a symbolic link to `input` resolved to the file it names. +/// A save writes a new file and renames it over its path, which would replace the link and leave +/// the input as it was: through the resolved path, `convert` and `--save` both replace the input. +fn in_place_target<'a>(in_place: bool, input: Option<&Path>, output: &'a Path) -> Cow<'a, Path> { + let link = output.symlink_metadata().is_ok_and(|m| m.file_type().is_symlink()); + if in_place + && link + && input.is_some_and(|input| same_file(input, output)) + && let Ok(target) = output.canonicalize() + { + return Cow::Owned(target); + } + Cow::Borrowed(output) +} + +/// Where a file that doesn't exist yet would be created: its folder resolved, links followed. +fn destination(path: &Path) -> Option { + let folder = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + Some(folder.canonicalize().ok()?.join(path.file_name()?)) +} + +/// An output [`Command::check_outputs`] refuses: `parse` prints it as a usage error (exit 2). +#[derive(Debug, thiserror::Error)] +pub(crate) enum OutputError { + #[error("{output} {} is the {input}, which it would replace: choose another file, or pass --in-place", .path.display())] + ReplacesInput { output: &'static str, input: &'static str, path: PathBuf }, + #[error("--bounce {} is the --in session, which it would replace with audio: choose another file", .0.display())] + BounceReplacesInput(PathBuf), + #[error("{output} {} is the script file, which it would replace: choose another file", .path.display())] + ReplacesScript { output: &'static str, path: PathBuf }, + #[error("--bounce and --save both name {}, so the save would replace the bounce: choose another file for one of them", .0.display())] + SameOutputs(PathBuf), +} + +impl OutputError { + /// Two arguments that may not name one file: clap's conflict kind. + fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { + cmd.error(ErrorKind::ArgumentConflict, self) + } +} + +/// The bit depths `convert` writes. `32` is the same as `32f`. +#[derive(Clone, Copy, ValueEnum)] +pub(crate) enum BitDepthArg { + #[value(name = "16")] + Int16, + #[value(name = "24")] + Int24, + #[value(name = "32f", alias = "32")] + Float32, +} + +impl From for soundcraft_audio_io::BitDepth { + fn from(depth: BitDepthArg) -> Self { + match depth { + BitDepthArg::Int16 => Self::Int16, + BitDepthArg::Int24 => Self::Int24, + BitDepthArg::Float32 => Self::Float32, + } + } +} + +/// A bounce position: seconds, or a time string the engine reads. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum TimeArg { + Seconds(f64), + Text(String), +} + +impl TimeArg { + /// The `start` / `end` parameter of `file.bounce_mix`. + pub(crate) fn to_json(&self) -> Value { + match self { + Self::Seconds(s) => json!({"seconds": s}), + Self::Text(t) => json!(t), + } + } +} + +/// One `--cmd ID[=JSON]`: the command id and its parameters (`{}` when none are given). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct CmdSpec { + pub(crate) id: String, + pub(crate) params: Value, +} + +/// Why a value was refused: clap prints it after the flag and its value (exit 2). +#[derive(Debug, thiserror::Error)] +pub(crate) enum ValueError { + #[error("expected seconds (12.5) or a time string, not an empty value")] + EmptyTime, + #[error("expected a finite number of seconds")] + NotFinite, + #[error("expected a command id, optionally followed by `=` and JSON parameters")] + EmptyCommandId, + #[error("bad JSON: {0}")] + Json(#[from] serde_json::Error), +} + +fn time_arg(s: &str) -> Result { + if s.is_empty() { + return Err(ValueError::EmptyTime); + } + match s.parse::() { + // JSON has no NaN or infinity: serde_json would send the engine `null`. + Ok(secs) if !secs.is_finite() => Err(ValueError::NotFinite), + Ok(secs) => Ok(TimeArg::Seconds(secs)), + Err(_) => Ok(TimeArg::Text(s.to_owned())), + } +} + +fn json_value(s: &str) -> Result { + Ok(serde_json::from_str(s)?) +} + +/// `ID` or `ID=JSON`; malformed JSON is an error, not `{}`. +fn cmd_spec(s: &str) -> Result { + let (id, params) = match s.split_once('=') { + Some((id, p)) => (id, json_value(p)?), + None => (s, json!({})), + }; + if id.is_empty() { + return Err(ValueError::EmptyCommandId); + } + Ok(CmdSpec { id: id.to_owned(), params }) +} + +/// Parse the arguments (without the binary name). clap reads them as `OsString`s: a folder need +/// not be valid Unicode, text must. A flag wins over its environment variable, unless that is +/// empty, and a bad value from one is a usage error naming the variable. A bare `--help` or `-h` +/// is help even after a mistake on the same line (`run --bounce --help`): clap reports the mistake +/// first. An output that would replace an input is refused here too +/// ([`Command::check_outputs`]), so nothing has run when it is reported. +pub(crate) fn parse(args: &[OsString]) -> Result { + let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset)); + let argv = std::iter::once(OsString::from("soundcraft-cli")).chain(args.iter().cloned()); + let matches = match cmd.try_get_matches_from_mut(argv) { + Err(e) if e.kind() != ErrorKind::DisplayHelp => { + let Some(flag) = args.iter().take_while(|a| *a != "--").find(|a| *a == "--help" || *a == "-h") else { + return Err(name_env_vars(e, &cmd, args)); + }; + let help = [OsString::from("soundcraft-cli"), args.first().cloned().unwrap_or_default(), flag.clone()]; + return Err(cmd.try_get_matches_from_mut(help).err().unwrap_or(e)); + } + matches => matches?, + }; + let cli = Cli::from_arg_matches(&matches)?; + if let Err(e) = cli.command.check_outputs() { + return Err(match matches.subcommand_name().and_then(|name| cmd.find_subcommand_mut(name)) { + Some(sub) => e.into_clap(sub), + None => e.into_clap(&mut cmd), + }); + } + Ok(cli) +} diff --git a/apps/soundcraft-cli/src/automation_args.rs b/apps/soundcraft-cli/src/automation_args.rs deleted file mode 100644 index e8135f91..00000000 --- a/apps/soundcraft-cli/src/automation_args.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed -//! flag must not silently remove a root and leave the server unconfined. - -use std::path::PathBuf; - -#[derive(Default)] -pub struct AutomationArgs { - pub read_roots: Vec, - pub write_roots: Vec, -} - -impl AutomationArgs { - /// Returns whether this argument is a root flag. Each flag may be given more than once (#874), - /// in either spelling (`--flag DIR`, `--flag=DIR`): every use adds a folder. - pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { - let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value))); - let roots = match flag { - "--automation-read-root" => &mut self.read_roots, - "--automation-write-root" => &mut self.write_roots, - _ => return Ok(false), - }; - let value = match inline { - Some(value) => value.to_owned(), - None => { - let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?; - if value.starts_with('-') { - return Err(format!("{flag} needs a folder; use {flag}= for a folder starting with '-'")); - } - value - } - }; - if value.is_empty() { - return Err(format!("{flag} needs a non-empty folder")); - } - roots.push(value.into()); - Ok(true) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn roots_add_up_and_other_arguments_are_left() { - let mut roots = AutomationArgs::default(); - let mut args = ["a folder".to_owned(), "song.scraft".to_owned()].into_iter(); - assert!(roots.consume("--automation-read-root", &mut args).unwrap()); - assert!(roots.consume("--automation-write-root=out", &mut args).unwrap()); - assert!(!roots.consume("--demo", &mut args).unwrap()); - assert_eq!(roots.read_roots, [PathBuf::from("a folder")]); - assert_eq!(roots.write_roots, [PathBuf::from("out")]); - assert_eq!(args.next().as_deref(), Some("song.scraft")); - // #874: a flag given again adds a folder, in either spelling. - assert!(roots.consume("--automation-read-root=other", &mut args).unwrap()); - assert!(roots.consume("--automation-write-root", &mut ["out2".to_owned()].into_iter()).unwrap()); - assert_eq!(roots.read_roots, [PathBuf::from("a folder"), PathBuf::from("other")]); - assert_eq!(roots.write_roots, [PathBuf::from("out"), PathBuf::from("out2")]); - } - - #[test] - fn invalid_operands_leave_roots_unchanged() { - for flag in ["--automation-read-root", "--automation-write-root"] { - for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] { - let mut roots = AutomationArgs { read_roots: vec!["read".into()], write_roots: vec!["write".into()] }; - let mut args = operand.map(str::to_owned).into_iter(); - assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}"); - assert_eq!(roots.read_roots, [PathBuf::from("read")]); - assert_eq!(roots.write_roots, [PathBuf::from("write")]); - } - let mut roots = AutomationArgs::default(); - assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err()); - } - } - - #[test] - fn explicit_dash_folder_and_relative_dash_folder_are_valid() { - let mut roots = AutomationArgs::default(); - assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap()); - assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap()); - assert_eq!(roots.read_roots, [PathBuf::from("-folder")]); - assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]); - } -} diff --git a/apps/soundcraft-cli/src/catalog.rs b/apps/soundcraft-cli/src/catalog.rs new file mode 100644 index 00000000..c701d66c --- /dev/null +++ b/apps/soundcraft-cli/src/catalog.rs @@ -0,0 +1,50 @@ +use super::args::{CommandsArgs, DescribeArgs, ParityArgs}; +use super::error::CliError; +use super::output::print_json; +use soundcraft_engine::Engine; +use std::io::Write; + +pub(crate) fn commands(args: &CommandsArgs, out: &mut dyn Write) { + let filter = args.filter.clone().unwrap_or_default(); + let e = Engine::default(); + for c in soundcraft_engine::command_specs() { + if !filter.is_empty() && !c.id.contains(&filter) && !c.label.to_ascii_lowercase().contains(&filter.to_ascii_lowercase()) { + continue; + } + let i = c.info(&e); + outln!(out, "{:<36} {:<34} {}", i.id, i.label, i.menu.join(" > ")); + } +} + +pub(crate) fn describe(args: &DescribeArgs, out: &mut dyn Write) -> Result<(), CliError> { + let id = &args.id; + let c = soundcraft_engine::find_command(id).ok_or_else(|| CliError::UnknownCommand(id.clone()))?; + print_json(out, &c.info(&Engine::default()), args.compact); + Ok(()) +} + +pub(crate) fn parity(args: &ParityArgs, out: &mut dyn Write) -> Result<(), CliError> { + let p = soundcraft_engine::catalog::parity_json(); + let mut md = String::new(); + md.push_str("# Parity report\n\nGenerated by `soundcraft-cli parity --write docs/parity-checklist.md` (also `cargo xtask parity`).\n"); + md.push_str("It compares the incumbent's menu tree (feature names observed black-box, `crates/engine/catalog/menus.txt`) with SoundCraft's command registry.\n"); + md.push_str("UI-layer commands (windows, AudioSuite) are counted by the app's own report (`engine.parity` over the control channel).\n\n"); + md.push_str(&format!( + "**Menu items implemented by the engine: {} / {} ({}%)**\n\n| Menu | Implemented | Total |\n|---|---:|---:|\n", + p["implemented"], p["total"], p["percent"] + )); + for m in p["per_menu"].as_array().cloned().unwrap_or_default() { + md.push_str(&format!("| {} | {} | {} |\n", m["menu"].as_str().unwrap_or(""), m["implemented"], m["total"])); + } + md.push_str("\n## Not yet implemented\n\n"); + for m in p["missing"].as_array().cloned().unwrap_or_default() { + md.push_str(&format!("- {}\n", m.as_str().unwrap_or(""))); + } + if let Some(path) = &args.write { + std::fs::write(path, &md).map_err(|source| CliError::File { path: path.clone(), source })?; + outln!(out, "wrote {}: {}% ({}/{})", path.display(), p["percent"], p["implemented"], p["total"]); + } else { + outln!(out, "{md}"); + } + Ok(()) +} diff --git a/apps/soundcraft-cli/src/convert.rs b/apps/soundcraft-cli/src/convert.rs new file mode 100644 index 00000000..91c606b8 --- /dev/null +++ b/apps/soundcraft-cli/src/convert.rs @@ -0,0 +1,105 @@ +use super::args::ConvertArgs; +use super::error::{CliError, ConvertError}; +use std::io::Write; +use std::num::NonZeroU32; + +pub(crate) fn convert(args: &ConvertArgs, out: &mut dyn Write) -> Result<(), CliError> { + let (input, output) = (&args.input, &args.output); + let rate = args.rate.map(NonZeroU32::get); + let bit_depth = args.bit_depth.into(); + let dither_flag = match (args.dither, args.no_dither) { + (true, _) => Some(true), + (_, true) => Some(false), + _ => None, + }; + let bytes = std::fs::read(input).map_err(|source| CliError::File { path: input.clone(), source })?; + let ext = input.extension().and_then(std::ffi::OsStr::to_str); + let (info, mut buf) = soundcraft_audio_io::decode(&bytes, ext).map_err(|source| CliError::Audio { path: input.clone(), source })?; + if let Some(rate) = rate { + buf.channels = soundcraft_dsp::offline::resample(&buf.channels, buf.sample_rate, rate); + buf.sample_rate = rate; + } + let normalize = args.normalize; + if normalize { + soundcraft_dsp::offline::normalize(&mut buf.channels, -0.1, false); + } + let processed = rate.is_some_and(|r| r != info.sample_rate) || normalize; + let dither = dither_flag.unwrap_or_else(|| auto_dither(info.sample_format, bit_depth, processed)); + // Lossy only for the message: an extension that is not valid Unicode names no format. + let out_ext = output.extension().map_or_else(|| "wav".into(), |e| e.to_string_lossy().to_ascii_lowercase()); + let Some(format) = soundcraft_audio_io::FileFormat::from_write_extension(&out_ext) else { + return Err(ConvertError::OutputFormat { output: output.clone(), ext: out_ext }.into()); + }; + let opts = soundcraft_audio_io::EncodeOptions { format, bit_depth, dither, bwf: None }; + let bytes = soundcraft_audio_io::encode(&buf, &opts).map_err(|source| CliError::Audio { path: output.clone(), source })?; + write_replacing(&args.write_path(), &bytes).map_err(|source| CliError::File { path: output.clone(), source })?; + outln!(out, "wrote {} ({} ch, {} Hz, {:.2} s)", output.display(), buf.num_channels(), buf.sample_rate, buf.duration_secs()); + Ok(()) +} + +/// Writes `bytes` to a new file next to `target`, flushes it and renames it over `target`, so `target` +/// (the input, for --in-place) holds either its old or its new contents. The new file is removed when +/// writing or renaming fails. +fn write_replacing(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + let name = target.file_name().map_or_else(|| "output".into(), |n| n.to_string_lossy().into_owned()); + let tmp = target.with_file_name(format!(".{name}.{}.part", std::process::id())); + let written = (|| { + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&tmp, target) + })(); + if written.is_err() { + let _ = std::fs::remove_file(&tmp); + } + written +} + +/// Whether `convert` dithers when not told: only when writing integer samples that cannot hold the +/// source exactly, i.e. the output has fewer bits than the source, the source is float or lossy, or +/// resampling/normalizing produced new sample values. A 16-bit file written as 16 or 24-bit, or +/// anything written as 32-bit float, is copied sample for sample (digital silence stays silent). +fn auto_dither(source: soundcraft_audio_io::SampleFormat, target: soundcraft_audio_io::BitDepth, processed: bool) -> bool { + use soundcraft_audio_io::{BitDepth, SampleFormat}; + let target_bits = match target { + BitDepth::Float32 => return false, + BitDepth::Int16 => 16, + BitDepth::Int24 => 24, + BitDepth::Int32 => 32, + }; + if processed { + return true; + } + match source { + SampleFormat::Int8 => target_bits < 8, + SampleFormat::Int16 => target_bits < 16, + SampleFormat::Int24 => target_bits < 24, + // Decoded through f32, which holds 24 bits: a 32-bit integer source has already lost + // resolution, so treat it like float. + SampleFormat::Int32 | SampleFormat::Float32 | SampleFormat::Float64 | SampleFormat::Compressed => true, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn convert_dithers_only_when_resolution_is_lost() { + use soundcraft_audio_io::{BitDepth, SampleFormat}; + // Same depth or wider: the samples fit exactly. + assert!(!auto_dither(SampleFormat::Int16, BitDepth::Int16, false)); + assert!(!auto_dither(SampleFormat::Int16, BitDepth::Int24, false)); + assert!(!auto_dither(SampleFormat::Int24, BitDepth::Int24, false)); + assert!(!auto_dither(SampleFormat::Int8, BitDepth::Int16, false)); + // Float output never dithers. + assert!(!auto_dither(SampleFormat::Float32, BitDepth::Float32, true)); + assert!(!auto_dither(SampleFormat::Int24, BitDepth::Float32, false)); + // Fewer bits, a float or lossy source, or processed samples: dither. + assert!(auto_dither(SampleFormat::Int24, BitDepth::Int16, false)); + assert!(auto_dither(SampleFormat::Float32, BitDepth::Int24, false)); + assert!(auto_dither(SampleFormat::Compressed, BitDepth::Int16, false)); + assert!(auto_dither(SampleFormat::Int32, BitDepth::Int24, false)); + assert!(auto_dither(SampleFormat::Int16, BitDepth::Int16, true)); + } +} diff --git a/apps/soundcraft-cli/src/error.rs b/apps/soundcraft-cli/src/error.rs new file mode 100644 index 00000000..a048694c --- /dev/null +++ b/apps/soundcraft-cli/src/error.rs @@ -0,0 +1,49 @@ +use std::path::{Path, PathBuf}; + +use soundcraft_audio_io::AudioError; +use soundcraft_automation::RemoteError; +use soundcraft_engine::EngineError; +use soundcraft_engine::file_access::RootError; + +/// Why a subcommand failed: printed as `error: {e}`, exit 1. +#[derive(Debug, thiserror::Error)] +pub(crate) enum CliError { + #[error(transparent)] + Convert(#[from] ConvertError), + #[error(transparent)] + Engine(#[from] EngineError), + #[error("unknown command `{0}`")] + UnknownCommand(String), + #[error("{id}: {source}")] + Command { id: String, source: EngineError }, + #[error("{}:{line}: bad JSON: {source}", path.display())] + ScriptJson { path: PathBuf, line: usize, source: serde_json::Error }, + #[error("{}:{line}: {id}: {source}", path.display())] + ScriptLine { path: PathBuf, line: usize, id: String, source: EngineError }, + #[error("{}: {source}", path.display())] + File { path: PathBuf, source: std::io::Error }, + #[error("{}: {source}", path.display())] + Audio { path: PathBuf, source: AudioError }, + /// A `--bounce` or `--save` path: the engine's commands take them in JSON, which holds only + /// text. + #[error("{}: the path is not valid Unicode", .0.display())] + NotUnicode(PathBuf), + #[error(transparent)] + Remote(#[from] RemoteError), + #[error(transparent)] + Roots(#[from] RootError), + #[error(transparent)] + Serve(std::io::Error), +} + +/// A path as the text the engine's commands take. +pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> { + path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned())) +} + +/// A `convert` option or output the tool refuses. +#[derive(Debug, PartialEq, thiserror::Error)] +pub(crate) enum ConvertError { + #[error("{}: cannot write `.{ext}` files (supported: {})", output.display(), soundcraft_audio_io::FileFormat::writable_extensions().join(", "))] + OutputFormat { output: PathBuf, ext: String }, +} diff --git a/apps/soundcraft-cli/src/info.rs b/apps/soundcraft-cli/src/info.rs new file mode 100644 index 00000000..51f9264c --- /dev/null +++ b/apps/soundcraft-cli/src/info.rs @@ -0,0 +1,27 @@ +use super::args::InfoArgs; +use super::error::CliError; +use super::output::print_json; +use super::session::warn_missing; +use serde_json::json; +use soundcraft_engine::Engine; +use std::io::Write; + +pub(crate) fn info(args: &InfoArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let path = &args.file; + if path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("scraft")) { + let mut e = Engine::default(); + let missing = soundcraft_engine::io::open_session(&mut e, path)?; + warn_missing(err, &missing); + outln!(out, "{}", soundcraft_engine::inspect::session_text(&e)); + return Ok(()); + } + let bytes = std::fs::read(path).map_err(|source| CliError::File { path: path.clone(), source })?; + let ext = path.extension().and_then(std::ffi::OsStr::to_str); + let i = soundcraft_audio_io::probe(&bytes, ext).map_err(|source| CliError::Audio { path: path.clone(), source })?; + print_json( + out, + &json!({"format": i.format, "sample_format": i.sample_format, "sample_rate": i.sample_rate, "channels": i.channels, "frames": i.frames, "seconds": i.duration_secs(), "bwf": i.bwf}), + args.compact, + ); + Ok(()) +} diff --git a/apps/soundcraft-cli/src/lib.rs b/apps/soundcraft-cli/src/lib.rs new file mode 100644 index 00000000..fe351e2e --- /dev/null +++ b/apps/soundcraft-cli/src/lib.rs @@ -0,0 +1,82 @@ +//! `soundcraft-cli`: SoundCraft without a window. `run` is the whole program, so it can be tested +//! in-process as well as through the binary. `soundcraft-cli --help` lists the subcommands. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +#[macro_use] +mod output; + +mod app; +mod args; +mod catalog; +mod convert; +mod error; +mod info; +mod mcp; +mod session; + +use std::ffi::OsString; +use std::io::Write; + +use clap::CommandFactory; + +use app::app; +use args::{Cli, Command, parse}; +use catalog::{commands, describe, parity}; +use convert::convert; +use error::CliError; +use info::info; +use mcp::mcp; +use session::{run_cmds, script}; + +/// The command line's clap definition. +pub fn command() -> clap::Command { + Cli::command() +} + +/// Run the CLI on its arguments (without the program name), writing results to `out` and +/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage +/// error. Help and the version go to `out`, exit 0. Plugin hosts are shut down by the caller once +/// the process is done with every engine (see `main`). +pub fn run(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32 +where + I: IntoIterator, + T: Into, +{ + let args: Vec = args.into_iter().map(Into::into).collect(); + // Help and the version (`help`, `-h`, ` --help`, `-V`) come back as errors too. + let cli = match parse(&args) { + Ok(cli) => cli, + Err(e) => { + let to: &mut dyn Write = if e.use_stderr() { err } else { out }; + let _ = write!(to, "{}", e.render()); + return e.exit_code(); + } + }; + match dispatch(cli.command, out, err) { + Ok(()) => 0, + Err(e) => { + outln!(err, "error: {e}"); + 1 + } + } +} + +fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + match command { + Command::Info(a) => info(&a, out, err)?, + Command::Convert(a) => convert(&a, out)?, + Command::Run(a) => run_cmds(&a, out, err)?, + Command::Script(a) => script(&a, out, err)?, + Command::Commands(a) => commands(&a, out), + Command::Describe(a) => describe(&a, out)?, + Command::App(a) => app(&a, out)?, + Command::Mcp(a) => mcp(&a, err)?, + Command::Parity(a) => parity(&a, out)?, + Command::Plugins => { + for p in soundcraft_dsp::plugins() { + outln!(out, "{:<20} {:<22} {:?}{}", p.id, p.name, p.category, if p.is_instrument { " (instrument)" } else { "" }); + } + } + } + Ok(()) +} diff --git a/apps/soundcraft-cli/src/main.rs b/apps/soundcraft-cli/src/main.rs index 899ba71e..7d381be7 100644 --- a/apps/soundcraft-cli/src/main.rs +++ b/apps/soundcraft-cli/src/main.rs @@ -1,684 +1,12 @@ -//! `soundcraft-cli`: SoundCraft without a window. -//! -//! ```text -//! soundcraft-cli info FILE audio file or .scraft summary -//! soundcraft-cli convert IN OUT [--bit-depth 16|24|32f] [--rate HZ] [--normalize] [--dither | --no-dither] -//! dithers only when the output loses resolution, unless told -//! soundcraft-cli run [--in S.scraft | --demo] [--cmd ID[=JSON]]… [--bounce OUT] [--start T --end T] [--save S.scraft] [--inspect] -//! soundcraft-cli script FILE [--in S | --demo] [--save S] [--bounce OUT [--start T --end T]] (one `ID JSON` per line; -//! without --start/--end, --bounce covers the whole session) -//! soundcraft-cli commands [FILTER] list commands -//! soundcraft-cli describe ID one command's details -//! soundcraft-cli app [--port P] METHOD [JSON] call a running app's control channel -//! soundcraft-cli mcp [--connect PORT] [--demo] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! MCP server on stdio. The roots confine every file the -//! agent's commands read (open, import, presets) and write -//! (save, bounce, export) to those folders, links followed; -//! each flag may be given more than once, a path inside any -//! of its folders being allowed, and a kind left out grants -//! none of its access. They run the in-process server, so -//! they conflict with --connect. -//! soundcraft-cli parity [--write PATH] parity report (markdown) -//! soundcraft-cli plugins list built-in plugins -//! ``` +//! `soundcraft-cli`: SoundCraft without a window. See the library crate for the commands. + #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -mod automation_args; - -use serde_json::{Value, json}; -use soundcraft_automation::{Backend, Headless, Remote, mcp::Server}; -use soundcraft_engine::Engine; -use soundcraft_engine::file_access::{self, AutomationRoots}; -use std::io::Write; -use std::process::ExitCode; - -/// Print without panicking on a closed pipe. A write error must not skip later work -/// such as `--bounce` or `--save`, and must not by itself report success. -macro_rules! outln { - ($($t:tt)*) => {{ - let mut o = std::io::stdout().lock(); - let _ = writeln!(o, $($t)*); - }}; -} - -fn arg_value(args: &[String], flag: &str) -> Option { - args.iter().enumerate().find_map(|(i, a)| { - if a == flag { args.get(i + 1).cloned() } else { a.strip_prefix(flag).and_then(|rest| rest.strip_prefix('=')).map(str::to_owned) } - }) -} - -/// Every option a subcommand accepts, with whether it carries a value. -type Options = [(&'static str, bool)]; - -/// A misspelled option, or one whose value is missing, reads as absent through `arg_value`, so the -/// subcommand would run without what was asked for and still report success. Reject both instead. -fn check_options(args: &[String], allowed: &Options) -> Result<(), String> { - let mut i = 0; - while i < args.len() { - let Some(name) = args[i].strip_prefix("--") else { - i += 1; - continue; - }; - let (name, inline) = name.split_once('=').map_or((name, None), |(n, v)| (n, Some(v))); - let flag = format!("--{name}"); - let Some(&(_, takes_value)) = allowed.iter().find(|(f, _)| f == &flag) else { - return Err(format!("unknown option {flag}")); - }; - match (takes_value, inline) { - (false, Some(_)) => return Err(format!("{flag} takes no value")), - (true, None) => { - // A following option is the next flag, not this one's value. - if args.get(i + 1).is_none_or(|v| v.starts_with("--")) { - return Err(format!("{flag} needs a value")); - } - i += 1; - } - _ => {} - } - i += 1; - } - Ok(()) -} - -/// `--in`, `--demo`/`--sample`, `--bounce`, `--start`, `--end`, `--save` and `--inspect`, read by -/// `load_engine` and `finish` and so shared by `run` and `script`. -const ENGINE_OPTIONS: &Options = &[ - ("--in", true), - ("--demo", false), - ("--sample", false), - ("--bounce", true), - ("--start", true), - ("--end", true), - ("--save", true), - ("--inspect", false), -]; - -fn fail(msg: impl std::fmt::Display) -> ExitCode { - eprintln!("soundcraft-cli: {msg}"); - ExitCode::FAILURE -} - -/// The usage block of the module doc comment, up to its closing code fence. -fn help_text() -> String { - include_str!("main.rs") - .lines() - .skip(3) - .take_while(|l| l.trim_end() != "//! ```") - .map(|l| l.trim_start_matches("//! ")) - .collect::>() - .join("\n") -} - -fn main() -> ExitCode { - let args: Vec = std::env::args().skip(1).collect(); - let Some(cmd) = args.first().cloned() else { - eprintln!("usage: soundcraft-cli … (see --help)"); - return ExitCode::FAILURE; - }; - let rest: Vec = args.iter().skip(1).cloned().collect(); - let code = match cmd.as_str() { - "--version" | "-V" | "version" => { - outln!("SoundCraft CLI {}", env!("CARGO_PKG_VERSION")); - ExitCode::SUCCESS - } - "--help" | "-h" | "help" => { - outln!("{}", help_text()); - ExitCode::SUCCESS - } - "info" => info(&rest), - "convert" => convert(&rest), - "run" => run(&rest), - "script" => script(&rest), - "commands" => commands(&rest), - "describe" => describe(&rest), - "app" => app(&rest), - "mcp" => mcp(&rest), - "parity" => parity(&rest), - "plugins" => { - for p in soundcraft_dsp::plugins() { - outln!("{:<20} {:<22} {:?}{}", p.id, p.name, p.category, if p.is_instrument { " (instrument)" } else { "" }); - } - ExitCode::SUCCESS - } - other => fail(format!("unknown subcommand `{other}`")), - }; - // The subcommand's engine and its plugin instances are gone by now. +fn main() { + // `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed. + let code = soundcraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); + // The subcommand's engine and its plugin instances are gone by now. This is process teardown, + // so it lives here and not in `run`, which tests call many times in one process. soundcraft_engine::shutdown_plugin_hosts(); - code -} - -fn info(args: &[String]) -> ExitCode { - let Some(path) = args.first() else { return fail("info FILE") }; - if path.ends_with(".scraft") { - let mut e = Engine::default(); - match soundcraft_engine::io::open_session(&mut e, path) { - Ok(missing) => warn_missing(&missing), - Err(err) => return fail(err), - } - outln!("{}", soundcraft_engine::inspect::session_text(&e)); - return ExitCode::SUCCESS; - } - let bytes = match std::fs::read(path) { - Ok(b) => b, - Err(e) => return fail(format!("{path}: {e}")), - }; - let ext = std::path::Path::new(path).extension().and_then(std::ffi::OsStr::to_str); - match soundcraft_audio_io::probe(&bytes, ext) { - Ok(i) => { - outln!("{}", serde_json::to_string_pretty(&json!({"format": i.format, "sample_format": i.sample_format, "sample_rate": i.sample_rate, "channels": i.channels, "frames": i.frames, "seconds": i.duration_secs(), "bwf": i.bwf})).unwrap_or_default()); - ExitCode::SUCCESS - } - Err(e) => fail(format!("{path}: {e}")), - } -} - -fn convert(args: &[String]) -> ExitCode { - let (Some(input), Some(output)) = (args.first(), args.get(1)) else { return fail("convert IN OUT") }; - const OPTIONS: &Options = &[("--rate", true), ("--bit-depth", true), ("--normalize", false), ("--dither", false), ("--no-dither", false)]; - if let Err(e) = check_options(&args[2..], OPTIONS) { - return fail(e); - } - let rate = match parse_rate(arg_value(args, "--rate").as_deref()) { - Ok(r) => r, - Err(e) => return fail(e), - }; - let bit_depth = match parse_bit_depth(arg_value(args, "--bit-depth").as_deref()) { - Ok(b) => b, - Err(e) => return fail(e), - }; - let dither_flag = match parse_dither(args) { - Ok(d) => d, - Err(e) => return fail(e), - }; - let bytes = match std::fs::read(input) { - Ok(b) => b, - Err(e) => return fail(format!("{input}: {e}")), - }; - let ext = std::path::Path::new(input).extension().and_then(std::ffi::OsStr::to_str); - let (info, mut buf) = match soundcraft_audio_io::decode(&bytes, ext) { - Ok(x) => x, - Err(e) => return fail(format!("{input}: {e}")), - }; - if let Some(rate) = rate { - buf.channels = soundcraft_dsp::offline::resample(&buf.channels, buf.sample_rate, rate); - buf.sample_rate = rate; - } - let normalize = args.iter().any(|a| a == "--normalize"); - if normalize { - soundcraft_dsp::offline::normalize(&mut buf.channels, -0.1, false); - } - let processed = rate.is_some_and(|r| r != info.sample_rate) || normalize; - let dither = dither_flag.unwrap_or_else(|| auto_dither(info.sample_format, bit_depth, processed)); - let out_ext = std::path::Path::new(output).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("wav").to_ascii_lowercase(); - let Some(format) = soundcraft_audio_io::encode_format_for(&out_ext) else { - return fail(format!("{output}: cannot write `.{out_ext}` files (supported: {})", soundcraft_audio_io::ENCODE_EXTENSIONS)); - }; - let opts = soundcraft_audio_io::EncodeOptions { format, bit_depth, dither, bwf: None }; - match soundcraft_audio_io::encode(&buf, &opts).map_err(|e| e.to_string()).and_then(|b| std::fs::write(output, b).map_err(|e| e.to_string())) { - Ok(()) => { - outln!("wrote {output} ({} ch, {} Hz, {:.2} s)", buf.num_channels(), buf.sample_rate, buf.duration_secs()); - ExitCode::SUCCESS - } - Err(e) => fail(e), - } -} - -fn parse_rate(v: Option<&str>) -> Result, String> { - match v { - None => Ok(None), - Some(r) => match r.parse::() { - Ok(hz) if hz > 0 => Ok(Some(hz)), - _ => Err(format!("--rate: expected a sample rate in Hz, got `{r}`")), - }, - } -} - -fn parse_bit_depth(v: Option<&str>) -> Result { - match v { - None | Some("24") => Ok(soundcraft_audio_io::BitDepth::Int24), - Some("16") => Ok(soundcraft_audio_io::BitDepth::Int16), - Some("32") | Some("32f") => Ok(soundcraft_audio_io::BitDepth::Float32), - Some(b) => Err(format!("--bit-depth: expected 16, 24 or 32f, got `{b}`")), - } -} - -/// `--dither` / `--no-dither`: `Some` when the caller chose, `None` to decide from the depths. -fn parse_dither(args: &[String]) -> Result, String> { - match (args.iter().any(|a| a == "--dither"), args.iter().any(|a| a == "--no-dither")) { - (true, true) => Err("--dither and --no-dither: choose one".into()), - (true, false) => Ok(Some(true)), - (false, true) => Ok(Some(false)), - (false, false) => Ok(None), - } -} - -/// Whether `convert` dithers when not told: only when writing integer samples that cannot hold the -/// source exactly, i.e. the output has fewer bits than the source, the source is float or lossy, or -/// resampling/normalizing produced new sample values. A 16-bit file written as 16 or 24-bit, or -/// anything written as 32-bit float, is copied sample for sample (digital silence stays silent). -fn auto_dither(source: soundcraft_audio_io::SampleFormat, target: soundcraft_audio_io::BitDepth, processed: bool) -> bool { - use soundcraft_audio_io::{BitDepth, SampleFormat}; - let target_bits = match target { - BitDepth::Float32 => return false, - BitDepth::Int16 => 16, - BitDepth::Int24 => 24, - BitDepth::Int32 => 32, - }; - if processed { - return true; - } - match source { - SampleFormat::Int8 => target_bits < 8, - SampleFormat::Int16 => target_bits < 16, - SampleFormat::Int24 => target_bits < 24, - // Decoded through f32, which holds 24 bits: a 32-bit integer source has already lost - // resolution, so treat it like float. - SampleFormat::Int32 | SampleFormat::Float32 | SampleFormat::Float64 | SampleFormat::Compressed => true, - } -} - -/// One stderr line per media file a session refers to but could not load (the exit code is unchanged). -fn missing_warnings(missing: &[String]) -> Vec { - missing.iter().map(|m| format!("warning: missing media: {m}")).collect() -} - -fn warn_missing(missing: &[String]) { - for line in missing_warnings(missing) { - eprintln!("{line}"); - } -} - -fn load_engine(args: &[String]) -> Result { - if let Some(p) = arg_value(args, "--in") { - let mut e = Engine::default(); - let missing = soundcraft_engine::io::open_session(&mut e, &p).map_err(|e| e.to_string())?; - warn_missing(&missing); - Ok(e) - } else if args.iter().any(|a| a == "--demo" || a == "--sample") { - Ok(soundcraft_engine::demo::demo_engine()) - } else { - Ok(Engine::default()) - } -} - -fn finish(e: &mut Engine, args: &[String]) -> ExitCode { - if let Some(out) = arg_value(args, "--bounce") { - let mut p = json!({"path": out}); - if let Some(s) = arg_value(args, "--start") { - p["start"] = time_arg(&s); - } - if let Some(s) = arg_value(args, "--end") { - p["end"] = time_arg(&s); - } - // No range given: bounce the whole session, not whatever edit selection the commands left. - if p.get("start").is_none() && p.get("end").is_none() { - p["start"] = json!(0); - p["end"] = json!(e.session().content_end().max(1)); - } - match e.execute("file.bounce_mix", &p) { - Ok(v) => outln!("{v}"), - Err(err) => return fail(err), - } - } - if let Some(path) = arg_value(args, "--save") { - match e.execute("session.save", &json!({"path": path, "replace": true})) { - Ok(v) => outln!("{v}"), - Err(err) => return fail(err), - } - } - if args.iter().any(|a| a == "--inspect") { - outln!("{}", serde_json::to_string_pretty(&soundcraft_engine::inspect::session(e, false)).unwrap_or_default()); - } - ExitCode::SUCCESS -} - -/// `12.5` → seconds; anything else is passed through as a time string. -fn time_arg(s: &str) -> Value { - s.parse::().map_or_else(|_| json!(s), |f| json!({"seconds": f})) -} - -/// `ID` or `ID=JSON` → command id and params; malformed JSON is an error, not `{}`. -fn parse_cmd_spec(spec: &str) -> Result<(String, Value), String> { - match spec.split_once('=') { - Some((id, p)) => serde_json::from_str::(p).map(|v| (id.to_string(), v)).map_err(|err| format!("{id}: bad JSON: {err}")), - None => Ok((spec.to_string(), json!({}))), - } -} - -fn run(args: &[String]) -> ExitCode { - let options: Vec<(&str, bool)> = ENGINE_OPTIONS.iter().copied().chain([("--cmd", true)]).collect(); - if let Err(e) = check_options(args, &options) { - return fail(e); - } - let mut e = match load_engine(args) { - Ok(e) => e, - Err(err) => return fail(err), - }; - let mut it = args.iter(); - while let Some(a) = it.next() { - let spec = match a.strip_prefix("--cmd=") { - Some(inline) => inline, - None if a == "--cmd" => match it.next() { - Some(next) => next, - None => continue, - }, - None => continue, - }; - let (id, params) = match parse_cmd_spec(spec) { - Ok(v) => v, - Err(err) => return fail(err), - }; - match e.execute(&id, ¶ms) { - Ok(v) => outln!("{id}: {v}"), - Err(err) => return fail(format!("{id}: {err}")), - } - } - finish(&mut e, args) -} - -fn script(args: &[String]) -> ExitCode { - let Some(path) = args.first() else { return fail("script FILE") }; - let options: Vec<(&str, bool)> = ENGINE_OPTIONS.iter().copied().chain([("--keep-going", false)]).collect(); - if let Err(e) = check_options(&args[1..], &options) { - return fail(e); - } - let text = match std::fs::read_to_string(path) { - Ok(t) => t, - Err(e) => return fail(format!("{path}: {e}")), - }; - let mut e = match load_engine(args) { - Ok(e) => e, - Err(err) => return fail(err), - }; - let keep = args.iter().any(|a| a == "--keep-going"); - for (n, line) in text.lines().enumerate() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - let (id, p) = line.split_once(char::is_whitespace).unwrap_or((line, "{}")); - let params = match serde_json::from_str::(p.trim()) { - Ok(v) => v, - Err(err) => return fail(format!("{path}:{}: bad JSON: {err}", n + 1)), - }; - match e.execute(id, ¶ms) { - Ok(v) => outln!("{id}: {v}"), - Err(err) => { - eprintln!("{path}:{}: {id}: {err}", n + 1); - if !keep { - return ExitCode::FAILURE; - } - } - } - } - finish(&mut e, args) -} - -fn commands(args: &[String]) -> ExitCode { - let filter = args.first().cloned().unwrap_or_default(); - let e = Engine::default(); - for c in soundcraft_engine::command_specs() { - if !filter.is_empty() && !c.id.contains(&filter) && !c.label.to_ascii_lowercase().contains(&filter.to_ascii_lowercase()) { - continue; - } - let i = c.info(&e); - outln!("{:<36} {:<34} {}", i.id, i.label, i.menu.join(" > ")); - } - ExitCode::SUCCESS -} - -fn describe(args: &[String]) -> ExitCode { - let Some(id) = args.first() else { return fail("describe ID") }; - match soundcraft_engine::find_command(id) { - Some(c) => { - outln!("{}", serde_json::to_string_pretty(&c.info(&Engine::default())).unwrap_or_default()); - ExitCode::SUCCESS - } - None => fail(format!("unknown command `{id}`")), - } -} - -/// Control-channel methods. Every other dotted id is an engine command. -fn is_control_method(method: &str) -> bool { - matches!( - method, - "engine.execute" - | "command" - | "engine.commands" - | "engine.parity" - | "session.inspect" - | "document.inspect" - | "ui.inspect" - | "ui.menu.list" - | "ui.menu.invoke" - | "ui.set" - | "ui.move" - | "ui.click" - | "ui.drag" - | "ui.key" - | "ui.text" - | "ui.screenshot" - | "app.quit" - ) -} - -/// A command id is shorthand for `engine.execute`. Documented control methods stay methods. -fn app_request(method: &str, params: Value) -> (String, Value) { - if is_control_method(method) || !method.contains('.') { - (method.to_string(), params) - } else { - ("engine.execute".to_string(), json!({"command": method, "params": params})) - } -} - -fn app(args: &[String]) -> ExitCode { - let port = arg_value(args, "--port").or_else(|| std::env::var("SOUNDCRAFT_CONTROL_PORT").ok()).unwrap_or_else(|| "7979".into()); - let positional: Vec<&String> = args - .iter() - .enumerate() - .filter(|(i, a)| !(a.starts_with("--") || (*i > 0 && args.get(i - 1).is_some_and(|p| p == "--port")))) - .map(|(_, a)| a) - .collect(); - let Some(method) = positional.first() else { return fail("app [--port P] METHOD [JSON]") }; - let params = match positional.get(1) { - Some(p) => match serde_json::from_str::(p) { - Ok(v) => v, - Err(err) => return fail(format!("{method}: bad JSON: {err}")), - }, - None => json!({}), - }; - let mut r = Remote::new(&port); - // A bare command id is shorthand for engine.execute. Control-channel methods stay methods. - let (m, p) = app_request(method, params); - match r.call(&m, p) { - Ok(v) => { - outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()); - ExitCode::SUCCESS - } - Err(e) => fail(e), - } -} - -/// What `mcp` was asked for. -struct McpArgs { - connect: Option, - demo: bool, - roots: Option>, -} - -/// Parse the `mcp` options up front: a malformed or misspelled root flag must not leave the -/// server running unconfined. -fn parse_mcp_args(args: &[String]) -> Result { - let mut connect = None; - let mut demo = false; - let mut roots_args = automation_args::AutomationArgs::default(); - let mut it = args.iter().cloned(); - while let Some(a) = it.next() { - if roots_args.consume(&a, &mut it)? { - continue; - } - match a.as_str() { - "--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?), - "--demo" => demo = true, - other if other.starts_with("--automation-") => return Err(format!("unknown mcp option `{other}`")), - _ => {} - } - } - let read: Vec<&std::path::Path> = roots_args.read_roots.iter().map(std::path::PathBuf::as_path).collect(); - let write: Vec<&std::path::Path> = roots_args.write_roots.iter().map(std::path::PathBuf::as_path).collect(); - let roots = AutomationRoots::new(&read, &write)?; - if roots.is_some() && connect.is_some() { - return Err("--automation-read-root and --automation-write-root confine the in-process server; a running app is not confined by them, \ -so drop --connect (or use --connect without the roots)" - .into()); - } - Ok(McpArgs { connect, demo, roots }) -} - -fn mcp(args: &[String]) -> ExitCode { - let McpArgs { connect, demo, roots } = match parse_mcp_args(args) { - Ok(a) => a, - Err(err) => return fail(err), - }; - let stdin = std::io::stdin(); - let stdout = std::io::stdout(); - let r = if let Some(port) = connect { - let mut s = Server::new(Remote::new(&port)); - s.serve(stdin.lock(), stdout.lock()) - } else { - // `--demo` is the operator's own choice, made before the roots come into force. - let e = if demo { soundcraft_engine::demo::demo_engine() } else { Engine::default() }; - let mut h = Headless::new(e); - if let Some(roots) = roots { - // Every thread of this process, not only the server's: nothing reaches past the roots. - file_access::confine_process(roots.clone()); - eprintln!("soundcraft-cli: files confined: {}", roots.describe()); - h = h.with_automation_roots(Some(roots)); - } - let mut s = Server::new(h); - s.serve(stdin.lock(), stdout.lock()) - }; - match r { - Ok(()) => ExitCode::SUCCESS, - Err(e) => fail(e), - } -} - -fn parity(args: &[String]) -> ExitCode { - let p = soundcraft_engine::catalog::parity_json(); - let mut md = String::new(); - md.push_str("# Parity report\n\nGenerated by `soundcraft-cli parity --write docs/parity-checklist.md` (also `cargo xtask parity`).\n"); - md.push_str("It compares the incumbent's menu tree (feature names observed black-box, `crates/engine/catalog/menus.txt`) with SoundCraft's command registry.\n"); - md.push_str("UI-layer commands (windows, AudioSuite) are counted by the app's own report (`engine.parity` over the control channel).\n\n"); - md.push_str(&format!( - "**Menu items implemented by the engine: {} / {} ({}%)**\n\n| Menu | Implemented | Total |\n|---|---:|---:|\n", - p["implemented"], p["total"], p["percent"] - )); - for m in p["per_menu"].as_array().cloned().unwrap_or_default() { - md.push_str(&format!("| {} | {} | {} |\n", m["menu"].as_str().unwrap_or(""), m["implemented"], m["total"])); - } - md.push_str("\n## Not yet implemented\n\n"); - for m in p["missing"].as_array().cloned().unwrap_or_default() { - md.push_str(&format!("- {}\n", m.as_str().unwrap_or(""))); - } - if let Some(path) = arg_value(args, "--write") { - if let Err(e) = std::fs::write(&path, &md) { - return fail(format!("{path}: {e}")); - } - outln!("wrote {path}: {}% ({}/{})", p["percent"], p["implemented"], p["total"]); - } else { - outln!("{md}"); - } - ExitCode::SUCCESS -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn command_ids_are_execute_shorthand_and_control_methods_stay_methods() { - let (m, p) = app_request("engine.history", json!({})); - assert_eq!(m, "engine.execute"); - assert_eq!(p["command"], "engine.history"); - let (m, p) = app_request("ui.theme", json!({"mode": "light"})); - assert_eq!(m, "engine.execute"); - assert_eq!(p["params"]["mode"], "light"); - let (m, _) = app_request("session.new", json!({"name": "Session A"})); - assert_eq!(m, "engine.execute"); - let (m, _) = app_request("track.new", json!({})); - assert_eq!(m, "engine.execute"); - for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] { - assert_eq!(app_request(method, json!({})).0, method); - } - } - - #[test] - fn convert_rejects_invalid_rate_and_bit_depth() { - assert_eq!(parse_rate(None), Ok(None)); - assert_eq!(parse_rate(Some("44100")), Ok(Some(44_100))); - assert!(parse_rate(Some("4410x")).is_err()); - assert!(parse_rate(Some("0")).is_err()); - assert!(matches!(parse_bit_depth(None), Ok(soundcraft_audio_io::BitDepth::Int24))); - assert!(matches!(parse_bit_depth(Some("16")), Ok(soundcraft_audio_io::BitDepth::Int16))); - assert!(matches!(parse_bit_depth(Some("32f")), Ok(soundcraft_audio_io::BitDepth::Float32))); - assert!(parse_bit_depth(Some("8")).is_err()); - } - - #[test] - fn convert_dither_flags() { - let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); - assert_eq!(parse_dither(&args(&["in.wav", "out.wav"])), Ok(None)); - assert_eq!(parse_dither(&args(&["in.wav", "out.wav", "--dither"])), Ok(Some(true))); - assert_eq!(parse_dither(&args(&["in.wav", "out.wav", "--no-dither"])), Ok(Some(false))); - assert!(parse_dither(&args(&["in.wav", "out.wav", "--dither", "--no-dither"])).is_err()); - } - - #[test] - fn convert_dithers_only_when_resolution_is_lost() { - use soundcraft_audio_io::{BitDepth, SampleFormat}; - // Same depth or wider: the samples fit exactly. - assert!(!auto_dither(SampleFormat::Int16, BitDepth::Int16, false)); - assert!(!auto_dither(SampleFormat::Int16, BitDepth::Int24, false)); - assert!(!auto_dither(SampleFormat::Int24, BitDepth::Int24, false)); - assert!(!auto_dither(SampleFormat::Int8, BitDepth::Int16, false)); - // Float output never dithers. - assert!(!auto_dither(SampleFormat::Float32, BitDepth::Float32, true)); - assert!(!auto_dither(SampleFormat::Int24, BitDepth::Float32, false)); - // Fewer bits, a float or lossy source, or processed samples: dither. - assert!(auto_dither(SampleFormat::Int24, BitDepth::Int16, false)); - assert!(auto_dither(SampleFormat::Float32, BitDepth::Int24, false)); - assert!(auto_dither(SampleFormat::Compressed, BitDepth::Int16, false)); - assert!(auto_dither(SampleFormat::Int32, BitDepth::Int24, false)); - assert!(auto_dither(SampleFormat::Int16, BitDepth::Int16, true)); - } - - #[test] - fn missing_media_gets_one_warning_each() { - assert!(missing_warnings(&[]).is_empty()); - let w = missing_warnings(&["a.wav".to_string(), "b.wav: decode failed".to_string()]); - assert_eq!(w, vec!["warning: missing media: a.wav", "warning: missing media: b.wav: decode failed"]); - } - - #[test] - fn cmd_spec_parses_id_and_json() { - assert_eq!(parse_cmd_spec("a.b").unwrap(), ("a.b".to_string(), json!({}))); - assert_eq!(parse_cmd_spec("a.b={\"x\":1}").unwrap(), ("a.b".to_string(), json!({"x": 1}))); - } - - #[test] - fn cmd_spec_rejects_truncated_json() { - let err = parse_cmd_spec("a.b={\"x\":").unwrap_err(); - assert!(err.starts_with("a.b: bad JSON"), "{err}"); - } - - #[test] - fn help_text_is_only_the_usage_block() { - let help = help_text(); - assert!(help.starts_with("soundcraft-cli info FILE")); - assert!(help.ends_with("soundcraft-cli plugins list built-in plugins")); - assert!(help.contains("--automation-read-root DIR") && help.contains("--automation-write-root DIR")); - assert!(!help.contains("```")); - assert!(!help.contains("#![") && !help.contains("use serde_json")); - } + std::process::exit(code); } diff --git a/apps/soundcraft-cli/src/mcp.rs b/apps/soundcraft-cli/src/mcp.rs new file mode 100644 index 00000000..874c85ec --- /dev/null +++ b/apps/soundcraft-cli/src/mcp.rs @@ -0,0 +1,46 @@ +use super::args::McpArgs; +use super::error::CliError; +use soundcraft_automation::{ControlTarget, Headless, Remote, mcp::Server}; +use soundcraft_engine::Engine; +use soundcraft_engine::file_access::{self, AutomationRoots}; +use std::io::Write; + +/// What `mcp` serves. +struct Setup { + connect: Option, + demo: bool, + roots: Option>, +} + +/// Open the roots before the server starts: a folder that can't be opened must not leave the +/// server running unconfined. +fn setup(args: &McpArgs) -> Result { + let read: Vec<&std::path::Path> = args.automation.automation_read_root.iter().map(std::path::PathBuf::as_path).collect(); + let write: Vec<&std::path::Path> = args.automation.automation_write_root.iter().map(std::path::PathBuf::as_path).collect(); + let roots = AutomationRoots::new(&read, &write)?; + Ok(Setup { connect: args.connect.clone(), demo: args.demo, roots }) +} + +/// Serves on the process's real stdin and stdout; only the notes go to `err`. +pub(crate) fn mcp(args: &McpArgs, err: &mut dyn Write) -> Result<(), CliError> { + let Setup { connect, demo, roots } = setup(args)?; + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + let served = if let Some(target) = connect { + let mut s = Server::new(Remote::new(&target)); + s.serve(stdin.lock(), stdout.lock()) + } else { + // `--demo` is the operator's own choice, made before the roots come into force. + let e = if demo { soundcraft_engine::demo::demo_engine() } else { Engine::default() }; + let mut h = Headless::new(e); + if let Some(roots) = roots { + // Every thread of this process, not only the server's: nothing reaches past the roots. + file_access::confine_process(roots.clone()); + outln!(err, "soundcraft-cli: files confined: {}", roots.describe()); + h = h.with_automation_roots(Some(roots)); + } + let mut s = Server::new(h); + s.serve(stdin.lock(), stdout.lock()) + }; + served.map_err(CliError::Serve) +} diff --git a/apps/soundcraft-cli/src/output.rs b/apps/soundcraft-cli/src/output.rs new file mode 100644 index 00000000..f6384222 --- /dev/null +++ b/apps/soundcraft-cli/src/output.rs @@ -0,0 +1,32 @@ +/// Print to a writer without panicking on a closed pipe. A write error must not skip later work +/// such as `--bounce` or `--save`, and must not by itself report success. +macro_rules! outln { + ($w:expr, $($t:tt)*) => {{ + let _ = writeln!($w, $($t)*); + }}; +} + +/// Print `value` as JSON: pretty-printed, or on one line when `compact`. Every subcommand that +/// prints a JSON document goes through here, so `--compact` means the same thing everywhere. +pub(crate) fn print_json(out: &mut dyn std::io::Write, value: &impl serde::Serialize, compact: bool) { + let text = if compact { serde_json::to_string(value) } else { serde_json::to_string_pretty(value) }; + outln!(out, "{}", text.unwrap_or_default()); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn compact_is_one_line_and_pretty_is_the_same_value_over_several() { + let v = json!({"a": [1, 2], "b": {"c": "d"}}); + let (mut pretty, mut compact) = (Vec::new(), Vec::new()); + print_json(&mut pretty, &v, false); + print_json(&mut compact, &v, true); + let (pretty, compact) = (String::from_utf8(pretty).unwrap_or_default(), String::from_utf8(compact).unwrap_or_default()); + assert!(pretty.trim_end().lines().count() > 1); + assert_eq!(compact, "{\"a\":[1,2],\"b\":{\"c\":\"d\"}}\n"); + assert_eq!(serde_json::from_str::(&pretty).ok(), Some(v)); + } +} diff --git a/apps/soundcraft-cli/src/session.rs b/apps/soundcraft-cli/src/session.rs new file mode 100644 index 00000000..20e17b1a --- /dev/null +++ b/apps/soundcraft-cli/src/session.rs @@ -0,0 +1,111 @@ +use super::args::{CmdSpec, EngineArgs, RunArgs, ScriptArgs}; +use super::error::{CliError, unicode}; +use super::output::print_json; +use serde_json::{Value, json}; +use soundcraft_engine::Engine; +use std::io::Write; + +/// One stderr line per media file a session refers to but could not load (the exit code is unchanged). +pub(crate) fn warn_missing(err: &mut dyn Write, missing: &[String]) { + for m in missing { + outln!(err, "warning: missing media: {m}"); + } +} + +/// The outputs go to the engine as JSON text, so a non-Unicode one is refused before any command runs. +fn load_engine(args: &EngineArgs, err: &mut dyn Write) -> Result { + if let Some(bounce) = &args.bounce { + unicode(bounce)?; + } + if let Some(save) = args.save_path() { + unicode(&save)?; + } + if let Some(p) = &args.input { + let mut e = Engine::default(); + let missing = soundcraft_engine::io::open_session(&mut e, p)?; + warn_missing(err, &missing); + Ok(e) + } else if args.demo { + Ok(soundcraft_engine::demo::demo_engine()) + } else { + Ok(Engine::default()) + } +} + +fn finish(e: &mut Engine, args: &EngineArgs, out: &mut dyn Write) -> Result<(), CliError> { + if let Some(path) = &args.bounce { + let mut p = json!({"path": unicode(path)?}); + if let Some(s) = &args.start { + p["start"] = s.to_json(); + } + if let Some(s) = &args.end { + p["end"] = s.to_json(); + } + // No range given: bounce the whole session, not whatever edit selection the commands left. + if p.get("start").is_none() && p.get("end").is_none() { + p["start"] = json!(0); + p["end"] = json!(e.session().content_end().max(1)); + } + let v = e.execute("file.bounce_mix", &p)?; + outln!(out, "{v}"); + } + if let Some(path) = args.save_path() { + let v = e.execute("session.save", &json!({"path": unicode(&path)?, "replace": true}))?; + outln!(out, "{v}"); + } + if args.inspect { + print_json(out, &soundcraft_engine::inspect::session(e, false), args.compact); + } + Ok(()) +} + +pub(crate) fn run_cmds(args: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut e = load_engine(&args.engine, err)?; + for CmdSpec { id, params } in &args.cmd { + match e.execute(id, params) { + Ok(v) => outln!(out, "{id}: {v}"), + Err(source) => return Err(CliError::Command { id: id.clone(), source }), + } + } + finish(&mut e, &args.engine, out) +} + +pub(crate) fn script(args: &ScriptArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let path = &args.file; + let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?; + let mut e = load_engine(&args.engine, err)?; + let keep = args.keep_going; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (id, p) = line.split_once(char::is_whitespace).unwrap_or((line, "{}")); + let params = serde_json::from_str::(p.trim()).map_err(|source| CliError::ScriptJson { path: path.clone(), line: n + 1, source })?; + match e.execute(id, ¶ms) { + Ok(v) => outln!(out, "{id}: {v}"), + Err(source) => { + let failure = CliError::ScriptLine { path: path.clone(), line: n + 1, id: id.to_owned(), source }; + if !keep { + return Err(failure); + } + outln!(err, "{failure}"); + } + } + } + finish(&mut e, &args.engine, out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn missing_media_gets_one_warning_each() { + let mut err = Vec::new(); + warn_missing(&mut err, &[]); + assert!(err.is_empty()); + warn_missing(&mut err, &["a.wav".to_string(), "b.wav: decode failed".to_string()]); + assert_eq!(String::from_utf8(err).unwrap(), "warning: missing media: a.wav\nwarning: missing media: b.wav: decode failed\n"); + } +} diff --git a/apps/soundcraft-cli/tests/it/behaviour.rs b/apps/soundcraft-cli/tests/it/behaviour.rs new file mode 100644 index 00000000..ce0076d1 --- /dev/null +++ b/apps/soundcraft-cli/tests/it/behaviour.rs @@ -0,0 +1,550 @@ +//! How `soundcraft-cli` parses its arguments and reports results today, run as the real binary. +//! A change to the command line's behaviour updates them on purpose. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use soundcraft_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileFormat}; + +/// What one run of the binary produced. +struct Invoke { + code: i32, + stdout: String, + stderr: String, +} + +/// Runs the binary in `dir` with empty stdin and no control-port variable. +fn invoke(dir: &Path, args: &[&str]) -> Invoke { + invoke_env(dir, args, None) +} + +fn invoke_env(dir: &Path, args: &[&str], control_port: Option<&str>) -> Invoke { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli")); + cmd.env("SOUNDCRAFT_NO_PREFS", "1").env_remove("SOUNDCRAFT_CONTROL_PORT"); + if let Some(port) = control_port { + cmd.env("SOUNDCRAFT_CONTROL_PORT", port); + } + let out = cmd.current_dir(dir).args(args).stdin(Stdio::null()).output().unwrap(); + Invoke { code: out.status.code().unwrap(), stdout: String::from_utf8(out.stdout).unwrap(), stderr: String::from_utf8(out.stderr).unwrap() } +} + +/// A fresh directory holding `in.wav` (200 samples, 16-bit mono, 48 kHz) and `s.txt` (a one-command script). +fn sandbox(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("sc-cli-behaviour-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut buf = AudioBuffer::new(48_000, 1, 200); + for (i, d) in buf.channels[0].iter_mut().enumerate() { + *d = i as f32 / 400.0; + } + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Int16, dither: false, bwf: None }; + std::fs::write(dir.join("in.wav"), soundcraft_audio_io::encode(&buf, &opts).unwrap()).unwrap(); + std::fs::write(dir.join("s.txt"), "track.new {}\n").unwrap(); + dir +} + +/// The sample rate of the WAV `name` in `dir`. +fn rate_of(dir: &Path, name: &str) -> u32 { + soundcraft_audio_io::probe(&std::fs::read(dir.join(name)).unwrap(), None).unwrap().sample_rate +} + +/// Bit depth of the WAV `name` in `dir`, as the probe reports the sample format. +fn format_of(dir: &Path, name: &str) -> String { + format!("{:?}", soundcraft_audio_io::probe(&std::fs::read(dir.join(name)).unwrap(), None).unwrap().sample_format) +} + +/// Exit 1, nothing on stdout, and exactly `error: {message}` on stderr. +#[track_caller] +fn assert_fails(got: &Invoke, message: &str) { + assert_eq!(got.code, 1, "stderr: {}", got.stderr); + assert_eq!(got.stdout, ""); + assert_eq!(got.stderr, format!("error: {message}\n")); +} + +/// Exit 0 with nothing on either stream. +#[track_caller] +fn assert_silent_success(got: &Invoke) { + assert_eq!((got.code, got.stdout.as_str(), got.stderr.as_str()), (0, "", "")); +} + +/// Exit 2, nothing on stdout, and a clap usage error starting with `error: {message}` on stderr. +#[track_caller] +fn assert_usage_error(got: &Invoke, message: &str) { + assert_eq!(got.code, 2, "stderr: {}", got.stderr); + assert_eq!(got.stdout, ""); + assert!(got.stderr.starts_with(&format!("error: {message}")), "{}", got.stderr); +} + +/// The OS's message for a missing file: error 2 is `ENOENT` on Unix and `ERROR_FILE_NOT_FOUND` on Windows. +fn not_found() -> std::io::Error { + std::io::Error::from_raw_os_error(2) +} + +/// Exit 1 with the refused-connection message for `port`; the OS's text for the refusal differs by platform. +#[track_caller] +fn assert_refused(got: &Invoke, port: u16) { + assert_eq!((got.code, got.stdout.as_str()), (1, "")); + let prefix = format!("error: cannot reach SoundCraft at 127.0.0.1:{port}: "); + assert!(got.stderr.starts_with(&prefix) && got.stderr.contains(" (os error ") && got.stderr.ends_with(")\n"), "{}", got.stderr); +} + +// ---- unknown flags ---- + +#[test] +fn unknown_flags_stop_the_work_before_it_starts() { + let dir = sandbox("unknown-flag-reject"); + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "out.wav", "--bogus"]), "unexpected argument '--bogus' found"); + assert_usage_error(&invoke(&dir, &["run", "--bogus", "--save", "s.scraft"]), "unexpected argument '--bogus' found"); + assert_usage_error(&invoke(&dir, &["script", "s.txt", "--bogus"]), "unexpected argument '--bogus' found"); + // A single-dash word is a flag too. + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "out.wav", "-x"]), "unexpected argument '-x' found"); + assert!(!dir.join("out.wav").exists() && !dir.join("s.scraft").exists()); +} + +#[test] +fn convert_flags_may_come_before_or_between_the_positionals() { + let dir = sandbox("convert-order"); + let got = invoke(&dir, &["convert", "--rate", "44100", "in.wav", "a.wav"]); + assert_eq!((got.code, got.stdout.as_str(), got.stderr.as_str()), (0, "wrote a.wav (1 ch, 44100 Hz, 0.00 s)\n", "")); + let got = invoke(&dir, &["convert", "in.wav", "--rate", "44100", "b.wav"]); + assert_eq!((got.code, got.stdout.as_str(), got.stderr.as_str()), (0, "wrote b.wav (1 ch, 44100 Hz, 0.00 s)\n", "")); + assert_eq!((rate_of(&dir, "a.wav"), rate_of(&dir, "b.wav")), (44_100, 44_100)); +} + +// ---- value flags ---- + +#[test] +fn convert_value_flags_take_a_separate_or_inline_value() { + let dir = sandbox("convert-values"); + assert_eq!(invoke(&dir, &["convert", "in.wav", "c.wav", "--rate", "44100"]).stdout, "wrote c.wav (1 ch, 44100 Hz, 0.00 s)\n"); + assert_eq!(invoke(&dir, &["convert", "in.wav", "d.wav", "--rate=44100"]).stdout, "wrote d.wav (1 ch, 44100 Hz, 0.00 s)\n"); + assert_eq!(rate_of(&dir, "c.wav"), 44_100); + assert_eq!(rate_of(&dir, "d.wav"), 44_100); + assert_eq!(invoke(&dir, &["convert", "in.wav", "e.wav", "--bit-depth", "16"]).code, 0); + assert_eq!(invoke(&dir, &["convert", "in.wav", "f.wav", "--bit-depth=32f"]).code, 0); + assert_eq!(format_of(&dir, "e.wav"), "Int16"); + assert_eq!(format_of(&dir, "f.wav"), "Float32"); + assert_eq!(invoke(&dir, &["convert", "in.wav", "h.wav", "--bit-depth", "32"]).code, 0); + assert_eq!(format_of(&dir, "h.wav"), "Float32"); + assert_eq!(invoke(&dir, &["convert", "in.wav", "g.wav"]).code, 0); + assert_eq!(format_of(&dir, "g.wav"), "Int24"); +} + +#[test] +fn convert_value_flag_without_a_value_or_with_a_bad_one_fails() { + let dir = sandbox("convert-bad-values"); + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "o.wav", "--rate"]), "a value is required for '--rate ' but none was supplied"); + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "o.wav", "--bit-depth"]), "a value is required for '--bit-depth <16|24|32f>'"); + // A following flag is the next flag, not the value. + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "o.wav", "--rate", "--normalize"]), "a value is required for '--rate '"); + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "o.wav", "--normalize=1"]), "unexpected value '1' for '--normalize' found"); + assert!(!dir.join("o.wav").exists()); +} + +#[test] +fn repeated_flags_are_usage_errors_in_either_spelling() { + let dir = sandbox("repeat"); + for args in [ + &["convert", "in.wav", "a.wav", "--rate", "44100", "--rate", "22050"][..], + &["convert", "in.wav", "a.wav", "--rate=22050", "--rate", "44100"], + &["convert", "in.wav", "a.wav", "--bit-depth", "16", "--bit-depth", "24"], + &["convert", "in.wav", "a.wav", "--normalize", "--normalize"], + &["run", "--save", "a.scraft", "--save", "b.scraft"], + &["run", "--demo", "--demo"], + &["run", "--demo", "--sample"], + &["script", "s.txt", "--keep-going", "--keep-going"], + &["app", "--port", "1", "--port", "2", "x"], + &["mcp", "--demo", "--demo"], + ] { + let got = invoke(&dir, args); + assert_usage_error(&got, "the argument '--"); + assert_eq!(got.code, 2, "{args:?}"); + } + assert!(!dir.join("a.wav").exists() && !dir.join("a.scraft").exists()); +} + +#[test] +fn convert_input_and_output_errors() { + let dir = sandbox("convert-io"); + assert_fails(&invoke(&dir, &["convert", "nope.wav", "o.wav"]), &format!("nope.wav: {}", not_found())); + assert_fails(&invoke(&dir, &["convert", "in.wav", "o.xyz"]), "o.xyz: cannot write `.xyz` files (supported: wav, wave, bwf, aif, aiff, flac)"); +} + +#[test] +fn run_value_flags_take_a_separate_or_inline_value() { + let dir = sandbox("run-values"); + let tracks = "track.new: {\"tracks\":[1]}\n"; + assert_eq!(invoke(&dir, &["run", "--cmd", "track.new"]).stdout, tracks); + assert_eq!(invoke(&dir, &["run", "--cmd=track.new"]).stdout, tracks); + let save = invoke(&dir, &["run", "--save", "s1.scraft"]); + assert_eq!((save.code, save.stdout.as_str()), (0, "{\"audio_files_written\":0,\"path\":\"s1.scraft\"}\n")); + let save = invoke(&dir, &["run", "--save=s2.scraft"]); + assert_eq!((save.code, save.stdout.as_str()), (0, "{\"audio_files_written\":0,\"path\":\"s2.scraft\"}\n")); + assert!(dir.join("s1.scraft").exists() && dir.join("s2.scraft").exists()); + // --in in both spellings loads the saved session. + for args in [["run", "--in", "s1.scraft", "--inspect"], ["run", "--in=s1.scraft", "--inspect", ""]] { + let args: Vec<&str> = args.into_iter().filter(|a| !a.is_empty()).collect(); + let got = invoke(&dir, &args); + assert_eq!(got.code, 0, "{args:?}: {}", got.stderr); + assert!(got.stdout.contains("\"dirty\": false"), "{args:?}: {}", got.stdout); + } + // --bounce with --start/--end in both spellings. + let spaced = invoke(&dir, &["run", "--demo", "--bounce", "b1.wav", "--start", "0", "--end", "0.1"]); + assert_eq!(spaced.code, 0, "{}", spaced.stderr); + assert!(spaced.stdout.contains("\"path\":\"b1.wav\"") && spaced.stdout.contains("\"seconds\":0.1"), "{}", spaced.stdout); + let inline = invoke(&dir, &["run", "--demo", "--bounce=b2.wav", "--start=0", "--end=0.1"]); + assert_eq!(inline.code, 0, "{}", inline.stderr); + assert!(inline.stdout.contains("\"path\":\"b2.wav\"") && inline.stdout.contains("\"seconds\":0.1"), "{}", inline.stdout); + assert!(dir.join("b1.wav").exists() && dir.join("b2.wav").exists()); +} + +#[test] +fn run_cmd_repeats_and_runs_every_occurrence_in_order() { + let dir = sandbox("run-repeat"); + assert_eq!(invoke(&dir, &["run", "--cmd", "track.new", "--cmd=track.new"]).stdout, "track.new: {\"tracks\":[1]}\ntrack.new: {\"tracks\":[2]}\n"); +} + +#[test] +fn negative_times_are_values_but_other_dash_words_are_not() { + let dir = sandbox("negative-time"); + // The engine counts a position before 0, so the bounce starts a second ahead of the session. + for args in [&["--start", "-1"][..], &["--start=-1"]] { + let mut full = vec!["run", "--demo", "--end", "0.1", "--bounce", "b.wav"]; + full.extend(args); + let got = invoke(&dir, &full); + assert_eq!(got.code, 0, "{}", got.stderr); + assert!(got.stdout.contains("\"seconds\":1.1"), "{}", got.stdout); + } + assert_usage_error(&invoke(&dir, &["run", "--bounce", "-x.wav"]), "unexpected argument '-x' found"); + assert_usage_error(&invoke(&dir, &["run", "--cmd", "-x"]), "unexpected argument '-x' found"); +} + +#[test] +fn script_runs_lines_and_takes_options_before_or_after_the_file() { + let dir = sandbox("script"); + let got = invoke(&dir, &["script", "s.txt"]); + assert_eq!((got.code, got.stdout.as_str(), got.stderr.as_str()), (0, "track.new: {\"tracks\":[1]}\n", "")); + let got = invoke(&dir, &["script", "s.txt", "--save", "sv.scraft"]); + assert_eq!(got.stdout, "track.new: {\"tracks\":[1]}\n{\"audio_files_written\":0,\"path\":\"sv.scraft\"}\n"); + assert!(dir.join("sv.scraft").exists()); + assert_eq!(invoke(&dir, &["script", "s.txt", "--keep-going"]).stdout, "track.new: {\"tracks\":[1]}\n"); + assert_eq!(invoke(&dir, &["script", "--keep-going", "s.txt"]).stdout, "track.new: {\"tracks\":[1]}\n"); + assert_fails(&invoke(&dir, &["script", "nope.txt"]), &format!("nope.txt: {}", not_found())); + assert_fails(&invoke(&dir, &["script", "s.txt", "--in=nope.scraft"]), &format!("nope.scraft: {}", not_found())); +} + +#[test] +fn script_line_errors_stop_unless_keep_going() { + let dir = sandbox("script-errors"); + std::fs::write(dir.join("bad.txt"), "nosuch.cmd {}\ntrack.new {}\n").unwrap(); + std::fs::write(dir.join("badjson.txt"), "track.new {x\n").unwrap(); + // A stopping line error carries the `error:` prefix; a --keep-going one is a bare line. + let stop = invoke(&dir, &["script", "bad.txt"]); + assert_eq!((stop.code, stop.stdout.as_str()), (1, "")); + assert_eq!(stop.stderr, "error: bad.txt:1: nosuch.cmd: unknown command `nosuch.cmd`\n"); + let keep = invoke(&dir, &["script", "bad.txt", "--keep-going"]); + assert_eq!((keep.code, keep.stdout.as_str()), (0, "track.new: {\"tracks\":[1]}\n")); + assert_eq!(keep.stderr, "bad.txt:1: nosuch.cmd: unknown command `nosuch.cmd`\n"); + assert_fails(&invoke(&dir, &["script", "badjson.txt"]), "badjson.txt:1: bad JSON: key must be a string at line 1 column 2"); +} + +#[test] +fn info_prints_json_for_audio_and_fails_for_missing_files() { + let dir = sandbox("info"); + let got = invoke(&dir, &["info", "in.wav"]); + assert_eq!((got.code, got.stderr.as_str()), (0, "")); + assert!( + got.stdout.contains("\"channels\": 1") + && got.stdout.contains("\"sample_rate\": 48000") + && got.stdout.contains("\"sample_format\": \"Int16\""), + "{}", + got.stdout + ); + assert_fails(&invoke(&dir, &["info", "nope.wav"]), &format!("nope.wav: {}", not_found())); +} + +/// The extension decides a session in any case, as the desktop app's `open_path` does. +#[test] +fn info_reads_a_session_whatever_the_extension_case() { + let dir = sandbox("info-session-case"); + assert_eq!(invoke(&dir, &["run", "--demo", "--save", "S.SCRAFT"]).code, 0); + let got = invoke(&dir, &["info", "S.SCRAFT"]); + assert_eq!((got.code, got.stderr.as_str()), (0, "")); + assert!(got.stdout.starts_with("SESSION NAME:"), "{}", got.stdout); +} + +#[test] +fn info_compact_is_the_same_json_on_one_line() { + let dir = sandbox("info-compact"); + let (pretty, compact) = (invoke(&dir, &["info", "in.wav"]), invoke(&dir, &["info", "in.wav", "--compact"])); + assert_eq!((compact.code, compact.stderr.as_str()), (0, "")); + assert_eq!(compact.stdout.trim_end().lines().count(), 1, "{}", compact.stdout); + assert_eq!( + serde_json::from_str::(&pretty.stdout).unwrap(), + serde_json::from_str::(&compact.stdout).unwrap() + ); +} + +#[test] +fn parity_writes_a_report_with_write_in_both_spellings() { + let dir = sandbox("parity"); + let stdout_report = invoke(&dir, &["parity"]); + assert_eq!(stdout_report.code, 0); + assert!(stdout_report.stdout.starts_with("# Parity report\n"), "{}", stdout_report.stdout); + for (flag, name) in [(vec!["--write", "p1.md"], "p1.md"), (vec!["--write=p2.md"], "p2.md")] { + let mut args = vec!["parity"]; + args.extend(flag); + let got = invoke(&dir, &args); + assert_eq!(got.code, 0, "{}", got.stderr); + assert!(got.stdout.starts_with(&format!("wrote {name}: ")), "{}", got.stdout); + assert!(std::fs::read_to_string(dir.join(name)).unwrap().starts_with("# Parity report\n")); + } + assert_usage_error(&invoke(&dir, &["parity", "--write"]), "a value is required for '--write ' but none was supplied"); +} + +// ---- outputs that replace an input ---- + +/// `in.wav`, `s.txt` and a saved session `s.scraft`. +fn sandbox_with_session(tag: &str) -> PathBuf { + let dir = sandbox(tag); + assert_eq!(invoke(&dir, &["run", "--save", "s.scraft"]).code, 0); + dir +} + +#[test] +fn an_output_that_is_an_input_is_refused_before_any_work() { + let dir = sandbox_with_session("out-is-in"); + std::fs::hard_link(dir.join("in.wav"), dir.join("hard.wav")).unwrap(); + let (wav, session, script) = + (std::fs::read(dir.join("in.wav")).unwrap(), std::fs::read(dir.join("s.scraft")).unwrap(), std::fs::read(dir.join("s.txt")).unwrap()); + let in_wav = dir.join("in.wav"); + let absolute = in_wav.to_str().unwrap(); + for out in ["in.wav", "./in.wav", "../{}/in.wav", absolute, "hard.wav"] { + let out = out.replace("{}", dir.file_name().unwrap().to_str().unwrap()); + let got = invoke(&dir, &["convert", "in.wav", &out, "--rate", "44100"]); + assert_usage_error(&got, &format!(" {out} is the file, which it would replace: choose another file, or pass --in-place")); + } + // Nothing ran: no --cmd result, no bounce, no save. + let refused: &[(&[&str], &str)] = &[ + (&["run", "--in", "s.scraft", "--cmd", "track.new", "--save", "s.scraft"], "--save s.scraft is the --in session"), + (&["run", "--in=./s.scraft", "--cmd", "track.new", "--bounce", "s.scraft"], "--bounce s.scraft is the --in session"), + // --in-place lets only --save replace the session. + ( + &["run", "--in", "s.scraft", "--in-place", "--cmd", "track.new", "--bounce", "./s.scraft"], + "--bounce ./s.scraft is the --in session, which it would replace with audio: choose another file", + ), + (&["script", "s.txt", "--in", "s.scraft", "--in-place", "--bounce", "s.scraft"], "--bounce s.scraft is the --in session"), + (&["script", "s.txt", "--in", "s.scraft", "--save", "./s.scraft"], "--save ./s.scraft is the --in session"), + (&["script", "s.txt", "--save", "./s.txt"], "--save ./s.txt is the script file, which it would replace: choose another file"), + (&["script", "s.txt", "--in", "s.scraft", "--in-place", "--bounce", "s.txt"], "--bounce s.txt is the script file"), + (&["run", "--demo", "--cmd", "track.new", "--bounce", "b.wav", "--save", "./b.wav"], "--bounce and --save both name ./b.wav"), + ]; + for (args, message) in refused { + let got = invoke(&dir, args); + assert_usage_error(&got, message); + assert!(got.stderr.contains("\nUsage: soundcraft-cli "), "{}", got.stderr); + } + assert_eq!(std::fs::read(dir.join("in.wav")).unwrap(), wav); + assert_eq!(std::fs::read(dir.join("s.scraft")).unwrap(), session); + assert_eq!(std::fs::read(dir.join("s.txt")).unwrap(), script); + assert!(!dir.join("b.wav").exists()); + assert_usage_error( + &invoke(&dir, &["run", "--in-place", "--save", "s.scraft"]), + "the following required arguments were not provided:\n --in ", + ); +} + +#[cfg(unix)] +#[test] +fn an_output_linked_to_the_input_is_refused() { + let dir = sandbox_with_session("out-is-in-link"); + std::os::unix::fs::symlink("in.wav", dir.join("link.wav")).unwrap(); + std::os::unix::fs::symlink(".", dir.join("here")).unwrap(); + assert_usage_error(&invoke(&dir, &["convert", "in.wav", "link.wav"]), " link.wav is the file"); + assert_usage_error(&invoke(&dir, &["run", "--in", "s.scraft", "--save", "here/s.scraft"]), "--save here/s.scraft is the --in session"); + // Two outputs that don't exist yet, one through a linked folder. + assert_usage_error(&invoke(&dir, &["run", "--bounce", "here/b.wav", "--save", "b.wav"]), "--bounce and --save both name b.wav"); + assert_eq!(rate_of(&dir, "in.wav"), 48_000); +} + +#[test] +fn in_place_replaces_the_input_and_other_files_are_still_replaced() { + let dir = sandbox_with_session("in-place"); + let got = invoke(&dir, &["convert", "in.wav", "./in.wav", "--rate", "44100", "--in-place"]); + assert_eq!(got.code, 0, "{}", got.stderr); + assert_eq!(rate_of(&dir, "in.wav"), 44_100); + let got = invoke(&dir, &["run", "--in", "s.scraft", "--cmd", "track.new", "--save", "s.scraft", "--in-place"]); + assert_eq!(got.stdout, "track.new: {\"tracks\":[1]}\n{\"audio_files_written\":0,\"path\":\"s.scraft\"}\n", "{}", got.stderr); + // The saved session holds that track, so the next one is the second. + assert_eq!(invoke(&dir, &["run", "--in", "s.scraft", "--cmd", "track.new"]).stdout, "track.new: {\"tracks\":[2]}\n"); + // An existing file that is no input is replaced without --in-place. + for rate in ["32000", "22050"] { + let got = invoke(&dir, &["convert", "in.wav", "o.wav", "--rate", rate]); + assert_eq!(got.code, 0, "{}", got.stderr); + } + assert_eq!(rate_of(&dir, "o.wav"), 22_050); + // other.scraft gets the script's track, then is replaced by s.scraft as it is. + let next_track = |session: &str| invoke(&dir, &["run", "--in", session, "--cmd", "track.new"]).stdout; + let got = invoke(&dir, &["script", "s.txt", "--in", "s.scraft", "--save", "other.scraft"]); + assert_eq!(got.code, 0, "{}", got.stderr); + assert_eq!(next_track("other.scraft"), "track.new: {\"tracks\":[3]}\n"); + let got = invoke(&dir, &["run", "--in", "s.scraft", "--save", "other.scraft"]); + assert_eq!(got.code, 0, "{}", got.stderr); + assert_eq!(next_track("other.scraft"), "track.new: {\"tracks\":[2]}\n"); +} + +/// A write that fails leaves the input as it was: the new bytes go to a new file first. +#[cfg(unix)] +#[test] +fn failed_in_place_convert_keeps_the_input() { + use std::os::unix::fs::PermissionsExt; + let dir = sandbox("in-place-fails"); + let before = std::fs::read(dir.join("in.wav")).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap(); + let can_create = std::fs::File::create(dir.join("probe")).is_ok(); + if !can_create { + let got = invoke(&dir, &["convert", "in.wav", "in.wav", "--rate", "44100", "--in-place"]); + assert_eq!(got.code, 1, "{}", got.stderr); + assert_eq!(std::fs::read(dir.join("in.wav")).unwrap(), before); + } + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(std::fs::read_dir(&dir).unwrap().all(|e| !e.unwrap().file_name().to_string_lossy().ends_with(".part"))); +} + +/// An in-place output that is a link to the input replaces the input, and the link stays a link. +#[cfg(unix)] +#[test] +fn in_place_through_a_link_replaces_the_linked_input() { + let dir = sandbox_with_session("in-place-link"); + std::os::unix::fs::symlink("in.wav", dir.join("link.wav")).unwrap(); + std::os::unix::fs::symlink("s.scraft", dir.join("link.scraft")).unwrap(); + let got = invoke(&dir, &["convert", "in.wav", "link.wav", "--rate", "44100", "--in-place"]); + assert_eq!(got.stdout, "wrote link.wav (1 ch, 44100 Hz, 0.00 s)\n", "{}", got.stderr); + assert_eq!(rate_of(&dir, "in.wav"), 44_100); + let got = invoke(&dir, &["run", "--in", "s.scraft", "--cmd", "track.new", "--save", "link.scraft", "--in-place"]); + assert_eq!(got.code, 0, "{}", got.stderr); + // s.scraft holds that track, so the next one is the second. + assert_eq!(invoke(&dir, &["run", "--in", "s.scraft", "--cmd", "track.new"]).stdout, "track.new: {\"tracks\":[2]}\n"); + for link in ["link.wav", "link.scraft"] { + assert!(dir.join(link).symlink_metadata().unwrap().file_type().is_symlink(), "{link}"); + } +} + +// ---- app ---- + +#[test] +fn app_port_comes_from_the_flag_then_the_environment() { + let dir = sandbox("app-env"); + assert_refused(&invoke_env(&dir, &["app", "session.inspect"], Some("1")), 1); + assert_refused(&invoke_env(&dir, &["app", "--port", "2", "session.inspect"], Some("1")), 2); + // The flag wins before the variable is read, so a bad one doesn't matter. + assert_refused(&invoke_env(&dir, &["app", "--port", "2", "session.inspect"], Some("abc")), 2); +} + +#[test] +fn app_takes_an_empty_port_variable_as_unset() { + if std::net::TcpStream::connect("127.0.0.1:7979").is_ok() { + eprintln!("skipped: something listens on 127.0.0.1:7979, the default port"); + return; + } + let dir = sandbox("app-env-empty"); + for empty in ["", " "] { + assert_refused(&invoke_env(&dir, &["app", "session.inspect"], Some(empty)), 7979); + } +} + +#[test] +fn a_bad_port_variable_is_a_usage_error_naming_it() { + let dir = sandbox("app-env-bad"); + for bad in ["abc", "70000", ":80"] { + assert_usage_error( + &invoke_env(&dir, &["app", "session.inspect"], Some(bad)), + &format!("invalid value '{bad}' for 'SOUNDCRAFT_CONTROL_PORT': expected a port, 0-65535, or host:port"), + ); + } +} + +#[test] +fn app_help_names_the_port_variable() { + let got = invoke(&sandbox("app-help"), &["app", "--help"]); + assert_eq!(got.code, 0, "{}", got.stderr); + assert!(got.stdout.contains("[env: SOUNDCRAFT_CONTROL_PORT=]\n [default: 7979]\n"), "{}", got.stdout); +} + +// ---- mcp ---- + +#[test] +fn mcp_accepts_its_flags_in_both_spellings_and_exits_cleanly_on_empty_stdin() { + let dir = sandbox("mcp-ok"); + for args in [vec!["mcp"], vec!["mcp", "--demo"], vec!["mcp", "--connect", "1"], vec!["mcp", "--connect=1"]] { + assert_silent_success(&invoke(&dir, &args)); + } + // A root prints the confinement line to stderr (never stdout). + for args in [&["mcp", "--automation-read-root", "."][..], &["mcp", "--automation-read-root=."][..]] { + let got = invoke(&dir, args); + assert_eq!((got.code, got.stdout.as_str()), (0, "")); + assert!(got.stderr.starts_with("soundcraft-cli: files confined: read ") && got.stderr.ends_with("; write none\n"), "{}", got.stderr); + } + // A repeated write-root flag is accepted in either spelling. + let twice = invoke(&dir, &["mcp", "--automation-write-root=.", "--automation-write-root", "."]); + assert_eq!(twice.code, 0); + assert!( + twice.stderr.starts_with("soundcraft-cli: files confined: read none; write ") && !twice.stderr.contains("; write none"), + "{}", + twice.stderr + ); +} + +#[test] +fn mcp_demo_with_connect_is_a_usage_error() { + let dir = sandbox("mcp-demo-connect"); + assert_usage_error(&invoke(&dir, &["mcp", "--demo", "--connect", "1"]), "the argument '--demo' cannot be used with '--connect '"); +} + +#[test] +fn mcp_roots_with_connect_are_a_usage_error() { + let dir = sandbox("mcp-roots-connect"); + // Refused before any folder is opened, so a missing one isn't reported. + assert_usage_error( + &invoke(&dir, &["mcp", "--connect", "1", "--automation-write-root", "missing"]), + "the argument '--connect ' cannot be used with '--automation-write-root '", + ); + assert_usage_error( + &invoke(&dir, &["mcp", "--automation-read-root=.", "--connect=1"]), + "the argument '--automation-read-root ' cannot be used with '--connect '", + ); +} + +/// A name that isn't valid Unicode works wherever the tool itself reads or writes the file +/// (`convert`); a session or bounce the engine opens or writes by text name is refused (exit 1), +/// naming the file. Run in-process: the names need no shell. +#[cfg(unix)] +#[test] +fn non_unicode_file_names() { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + let dir = sandbox("nonunicode"); + let latin1 = |ext: &str| { + let mut n = b"caf\xe9.".to_vec(); + n.extend_from_slice(ext.as_bytes()); + dir.join(OsString::from_vec(n)) + }; + let run = |args: Vec| { + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = soundcraft_cli::run(args, &mut out, &mut err); + (code, String::from_utf8_lossy(&err).into_owned()) + }; + let (code, err) = run(vec!["convert".into(), dir.join("in.wav").into(), latin1("flac").into()]); + assert_eq!(code, 0, "{err}"); + assert!(std::fs::metadata(latin1("flac")).unwrap().len() > 0); + // A session opens by path; only paths that go into the engine's JSON must be Unicode. + let (code, err) = run(vec!["run".into(), "--demo".into(), "--save".into(), dir.join("s.scraft").into()]); + assert_eq!(code, 0, "{err}"); + std::fs::rename(dir.join("s.scraft"), latin1("scraft")).unwrap(); + let (code, err) = run(vec!["info".into(), latin1("scraft").into()]); + assert_eq!(code, 0, "{err}"); + let (code, err) = run(vec!["run".into(), "--demo".into(), "--bounce".into(), latin1("wav").into()]); + assert_eq!(code, 1); + assert!(err.contains("caf\u{FFFD}.") && err.contains("not valid Unicode"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/soundcraft-cli/tests/it/cli.rs b/apps/soundcraft-cli/tests/it/cli.rs index 82feb1ce..2a95cb38 100644 --- a/apps/soundcraft-cli/tests/it/cli.rs +++ b/apps/soundcraft-cli/tests/it/cli.rs @@ -209,13 +209,13 @@ fn mcp_automation_root_flags_are_checked_up_front() { fails(&["--automation-write-root", dir, "--connect", "7979"], "--connect"); // #874: a flag may be given again, but every folder it names must exist. fails(&["--automation-read-root", dir, "--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root"); - fails(&["--automation-write-root", dir, "--automation-write-root"], "needs a folder"); - fails(&["--automation-read-root"], "needs a folder"); - fails(&["--automation-write-root", "--demo"], "needs a folder"); + fails(&["--automation-write-root", dir, "--automation-write-root"], "a value is required"); + fails(&["--automation-read-root"], "a value is required"); + fails(&["--automation-write-root", "--demo"], "a value is required"); fails(&["--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root"); - fails(&["--automation-write-root="], "needs a non-empty folder"); + fails(&["--automation-write-root="], "a value is required"); // A misspelled root flag must not start an unconfined server. - fails(&["--automation-read-roots", dir], "unknown mcp option"); + fails(&["--automation-read-roots", dir], "unexpected argument '--automation-read-roots'"); // A file is not a folder. std::fs::write(base.join("f.txt"), "x").unwrap(); fails(&["--automation-write-root", base.join("f.txt").to_str().unwrap()], "cannot open the automation write root"); @@ -224,9 +224,9 @@ fn mcp_automation_root_flags_are_checked_up_front() { #[test] fn usage_lists_the_root_flags() { - let o = run(&["--help"]); + let o = run(&["mcp", "--help"]); let help = String::from_utf8_lossy(&o.stdout).into_owned(); - assert!(help.contains("--automation-read-root DIR") && help.contains("--automation-write-root DIR"), "{help}"); + assert!(help.contains("--automation-read-root ") && help.contains("--automation-write-root "), "{help}"); } /// Without `--start`/`--end`, `--bounce` covers the whole session, not a stray edit selection diff --git a/apps/soundcraft-cli/tests/it/main.rs b/apps/soundcraft-cli/tests/it/main.rs index c573712b..f1c44788 100644 --- a/apps/soundcraft-cli/tests/it/main.rs +++ b/apps/soundcraft-cli/tests/it/main.rs @@ -1,5 +1,11 @@ //! Integration tests, built as one test binary: each file is a module. +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod behaviour; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod cli; mod closed_stdout; +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod man_and_completions; +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod run; diff --git a/apps/soundcraft-cli/tests/it/man_and_completions.rs b/apps/soundcraft-cli/tests/it/man_and_completions.rs new file mode 100644 index 00000000..8ed422f0 --- /dev/null +++ b/apps/soundcraft-cli/tests/it/man_and_completions.rs @@ -0,0 +1,55 @@ +//! The clap definition is consistent, and every shell's completions and every man page +//! (`examples/man-and-completions.rs`) can be generated from it. + +use clap::ValueEnum; +use clap_complete::Shell; + +// The example itself, so the test writes the files exactly as the packages get them. +#[allow(dead_code)] +#[path = "../../examples/man-and-completions.rs"] +mod example; + +#[test] +fn command_is_consistent() { + soundcraft_cli::command().debug_assert(); +} + +#[test] +fn completions_generate_for_every_shell() { + for &shell in Shell::value_variants() { + let mut out = Vec::new(); + clap_complete::generate(shell, &mut soundcraft_cli::command(), "soundcraft-cli", &mut out); + assert!(!out.is_empty(), "{shell}"); + } +} + +#[test] +fn man_pages_render_for_the_command_and_every_subcommand() { + let cmd = soundcraft_cli::command(); + for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) { + let mut out = Vec::new(); + clap_mangen::Man::new(page.clone()).render(&mut out).unwrap(); + assert!(!out.is_empty(), "{}", page.get_name()); + } +} + +/// The example writes the five completion files under the names `packaging/linux/package.sh` and +/// `packaging/freebsd/package.sh` install, `soundcraft-cli.1` and a page per subcommand, and no +/// pages for the `help` subcommand. +#[test] +fn the_example_writes_the_files_the_packages_install() { + let dir = std::env::temp_dir().join(format!("sc-cli-{}-man-and-completions", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + example::generate(&dir).unwrap(); + + let mut written: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect(); + written.sort(); + let completions = ["soundcraft-cli.bash", "_soundcraft-cli", "soundcraft-cli.fish", "soundcraft-cli.elv", "_soundcraft-cli.ps1"]; + let subcommands = ["info", "convert", "run", "script", "commands", "describe", "app", "mcp", "parity", "plugins"]; + let mut expected: Vec = completions.map(String::from).into(); + expected.push("soundcraft-cli.1".into()); + expected.extend(subcommands.iter().map(|s| format!("soundcraft-cli-{s}.1"))); + expected.sort(); + assert_eq!(written, expected); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/apps/soundcraft-cli/tests/it/run.rs b/apps/soundcraft-cli/tests/it/run.rs new file mode 100644 index 00000000..60ffff70 --- /dev/null +++ b/apps/soundcraft-cli/tests/it/run.rs @@ -0,0 +1,426 @@ +//! The CLI run in-process through `soundcraft_cli::run`: the tests that need no files, working +//! directory, environment or standard input. Those that do run the real binary (`behaviour.rs`). +//! A change to the command line's behaviour updates them on purpose. + +use soundcraft_cli::run; + +/// What [`run`] returned and wrote. +struct Invoke { + code: i32, + stdout: String, + stderr: String, +} + +fn invoke(args: &[&str]) -> Invoke { + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let code = run(args.iter().copied(), &mut stdout, &mut stderr); + Invoke { code, stdout: String::from_utf8(stdout).unwrap(), stderr: String::from_utf8(stderr).unwrap() } +} + +/// Exit 1, nothing on stdout, and exactly `error: {message}` on stderr. +#[track_caller] +fn assert_fails(got: &Invoke, message: &str) { + assert_eq!(got.code, 1, "stderr: {}", got.stderr); + assert_eq!(got.stdout, ""); + assert_eq!(got.stderr, format!("error: {message}\n")); +} + +/// Exit 0 with nothing on either stream. +#[track_caller] +fn assert_silent_success(got: &Invoke) { + assert_eq!((got.code, got.stdout.as_str(), got.stderr.as_str()), (0, "", "")); +} + +/// Exit 2, nothing on stdout, and a clap usage error on stderr: `error: ` with `message`, ending +/// with the `--help` hint. +#[track_caller] +fn assert_usage_error(got: &Invoke, message: &str) { + assert_eq!(got.code, 2, "stderr: {}", got.stderr); + assert_eq!(got.stdout, ""); + assert!(got.stderr.starts_with(&format!("error: {message}")), "{}", got.stderr); + assert!(got.stderr.ends_with("\n\nFor more information, try '--help'.\n"), "{}", got.stderr); +} + +/// Exit 0, help on stdout, nothing on stderr. +#[track_caller] +fn assert_help(got: &Invoke) -> &str { + assert_eq!((got.code, got.stderr.as_str()), (0, ""), "{}", got.stdout); + &got.stdout +} + +/// The OS's message for a missing file: error 2 is `ENOENT` on Unix and `ERROR_FILE_NOT_FOUND` on Windows. +fn not_found() -> std::io::Error { + std::io::Error::from_raw_os_error(2) +} + +/// Exit 1 with the refused-connection message for `port`; the OS's text for the refusal differs by platform. +#[track_caller] +fn assert_refused(got: &Invoke, port: u16) { + assert_eq!((got.code, got.stdout.as_str()), (1, "")); + let prefix = format!("error: cannot reach SoundCraft at 127.0.0.1:{port}: "); + assert!(got.stderr.starts_with(&prefix) && got.stderr.contains(" (os error ") && got.stderr.ends_with(")\n"), "{}", got.stderr); +} + +#[test] +fn top_level_help_lists_every_subcommand_on_stdout() { + let long = invoke(&["--help"]); + let help = assert_help(&long); + assert!(help.starts_with("soundcraft-cli: SoundCraft without a window\n\nUsage: soundcraft-cli \n"), "{help}"); + for sub in ["info", "convert", "run", "script", "commands", "describe", "app", "mcp", "parity", "plugins", "help"] { + assert!(help.contains(&format!("\n {sub} ")), "{sub}: {help}"); + } + assert!(help.contains("-V, --version") && !help.contains("\n version "), "{help}"); + for spelling in ["-h", "help"] { + let got = invoke(&[spelling]); + assert_eq!((got.code, got.stdout, got.stderr), (0, long.stdout.clone(), String::new()), "{spelling}"); + } +} + +#[test] +fn version_flags_print_the_long_version_to_stdout() { + let expected = format!("soundcraft-cli {} ({} {})\n", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH); + for spelling in ["--version", "-V"] { + let got = invoke(&[spelling]); + assert_eq!((got.code, got.stdout, got.stderr), (0, expected.clone(), String::new()), "{spelling}"); + } +} + +#[test] +fn version_is_not_a_subcommand() { + assert_usage_error(&invoke(&["version"]), "unrecognized subcommand 'version'"); +} + +#[test] +fn help_subcommand_shows_that_subcommands_help() { + let got = invoke(&["help", "convert"]); + let help = assert_help(&got); + assert!(help.starts_with("Convert an audio file"), "{help}"); + assert_eq!(help, assert_help(&invoke(&["convert", "--help"]))); +} + +#[test] +fn help_names_every_format_the_command_reads_and_writes() { + use soundcraft_audio_io::FileFormat; + let read = format!("({})", FileFormat::readable_extensions().join(", ")); + let write = format!("its extension picks the format ({})", FileFormat::writable_extensions().join(", ")); + let convert = invoke(&["convert", "--help"]); + let convert = assert_help(&convert); + assert!(convert.contains(&read) && convert.contains(&write), "{convert}"); + let info = invoke(&["info", "--help"]); + assert!(assert_help(&info).contains(&read), "{}", info.stdout); +} + +#[test] +fn no_arguments_prints_the_help_to_stderr_and_exits_2() { + let got = invoke(&[]); + assert_eq!((got.code, got.stdout.as_str()), (2, "")); + assert_eq!(got.stderr, invoke(&["--help"]).stdout); +} + +#[test] +fn unknown_subcommand_is_a_usage_error() { + assert_usage_error(&invoke(&["bogus"]), "unrecognized subcommand 'bogus'"); + assert_usage_error(&invoke(&["bogus", "--help"]), "unrecognized subcommand 'bogus'"); + // Subcommand names are case sensitive and not abbreviated. + assert_usage_error(&invoke(&["INFO"]), "unrecognized subcommand 'INFO'"); + assert!(invoke(&["plug"]).stderr.contains("tip: a similar subcommand exists: 'plugins'")); + assert_usage_error(&invoke(&["--bogus"]), "unexpected argument '--bogus' found"); +} + +/// Each subcommand's help: its usage line, then every argument and flag it takes. +#[test] +fn every_subcommand_has_help_listing_its_arguments() { + let engine = [ + "--in ", + "--demo", + "--sample", + "--bounce ", + "--start ", + "--end ", + "--save ", + "--inspect", + "--compact", + "--in-place", + ]; + let cases: &[(&str, &str, &[&str])] = &[ + ("info", "info [OPTIONS] ", &["", "--compact"]), + ( + "convert", + "convert [OPTIONS] ", + &["", "", "--bit-depth <16|24|32f>", "--rate ", "--normalize", "--dither", "--no-dither", "--in-place"], + ), + ("run", "run [OPTIONS]", &["--cmd "]), + ("script", "script [OPTIONS] ", &["", "--keep-going"]), + ("commands", "commands [FILTER]", &["[FILTER]"]), + ("describe", "describe [OPTIONS] ", &["", "--compact"]), + ( + "app", + "app [OPTIONS] [JSON]", + &["--port

", "--compact", "", "[JSON]", "[env: SOUNDCRAFT_CONTROL_PORT", "[default: 7979]"], + ), + ( + "mcp", + "mcp [OPTIONS]", + &["--connect ", "--demo", "--automation-read-root

", "--automation-write-root ", "conflict with --connect"], + ), + ("parity", "parity [OPTIONS]", &["--write "]), + ("plugins", "plugins", &[]), + ]; + for &(sub, usage, args) in cases { + let long = invoke(&[sub, "--help"]); + let help = assert_help(&long); + assert!(help.contains(&format!("\nUsage: soundcraft-cli {usage}\n")), "{sub}: {help}"); + let shared: &[&str] = if matches!(sub, "run" | "script") { &engine } else { &[] }; + for arg in args.iter().chain(shared).chain(&["-h, --help"]) { + assert!(help.contains(arg), "{sub} lacks {arg}: {help}"); + } + // `help SUB` is `SUB --help`; `-h` is the one-line-per-flag summary. + assert_eq!(invoke(&["help", sub]).stdout, long.stdout, "help {sub}"); + assert!(assert_help(&invoke(&[sub, "-h"])).contains(&format!("\nUsage: soundcraft-cli {usage}\n")), "{sub} -h"); + } +} + +#[test] +fn help_wins_over_a_mistake_before_it() { + let help = invoke(&["run", "--help"]).stdout; + assert_eq!(assert_help(&invoke(&["run", "--bounce", "--help"])), help); + assert_eq!(assert_help(&invoke(&["run", "--bogus", "--help"])), help); + assert!(assert_help(&invoke(&["convert", "--rate", "-h"])).contains("Usage: soundcraft-cli convert")); + assert!(assert_help(&invoke(&["mcp", "--connect", "--help"])).contains("Usage: soundcraft-cli mcp")); + // After `--`, `--help` is a value. + assert_eq!(invoke(&["info", "--", "--help"]).code, 1); +} + +#[test] +fn run_and_script_value_flags_without_a_value_are_usage_errors() { + for (flag, name) in [("--cmd", "ID[=JSON]"), ("--in", "S.scraft"), ("--save", "S.scraft"), ("--bounce", "OUT"), ("--start", "T"), ("--end", "T")] + { + let message = format!("a value is required for '{flag} <{name}>' but none was supplied"); + assert_usage_error(&invoke(&["run", flag]), &message); + if flag != "--cmd" { + assert_usage_error(&invoke(&["script", "s.txt", flag]), &message); + } + } + // A following flag is not the value. + assert_usage_error(&invoke(&["run", "--bounce", "--inspect"]), "a value is required for '--bounce '"); + assert_usage_error(&invoke(&["script", "s.txt", "--demo", "--bounce"]), "a value is required for '--bounce '"); +} + +#[test] +fn boolean_flags_reject_an_inline_value() { + assert_usage_error(&invoke(&["run", "--demo=1"]), "unexpected value '1' for '--demo' found; no more were expected"); + assert_usage_error(&invoke(&["run", "--inspect=1"]), "unexpected value '1' for '--inspect' found; no more were expected"); + assert_usage_error(&invoke(&["script", "s.txt", "--keep-going=1"]), "unexpected value '1' for '--keep-going' found; no more were expected"); + assert_usage_error(&invoke(&["mcp", "--demo=1"]), "unexpected value '1' for '--demo' found; no more were expected"); +} + +#[test] +fn missing_and_extra_positionals_are_usage_errors() { + assert_usage_error(&invoke(&["info"]), "the following required arguments were not provided:\n "); + assert_usage_error(&invoke(&["convert", "in.wav"]), "the following required arguments were not provided:\n "); + assert_usage_error(&invoke(&["script"]), "the following required arguments were not provided:\n "); + assert_usage_error(&invoke(&["describe"]), "the following required arguments were not provided:\n "); + assert_usage_error(&invoke(&["app", "--port", "1"]), "the following required arguments were not provided:\n "); + for args in [ + &["info", "a", "b"][..], + &["convert", "in.wav", "out.wav", "b"], + &["script", "s.txt", "b"], + &["run", "b"], + &["commands", "bounce", "b"], + &["describe", "file.bounce_mix", "b"], + &["app", "--port", "1", "session.inspect", "{}", "b"], + &["mcp", "b"], + &["parity", "b"], + &["plugins", "b"], + ] { + assert_usage_error(&invoke(args), "unexpected argument 'b' found"); + } +} + +#[test] +fn unknown_flags_are_usage_errors_on_every_subcommand() { + for args in [ + &["info", "in.wav", "--bogus"][..], + &["convert", "in.wav", "out.wav", "--bogus"], + &["run", "--bogus"], + &["script", "s.txt", "--bogus"], + &["commands", "--bogus"], + &["describe", "--bogus"], + &["app", "--bogus", "session.inspect"], + &["mcp", "--bogus"], + &["parity", "--bogus"], + &["plugins", "--bogus"], + ] { + assert_usage_error(&invoke(args), "unexpected argument '--bogus' found"); + } + // A single-dash word is a short flag, and there are none but -h. + assert_usage_error(&invoke(&["run", "-x"]), "unexpected argument '-x' found"); + assert_usage_error(&invoke(&["mcp", "--automation-bogus=x"]), "unexpected argument '--automation-bogus' found"); +} + +/// `args_os`: text that isn't valid Unicode reaches clap instead of aborting the process. +#[cfg(unix)] +#[test] +fn a_non_unicode_argument_is_a_usage_error_not_a_panic() { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let code = run([OsString::from("describe"), OsString::from_vec(b"\xe9.wav".to_vec())], &mut stdout, &mut stderr); + assert_eq!((code, stdout.as_slice()), (2, &b""[..])); + assert!(String::from_utf8_lossy(&stderr).starts_with("error: invalid UTF-8 was detected in one or more arguments")); +} + +/// A bounce or save path goes to the engine as JSON text: a non-Unicode one fails before any command runs. +#[cfg(unix)] +#[test] +fn a_non_unicode_output_fails_before_the_commands_run() { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + for flag in ["--bounce", "--save"] { + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let args = ["run", "--cmd", "track.new", flag].map(OsString::from); + let code = run(args.into_iter().chain([OsString::from_vec(b"\xe9.out".to_vec())]), &mut stdout, &mut stderr); + assert_eq!((code, stdout.as_slice()), (1, &b""[..]), "{flag}: {}", String::from_utf8_lossy(&stderr)); + } +} + +#[test] +fn run_demo_and_sample_are_the_same_flag() { + let demo = invoke(&["run", "--demo", "--inspect"]); + let sample = invoke(&["run", "--sample", "--inspect"]); + assert_eq!((demo.code, sample.code), (0, 0)); + assert_eq!(demo.stdout, sample.stdout); + assert!(demo.stdout.contains("\"name\": \"Verb\""), "{}", demo.stdout); +} + +/// `--compact` prints the same JSON on one line. +#[track_caller] +fn assert_compact_matches_pretty(pretty: &[&str], compact: &[&str]) { + let (p, c) = (invoke(pretty), invoke(compact)); + assert_eq!((p.code, c.code), (0, 0), "{} {}", p.stderr, c.stderr); + assert!(p.stdout.trim_end().contains('\n'), "pretty form spans lines: {}", p.stdout); + assert_eq!(c.stdout.trim_end().lines().count(), 1, "{}", c.stdout); + assert!(c.stdout.ends_with('\n')); + let (p, c): (serde_json::Value, serde_json::Value) = (serde_json::from_str(&p.stdout).unwrap(), serde_json::from_str(&c.stdout).unwrap()); + assert_eq!(p, c); +} + +#[test] +fn compact_prints_describe_and_run_inspect_on_one_line() { + assert_compact_matches_pretty(&["describe", "file.bounce_mix"], &["describe", "file.bounce_mix", "--compact"]); + assert_compact_matches_pretty(&["run", "--demo", "--inspect"], &["run", "--demo", "--inspect", "--compact"]); +} + +#[test] +fn compact_without_inspect_is_a_usage_error() { + assert_usage_error(&invoke(&["run", "--compact"]), "the following required arguments were not provided:\n --inspect"); +} + +#[test] +fn run_command_failures() { + assert_fails(&invoke(&["run", "--cmd", "nosuch.cmd"]), "nosuch.cmd: unknown command `nosuch.cmd`"); + assert_fails(&invoke(&["run", "--in", "nope.scraft"]), &format!("nope.scraft: {}", not_found())); + assert_fails(&invoke(&["run", "--in=nope.scraft"]), &format!("nope.scraft: {}", not_found())); +} + +/// Relations and typed values are checked by clap: exit 2, the message names the flag, and nothing runs. +#[test] +fn flag_relations_and_typed_values_are_usage_errors() { + for (args, message) in [ + (&["convert", "in.wav", "o.wav", "--dither", "--no-dither"][..], "the argument '--dither' cannot be used with '--no-dither'"), + (&["convert", "in.wav", "o.wav", "--rate", "0"], "invalid value '0' for '--rate '"), + (&["convert", "in.wav", "o.wav", "--rate=abc"], "invalid value 'abc' for '--rate '"), + (&["convert", "in.wav", "o.wav", "--bit-depth", "8"], "invalid value '8' for '--bit-depth <16|24|32f>'"), + (&["run", "--in", "s.scraft", "--demo"], "the argument '--in ' cannot be used with '--demo'"), + (&["script", "s.txt", "--in", "s.scraft", "--sample"], "the argument '--in ' cannot be used with '--demo'"), + (&["run", "--start", "1"], "the following required arguments were not provided:\n --bounce "), + (&["script", "s.txt", "--end", "1"], "the following required arguments were not provided:\n --bounce "), + (&["run", "--bounce", "b.wav", "--start", ""], "invalid value '' for '--start '"), + (&["run", "--bounce", "b.wav", "--start", "nan"], "invalid value 'nan' for '--start ': expected a finite number"), + (&["run", "--bounce", "b.wav", "--end", "inf"], "invalid value 'inf' for '--end ': expected a finite number"), + (&["run", "--bounce", "b.wav", "--end", "1e999"], "invalid value '1e999' for '--end ': expected a finite number"), + (&["run", "--cmd", "track.new={", "--bounce", "b.wav"], "invalid value 'track.new={' for '--cmd ': bad JSON:"), + (&["run", "--cmd", "=1"], "invalid value '=1' for '--cmd '"), + (&["describe", ""], "a value is required for ''"), + (&["commands", ""], "a value is required for '[FILTER]'"), + (&["app", ""], "a value is required for ''"), + ] { + let got = invoke(args); + assert_usage_error(&got, message); + } +} + +#[test] +fn a_bad_later_cmd_runs_none_of_them() { + assert_usage_error(&invoke(&["run", "--cmd", "track.new", "--cmd", "track.new={"]), "invalid value 'track.new={'"); +} + +#[test] +fn commands_filters_by_id_or_label() { + let all = invoke(&["commands"]); + assert_eq!((all.code, all.stderr.as_str()), (0, "")); + assert!(all.stdout.starts_with("session.new "), "{}", all.stdout); + let bounce = invoke(&["commands", "bounce"]); + assert!(bounce.stdout.contains("file.bounce_mix ") && !bounce.stdout.contains("session.new"), "{}", bounce.stdout); + // Matching is case-insensitive on the label only: an upper-case filter finds the labels, not the ids. + assert!(invoke(&["commands", "BOUNCE"]).stdout.contains("Bounce Mix...")); + assert_silent_success(&invoke(&["commands", "zzzzqq"])); +} + +#[test] +fn describe_prints_json_for_a_known_id_and_fails_for_an_unknown_one() { + let got = invoke(&["describe", "file.bounce_mix"]); + assert_eq!((got.code, got.stderr.as_str()), (0, "")); + assert!(got.stdout.starts_with("{\n \"id\": \"file.bounce_mix\",\n \"label\": \"Bounce Mix...\""), "{}", got.stdout); + assert_fails(&invoke(&["describe", "nosuch"]), "unknown command `nosuch`"); +} + +#[test] +fn plugins_lists_one_line_per_plugin() { + let got = invoke(&["plugins"]); + assert_eq!((got.code, got.stderr.as_str()), (0, "")); + assert!(got.stdout.starts_with("eq_1band EQ 1-Band Eq\n"), "{}", got.stdout); +} + +#[test] +fn app_reports_a_refused_connection_and_checks_arguments_first() { + for args in [ + vec!["app", "--port", "1", "session.inspect"], + vec!["app", "--port=1", "session.inspect"], + vec!["app", "session.inspect", "--port", "1"], + vec!["app", "--port", "1", "session.inspect", "{}"], + ] { + assert_refused(&invoke(&args), 1); + } + assert_usage_error( + &invoke(&["app", "--port", "1", "session.inspect", "{bad"]), + "invalid value '{bad' for '[JSON]': bad JSON: key must be a string at line 1 column 2", + ); + for bad in ["abc", "", "70000", ":80", "host:", "host:abc"] { + assert_usage_error( + &invoke(&["app", "--port", bad, "session.inspect"]), + &format!("invalid value '{bad}' for '--port

': expected a port, 0-65535, or host:port"), + ); + assert_usage_error(&invoke(&["mcp", "--connect", bad]), &format!("invalid value '{bad}' for '--connect ': expected a port")); + } +} + +#[test] +fn mcp_argument_errors_fail_before_reading_stdin() { + assert_usage_error(&invoke(&["mcp", "--connect"]), "a value is required for '--connect ' but none was supplied"); + assert_usage_error(&invoke(&["mcp", "--connect", "--demo"]), "a value is required for '--connect ' but none was supplied"); + for flag in ["--automation-read-root", "--automation-write-root"] { + let message = format!("a value is required for '{flag}

' but none was supplied"); + assert_usage_error(&invoke(&["mcp", flag]), &message); + assert_usage_error(&invoke(&["mcp", flag, "--demo"]), &message); + assert_usage_error(&invoke(&["mcp", &format!("{flag}=")]), &message); + } + assert_fails( + &invoke(&["mcp", "--automation-read-root", "missing-dir"]), + &format!("cannot open the automation read root `missing-dir`: {}", not_found()), + ); + assert_usage_error( + &invoke(&["mcp", "--automation-read-root", ".", "--connect", "1"]), + "the argument '--automation-read-root ' cannot be used with '--connect '", + ); +} diff --git a/apps/soundcraft-cli/tests/options.rs b/apps/soundcraft-cli/tests/options.rs index 5ca67031..11ed9070 100644 --- a/apps/soundcraft-cli/tests/options.rs +++ b/apps/soundcraft-cli/tests/options.rs @@ -58,7 +58,11 @@ fn convert_rejects_an_unknown_option_instead_of_writing_the_file() { for bad in ["--bitdepth", "--normalise", "--bogus"] { let o = run(&["convert", input.to_str().unwrap(), out.to_str().unwrap(), bad]); assert!(!o.status.success(), "{bad} should fail"); - assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("unknown option {bad}")), "{bad}: {}", String::from_utf8_lossy(&o.stderr)); + assert!( + String::from_utf8_lossy(&o.stderr).contains(&format!("unexpected argument '{bad}' found")), + "{bad}: {}", + String::from_utf8_lossy(&o.stderr) + ); assert!(!out.exists(), "{bad} should not write the output"); } } @@ -71,7 +75,11 @@ fn convert_rejects_an_option_whose_value_is_missing() { for bad in ["--rate", "--bit-depth"] { let o = run(&["convert", input.to_str().unwrap(), out.to_str().unwrap(), bad]); assert!(!o.status.success(), "{bad} should fail"); - assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("{bad} needs a value")), "{bad}: {}", String::from_utf8_lossy(&o.stderr)); + assert!( + String::from_utf8_lossy(&o.stderr).contains(&format!("a value is required for '{bad} ")), + "{bad}: {}", + String::from_utf8_lossy(&o.stderr) + ); assert!(!out.exists(), "{bad} should not write the output"); } } @@ -104,11 +112,11 @@ fn run_rejects_a_misspelled_or_value_less_bounce() { let out = dir.join("x.wav"); let o = run(&["run", "--cmd", "session.new", "--bounce"]); assert!(!o.status.success()); - assert!(String::from_utf8_lossy(&o.stderr).contains("--bounce needs a value"), "{}", String::from_utf8_lossy(&o.stderr)); + assert!(String::from_utf8_lossy(&o.stderr).contains("a value is required for '--bounce '"), "{}", String::from_utf8_lossy(&o.stderr)); let o = run(&["run", "--cmd", "session.new", "--bounces", out.to_str().unwrap()]); assert!(!o.status.success()); - assert!(String::from_utf8_lossy(&o.stderr).contains("unknown option --bounces"), "{}", String::from_utf8_lossy(&o.stderr)); + assert!(String::from_utf8_lossy(&o.stderr).contains("unexpected argument '--bounces' found"), "{}", String::from_utf8_lossy(&o.stderr)); assert!(!out.exists(), "nothing should be bounced"); } diff --git a/apps/soundcraft-web/Cargo.toml b/apps/soundcraft-web/Cargo.toml index 501c026a..d161499b 100644 --- a/apps/soundcraft-web/Cargo.toml +++ b/apps/soundcraft-web/Cargo.toml @@ -15,6 +15,7 @@ path = "src/main.rs" [target.'cfg(target_arch = "wasm32")'.dependencies] soundcraft-engine = { workspace = true } +soundcraft-audio-io.workspace = true soundcraft-ui-egui.workspace = true soundcraft-playback = { workspace = true } soundcraft-model = { workspace = true } diff --git a/apps/soundcraft-web/src/web.rs b/apps/soundcraft-web/src/web.rs index 0f3bf2e0..9cc84010 100644 --- a/apps/soundcraft-web/src/web.rs +++ b/apps/soundcraft-web/src/web.rs @@ -1,5 +1,6 @@ //! The browser shell: the eframe web runner around [`SoundApp`]. +use soundcraft_audio_io::FileFormat; use soundcraft_engine::{Engine, io}; use soundcraft_ui_egui::dialogs::Dialog; use soundcraft_ui_egui::sampler_window::SampleRead; @@ -67,8 +68,6 @@ enum Purpose { } const SESSION_EXTS: &[&str] = &[io::BUNDLE_EXTENSION, soundcraft_model::SESSION_EXTENSION]; -const AUDIO_EXTS: &[&str] = - &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac", "mp3", "ogg", "oga", "m4a", "m4b", "aac", "mp4", "caf", "mkv", "webm"]; const MIDI_EXTS: &[&str] = &["mid", "midi", "smf"]; impl Purpose { @@ -94,11 +93,11 @@ impl Purpose { } } - fn filter(self) -> (&'static str, &'static [&'static str]) { + fn filter(self) -> (&'static str, Vec<&'static str>) { match self { - Self::Session => ("SoundCraft Session", SESSION_EXTS), - Self::Audio => ("Audio", AUDIO_EXTS), - Self::Midi => ("MIDI", MIDI_EXTS), + Self::Session => ("SoundCraft Session", SESSION_EXTS.to_vec()), + Self::Audio => ("Audio", FileFormat::readable_extensions()), + Self::Midi => ("MIDI", MIDI_EXTS.to_vec()), } } } @@ -130,7 +129,7 @@ impl WebShell { let (inbox, ctx) = (self.inbox.clone(), ctx.clone()); wasm_bindgen_futures::spawn_local(async move { let (label, exts) = purpose.filter(); - let Some(file) = rfd::AsyncFileDialog::new().add_filter(label, exts).pick_file().await else { return }; + let Some(file) = rfd::AsyncFileDialog::new().add_filter(label, &exts).pick_file().await else { return }; let bytes = file.read().await; inbox.borrow_mut().push((purpose, file.file_name(), bytes)); ctx.request_repaint(); @@ -228,17 +227,15 @@ fn download(name: &str, bytes: &[u8]) -> Result<(), String> { let document = window.document().ok_or("no document")?; let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); let opts = web_sys::BlobPropertyBag::new(); - opts.set_type(match name.rsplit_once('.').map(|(_, x)| x.to_ascii_lowercase()).as_deref() { + let ext = name.rsplit_once('.').map(|(_, x)| x.to_ascii_lowercase()); + opts.set_type(match ext.as_deref() { Some("scraftz") => "application/zip", - Some("wav") => "audio/wav", - Some("aif" | "aiff") => "audio/aiff", - Some("flac") => "audio/flac", Some("mid" | "midi") => "audio/midi", Some("svg") => "image/svg+xml", Some("txt") => "text/plain", Some("json" | "scraft") => "application/json", Some("musicxml") => "application/vnd.recordare.musicxml+xml", - _ => "application/octet-stream", + ext => ext.and_then(FileFormat::from_extension).map_or("application/octet-stream", FileFormat::mime_type), }); let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?; let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?; diff --git a/apps/soundcraft/Cargo.toml b/apps/soundcraft/Cargo.toml index 113b37c9..bd6acc4c 100644 --- a/apps/soundcraft/Cargo.toml +++ b/apps/soundcraft/Cargo.toml @@ -16,8 +16,11 @@ asio = ["soundcraft-playback/asio"] [dependencies] soundcraft-engine.workspace = true +soundcraft-audio-io.workspace = true soundcraft-ui-egui.workspace = true soundcraft-playback.workspace = true +soundcraft-automation.workspace = true +clap.workspace = true eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links", "clipboard"] } egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } serde_json.workspace = true diff --git a/apps/soundcraft/src/config.rs b/apps/soundcraft/src/config.rs index c576c240..b1a1c4fb 100644 --- a/apps/soundcraft/src/config.rs +++ b/apps/soundcraft/src/config.rs @@ -17,21 +17,13 @@ enum Platform { Other, } -/// SoundCraft's settings folder. A nonempty `$SOUNDCRAFT_CONFIG_DIR` overrides the platform default. -/// The override is the complete directory; no application-name suffix is appended. An explicitly -/// empty value disables the settings directory instead of falling back to a personal profile. -/// Otherwise `portable.txt` beside the executable selects `/SoundCraftData`, when that -/// folder can be written (a read-only medium falls back to the platform default). -pub fn config_dir() -> Option { - static DIR: std::sync::OnceLock> = std::sync::OnceLock::new(); - DIR.get_or_init(|| { - let exe = std::env::current_exe().ok(); - resolve(exe.as_deref().and_then(Path::parent)) - }) - .clone() -} - -fn resolve(exe_dir: Option<&Path>) -> Option { +/// SoundCraft's settings folder, resolved from the variable lookup `get` (see `Env::from_lookup`). +/// A nonempty `$SOUNDCRAFT_CONFIG_DIR` overrides the platform default and is the complete +/// directory; no application-name suffix is appended. An explicitly empty value means no settings +/// folder instead of a fallback to a personal profile (the documented exception to RFC-0012 rule +/// 1.7). Otherwise `portable.txt` beside the executable selects `/SoundCraftData`, when +/// that folder can be written (a read-only medium falls back to the platform default). +pub fn resolve_config_dir(get: impl Fn(&str) -> Option) -> Option { let platform = if cfg!(target_os = "macos") { Platform::Mac } else if cfg!(windows) { @@ -39,11 +31,12 @@ fn resolve(exe_dir: Option<&Path>) -> Option { } else { Platform::Other }; - config_dir_with(platform, |name| std::env::var_os(name), exe_dir) + let exe = std::env::current_exe().ok(); + config_dir_with(platform, get, exe.as_deref().and_then(Path::parent)) } fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> Option { - if let Some(dir) = env("SOUNDCRAFT_CONFIG_DIR") { + if let Some(dir) = env(crate::env::CONFIG_DIR) { return (!dir.is_empty()).then(|| PathBuf::from(dir)); } if let Some(exe_dir) = exe_dir.filter(|d| d.join(PORTABLE_MARKER).is_file()) { diff --git a/apps/soundcraft/src/env.rs b/apps/soundcraft/src/env.rs new file mode 100644 index 00000000..bee06b30 --- /dev/null +++ b/apps/soundcraft/src/env.rs @@ -0,0 +1,154 @@ +//! The environment variables the app reads, read once at startup into [`Env`]. Library crates +//! never read these; `main` passes the values down. Platform variables (`HOME`, `DISPLAY`, ...) +//! and test-only ones stay with the code that needs them. +//! +//! `RUST_LOG` is not a field: the logger reads it ([`rust_log`]) before anything else, so that +//! the warnings [`Switch`] logs for a malformed value reach the log file. + +use std::ffi::OsString; +use std::path::PathBuf; + +use crate::switch::Switch; + +pub(crate) const CONFIG_DIR: &str = "SOUNDCRAFT_CONFIG_DIR"; +pub(crate) const NO_PREFS: &str = "SOUNDCRAFT_NO_PREFS"; +pub(crate) const NO_SYSTEM_FONTS: &str = "SOUNDCRAFT_NO_SYSTEM_FONTS"; +pub(crate) const WAYLAND: &str = "SOUNDCRAFT_WAYLAND"; +pub(crate) const RUST_LOG: &str = "RUST_LOG"; + +/// The variables and their `--help` lines, in the order `--help` lists them. +pub(crate) const VARS: &[(&str, &str)] = &[ + // Read by clap (`env =` on `--control`), not by `Env`. + ("SOUNDCRAFT_CONTROL_PORT", "The --control fallback: a port or host:port, ignored for another host"), + (CONFIG_DIR, "The settings folder (ui.json, Autosave, Presets, logs); empty: none (unlike the others, where empty counts as unset)"), + (NO_PREFS, "1 doesn't read or write preferences and logs to stderr only; 0 or unset is off"), + (NO_SYSTEM_FONTS, "1 uses the built-in fonts only; 0 or unset is off"), + (WAYLAND, "Linux: 1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"), + (RUST_LOG, "Log filter, env_logger style: debug, warn,soundcraft_mix=trace"), +]; + +/// The `--help` Environment section, generated from [`VARS`]. +pub(crate) fn help() -> String { + let width = VARS.iter().map(|(name, _)| name.len()).max().unwrap_or(0); + let mut out = String::from("Environment:\n"); + for (name, line) in VARS { + out.push_str(&format!(" {name:, + pub(crate) no_prefs: Switch, + pub(crate) no_system_fonts: Switch, + #[cfg(any(test, all(unix, not(target_os = "macos"))))] + pub(crate) wayland: Switch, +} + +impl Env { + /// Reads the process environment. Call after the logger is installed, so malformed switches are logged. + pub(crate) fn read() -> Env { + Env::from_lookup(|name| std::env::var_os(name)) + } + + pub(crate) fn from_lookup(get: impl Fn(&str) -> Option) -> Env { + let switch = |name: &str| match get(name) { + None => Switch::Default, + Some(v) => Switch::parse(name, Some(&v.to_string_lossy())), + }; + Env { + config_dir: crate::config::resolve_config_dir(&get), + no_prefs: switch(NO_PREFS), + no_system_fonts: switch(NO_SYSTEM_FONTS), + #[cfg(any(test, all(unix, not(target_os = "macos"))))] + wayland: switch(WAYLAND), + } + } + + /// Runs without preferences (`SOUNDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. + pub(crate) fn prefs_enabled(&self) -> bool { + self.no_prefs != Switch::On + } + + pub(crate) fn system_fonts(&self) -> bool { + self.no_system_fonts != Switch::On + } + + /// Whether to run through XWayland: winit has no file drag-and-drop on Wayland, so dropping + /// files from the file manager showed a "no" cursor. Needs a nonempty `DISPLAY` + /// (`display`); `SOUNDCRAFT_WAYLAND=1` keeps the native backend. + #[cfg(any(test, all(unix, not(target_os = "macos"))))] + pub(crate) fn use_xwayland(&self, display: Option<&OsString>) -> bool { + display.is_some_and(|d| !d.is_empty()) && self.wayland != Switch::On + } +} + +/// The `RUST_LOG` filter, `None` when unset or blank. +pub(crate) fn rust_log() -> Option { + std::env::var(RUST_LOG).ok().filter(|s| !s.trim().is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lookup(vars: &'static [(&'static str, &'static str)]) -> Env { + Env::from_lookup(|name| vars.iter().find(|(n, _)| *n == name).map(|(_, v)| OsString::from(v))) + } + + #[test] + fn variables_are_read_into_typed_fields() { + let env = lookup(&[(CONFIG_DIR, "/c"), (NO_PREFS, "yes"), (NO_SYSTEM_FONTS, "0"), (WAYLAND, "bogus")]); + assert_eq!(env.config_dir, Some(PathBuf::from("/c"))); + assert_eq!((env.no_prefs, env.no_system_fonts, env.wayland), (Switch::On, Switch::Off, Switch::Default)); + } + + #[test] + fn settings_folder_is_resolved_into_env() { + // Empty means no folder, even with a platform folder available. + assert_eq!(lookup(&[(CONFIG_DIR, ""), ("HOME", "/h"), ("XDG_CONFIG_HOME", "/x")]).config_dir, None); + assert_eq!(lookup(&[(CONFIG_DIR, "/c"), ("HOME", "/h")]).config_dir, Some(PathBuf::from("/c"))); + let unset = lookup(&[("HOME", "/h"), ("APPDATA", "/h"), ("XDG_CONFIG_HOME", "/x")]).config_dir; + assert!(unset.is_some_and(|d| d.ends_with("SoundCraft") || d.ends_with("soundcraft") || d.ends_with("SoundCraftData"))); + // Disabling preferences doesn't depend on the folder. + let env = lookup(&[(CONFIG_DIR, "/c"), (NO_PREFS, "1")]); + assert!(env.config_dir.is_some() && !env.prefs_enabled()); + } + + #[test] + fn no_prefs_and_no_system_fonts_turn_features_off() { + assert!(Env::default().prefs_enabled() && Env::default().system_fonts()); + let env = Env { no_prefs: Switch::On, no_system_fonts: Switch::On, ..Env::default() }; + assert!(!env.prefs_enabled() && !env.system_fonts()); + assert!(Env { no_prefs: Switch::Off, ..Env::default() }.prefs_enabled()); + } + + #[test] + fn xwayland_needs_a_display_and_wayland_not_forced() { + let display = OsString::from(":0"); + assert!(Env::default().use_xwayland(Some(&display))); + assert!(Env { wayland: Switch::Off, ..Env::default() }.use_xwayland(Some(&display))); + assert!(!Env { wayland: Switch::On, ..Env::default() }.use_xwayland(Some(&display))); + assert!(!Env::default().use_xwayland(None)); + assert!(!Env::default().use_xwayland(Some(&OsString::new()))); + } + + #[test] + fn help_lists_every_variable() { + let help = help(); + for (name, line) in VARS { + assert!(help.contains(name) && help.contains(line), "{name} missing from\n{help}"); + } + assert_eq!(help.matches("0/off/false/no").count(), 1, "{help}"); + } +} diff --git a/apps/soundcraft/src/launch_args.rs b/apps/soundcraft/src/launch_args.rs new file mode 100644 index 00000000..65c4af1c --- /dev/null +++ b/apps/soundcraft/src/launch_args.rs @@ -0,0 +1,223 @@ +//! The desktop app's command line, as clap types: `soundcraft --help` comes from these doc +//! comments, so the help and the parser can't disagree. Anything they don't declare is a usage +//! error naming it (exit status 2), as is a bad `--control` or `SOUNDCRAFT_CONTROL_PORT`. A file +//! whose name starts with `-` goes after `--`. Another host's `host:port` is a usage error from +//! `--control` and ignored from the variable ([`control_port`]). +//! +//! The control flag is `soundcraft-automation`'s, shared with `soundcraft-cli`. + +use std::ffi::OsString; +use std::path::PathBuf; + +use clap::builder::StyledStr; +use clap::error::{ContextKind, ContextValue, ErrorKind}; +use clap::parser::ValueSource; +use clap::{Command, CommandFactory, FromArgMatches, Parser}; +use soundcraft_automation::ControlTarget; +use soundcraft_automation::args::{ControlServerArgs, blank_env_is_unset, name_env_vars}; + +/// Opens SoundCraft with the given files +#[derive(Parser)] +#[command(name = "soundcraft", version = soundcraft_automation::args::long_version(), after_help = crate::env::help())] +pub(crate) struct LaunchArgs { + /// Sessions, audio and MIDI files to open. Put `--` before a name that starts with `-` + pub(crate) files: Vec, + /// Start with the demo session + #[arg(long, visible_alias = "sample")] + pub(crate) demo: bool, + /// Don't open an audio device + #[arg(long)] + pub(crate) no_audio: bool, + #[command(flatten)] + control: ControlServerArgs, + /// The port the control server starts on, from `control` ([`control_port`]). + #[arg(skip)] + pub(crate) control_port: Option, +} + +/// The command line, where an empty or blank variable counts as unset. +pub(crate) fn command() -> Command { + LaunchArgs::command().mut_args(blank_env_is_unset) +} + +/// Parses the launch arguments (without the program name) with `cmd`, from [`command`]. macOS +/// passes a process serial number (`-psn_…`) when an app is started from Finder on old versions: +/// it is dropped first, unless it comes after `--`. A bad value from a variable is a usage error +/// naming the variable. +pub(crate) fn parse(mut cmd: Command, args: impl IntoIterator) -> Result { + let mut options = true; + let args: Vec = args + .into_iter() + .filter(|a| { + options &= a != "--"; + !(options && a.to_str().is_some_and(|s| s.starts_with("-psn_"))) + }) + .collect(); + let argv = std::iter::once(OsString::from("soundcraft")).chain(args.iter().cloned()); + let matches = cmd.try_get_matches_from_mut(argv).map_err(|e| name_env_vars(e, &cmd, &args))?; + let mut launch = LaunchArgs::from_arg_matches(&matches)?; + launch.control_port = control_port(launch.control.control.take(), matches.value_source("control")).map_err(|e| e.into_clap(&mut cmd))?; + Ok(launch) +} + +/// The port the control server starts on, from `--control` or `SOUNDCRAFT_CONTROL_PORT` +/// (`source`). The server listens on 127.0.0.1 only, so it can't serve another host's +/// `host:port`. From the flag that is a usage error. The variable is `soundcraft-cli app`'s too and +/// may point it at another machine, so from there it is ignored with a warning and the app opens +/// without a control server. +fn control_port(value: Option, source: Option) -> Result, RemoteHost> { + match value { + None => Ok(None), + Some(target) if target.is_loopback() => Ok(Some(target.port)), + Some(target) if source == Some(ValueSource::EnvVariable) => { + log::warn!("SOUNDCRAFT_CONTROL_PORT={target} names another host, so no control server starts: it listens on 127.0.0.1 only"); + Ok(None) + } + Some(target) => Err(RemoteHost(target)), + } +} + +/// A `--control` `host:port` naming another host. +#[derive(Debug, PartialEq)] +struct RemoteHost(ControlTarget); + +impl RemoteHost { + /// clap's invalid-value error for `--control`, with the reason as a tip. + fn into_clap(self, cmd: &mut Command) -> clap::Error { + let flag = cmd.get_arguments().find(|a| a.get_id() == "control").map_or_else(|| "--control".to_owned(), ToString::to_string); + let tip = + StyledStr::from("the control server listens on 127.0.0.1 only: give a port, or host:port with a loopback host (127.0.0.1, localhost)"); + let mut error = clap::Error::new(ErrorKind::ValueValidation).with_cmd(cmd); + error.insert(ContextKind::InvalidArg, ContextValue::String(flag)); + error.insert(ContextKind::InvalidValue, ContextValue::String(self.0.to_string())); + error.insert(ContextKind::Suggested, ContextValue::StyledStrs(vec![tip])); + error.insert(ContextKind::Usage, ContextValue::StyledStr(cmd.render_usage())); + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::error::ErrorKind; + + /// Parse without the variable, so one exported where the tests run can't change them (the + /// process tests in `tests/launch_flags.rs` cover it). + fn parse_args(args: &[&str]) -> Result { + parse(command().mut_args(|a| a.env(None::<&str>)), args.iter().map(OsString::from)) + } + + fn usage_error(args: &[&str]) -> String { + let Err(e) = parse_args(args) else { panic!("{args:?} parsed") }; + assert_eq!(e.exit_code(), 2, "{args:?}: {e}"); + e.to_string() + } + + #[test] + fn command_is_consistent() { + command().debug_assert(); + } + + #[test] + fn flags_and_files_are_parsed() { + let a = parse_args(&["--demo", "--no-audio", "--control", "50494", "a.scraft", "b.wav"]).unwrap(); + assert!(a.demo && a.no_audio); + assert_eq!(a.control_port, Some(50494)); + assert_eq!(a.files, [PathBuf::from("a.scraft"), PathBuf::from("b.wav")]); + assert!(parse_args(&["--sample"]).unwrap().demo); + let none = parse_args(&[]).unwrap(); + assert!(!none.demo && !none.no_audio && none.control_port.is_none() && none.files.is_empty()); + } + + #[test] + fn version_and_help_stop_parsing() { + for flag in ["--version", "-V"] { + let e = parse_args(&[flag, "--control"]).err().unwrap(); + assert_eq!((e.kind(), e.exit_code()), (ErrorKind::DisplayVersion, 0)); + assert_eq!(e.to_string(), format!("soundcraft {}\n", soundcraft_automation::args::long_version())); + } + let e = parse_args(&["-h", "--bogus"]).err().unwrap(); + assert_eq!((e.kind(), e.exit_code()), (ErrorKind::DisplayHelp, 0)); + let help = e.to_string(); + for text in ["--demo", "--sample", "--no-audio", "--control "] { + assert!(help.contains(text), "{text}: {help}"); + } + let help = command().render_help().to_string(); + assert!(help.contains("[env: SOUNDCRAFT_CONTROL_PORT"), "{help}"); + for var in ["SOUNDCRAFT_CONFIG_DIR", "SOUNDCRAFT_NO_PREFS", "SOUNDCRAFT_NO_SYSTEM_FONTS", "SOUNDCRAFT_WAYLAND", "RUST_LOG"] { + assert!(help.contains(&format!("\n {var} ")), "{var}: {help}"); + } + } + + #[test] + fn a_bad_control_port_is_a_usage_error_naming_it() { + assert!(usage_error(&["--control", "78787"]).contains("invalid value '78787' for '--control '")); + assert!(usage_error(&["--control", "nope"]).contains("invalid value 'nope'")); + assert!(usage_error(&["--control"]).contains("a value is required for '--control '")); + assert!(usage_error(&["--control", "--demo"]).contains("a value is required for '--control '")); + assert!(usage_error(&["--control", "-1"]).contains("invalid value '-1' for '--control '")); + let remote = usage_error(&["--control", "10.0.0.5:7979"]); + assert!( + remote.starts_with("error: invalid value '10.0.0.5:7979' for '--control '\n\n tip: the control server listens on 127.0.0.1 only"), + "{remote}" + ); + assert!(remote.contains("\nUsage: soundcraft "), "{remote}"); + assert!(usage_error(&["--control", "::1:7979"]).contains("invalid value '::1:7979' for '--control '")); + } + + /// The variable may point `soundcraft-cli app` at another machine: the app then opens without + /// a control server. + #[test] + fn another_host_is_ignored_only_from_the_variable() { + let remote = || ControlTarget { host: Some("10.0.0.5".to_owned()), port: 7979 }; + assert_eq!(control_port(Some(remote()), Some(ValueSource::EnvVariable)), Ok(None)); + assert_eq!(control_port(Some(remote()), Some(ValueSource::CommandLine)), Err(RemoteHost(remote()))); + let local = ControlTarget { host: None, port: 7979 }; + assert_eq!(control_port(Some(local), Some(ValueSource::EnvVariable)), Ok(Some(7979))); + assert_eq!(control_port(None, None), Ok(None)); + } + + /// The variable `soundcraft-cli app` reads may hold `host:port`: a loopback one gives its port. + #[test] + fn a_loopback_host_and_port_gives_its_port() { + for value in ["127.0.0.1:50494", "localhost:50494"] { + assert_eq!(parse_args(&["--control", value]).unwrap().control_port, Some(50494), "{value}"); + } + } + + /// The control server binds 127.0.0.1, so `[::1]` is another host. + #[test] + fn an_ipv6_loopback_host_is_not_loopback() { + assert!(usage_error(&["--control", "[::1]:50494"]).contains("invalid value '[::1]:50494' for '--control '")); + } + + #[test] + fn unknown_flags_and_repeats_are_usage_errors() { + assert!(usage_error(&["--bogus"]).contains("unexpected argument '--bogus'")); + assert!(usage_error(&["-x"]).contains("unexpected argument '-x'")); + assert!(usage_error(&["--demo", "--demo"]).contains("cannot be used multiple times")); + } + + #[test] + fn double_dash_ends_options() { + let a = parse_args(&["a.wav", "--", "--demo", "-x"]).unwrap(); + assert!(!a.demo); + assert_eq!(a.files, [PathBuf::from("a.wav"), PathBuf::from("--demo"), PathBuf::from("-x")]); + } + + #[test] + fn a_finder_process_serial_number_is_dropped() { + assert_eq!(parse_args(&["-psn_0_12345", "a.wav"]).unwrap().files, [PathBuf::from("a.wav")]); + assert_eq!(parse_args(&["--", "-psn_x.wav"]).unwrap().files, [PathBuf::from("-psn_x.wav")]); + } + + /// A file name that isn't valid Unicode reaches `files` as it is. + #[cfg(unix)] + #[test] + fn non_unicode_file_names_are_kept() { + use std::os::unix::ffi::OsStringExt as _; + let latin1 = OsString::from_vec(b"caf\xe9.wav".to_vec()); + let a = parse(command().mut_args(|a| a.env(None::<&str>)), [latin1.clone()]).unwrap(); + assert_eq!(a.files, [PathBuf::from(latin1)]); + } +} diff --git a/apps/soundcraft/src/logging.rs b/apps/soundcraft/src/logging.rs index c82c58ac..a040dd08 100644 --- a/apps/soundcraft/src/logging.rs +++ b/apps/soundcraft/src/logging.rs @@ -413,13 +413,12 @@ impl log::Log for AppLogger { fn flush(&self) {} } -/// Install the logger (filter from `RUST_LOG`, else [`DEFAULT_FILTER`]); `None` when another +/// Install the logger (filter from `rust_log`, the `RUST_LOG` value, else [`DEFAULT_FILTER`]); `None` when another /// logger was installed first. Call [`AppLogger::attach_dir`] or [`AppLogger::no_file`] once the /// settings directory is known. -pub fn install() -> Option<&'static AppLogger> { +pub fn install(rust_log: Option<&str>) -> Option<&'static AppLogger> { static LOGGER: OnceLock = OnceLock::new(); - let spec = std::env::var("RUST_LOG").ok().filter(|s| !s.trim().is_empty()); - let filter = Filter::parse(spec.as_deref().unwrap_or(DEFAULT_FILTER)); + let filter = Filter::parse(rust_log.unwrap_or(DEFAULT_FILTER)); let max = filter.max(); let logger = LOGGER.get_or_init(|| AppLogger::new(filter, true)); log::set_logger(logger).ok()?; diff --git a/apps/soundcraft/src/main.rs b/apps/soundcraft/src/main.rs index bffb9cb3..8e54a5bd 100644 --- a/apps/soundcraft/src/main.rs +++ b/apps/soundcraft/src/main.rs @@ -1,6 +1,6 @@ //! SoundCraft desktop app. //! -//! Usage: `soundcraft [--demo] [--control ] [--no-audio] [session.scraft | audio files…]` +//! Usage: `soundcraft [--demo] [--control ] [--no-audio] [session.scraft | audio files…]`; `soundcraft --help` lists the flags and `SOUNDCRAFT_CONTROL_PORT`. //! //! `--control ` (or `SOUNDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server //! (`0` picks a free port and prints it): `{"id":1,"method":"ui.inspect","params":{}}` → @@ -13,17 +13,22 @@ mod config; mod control_server; +mod env; #[cfg(any(target_os = "windows", test))] mod graphics; +mod launch_args; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod switch; +use env::Env; +use soundcraft_audio_io::FileFormat; use soundcraft_engine::Engine; use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs}; use std::sync::Arc; -struct App(SoundApp, Option<&'static logging::AppLogger>, #[cfg(target_os = "macos")] Option); +struct App(SoundApp, Option<&'static logging::AppLogger>, Env, #[cfg(target_os = "macos")] Option); /// Sends the title only when it changes, remembered here as X11 and Wayland can't read it back. fn set_title(ctx: &egui::Context, title: String) { @@ -43,20 +48,20 @@ impl eframe::App for App { logger.report_audio_thread(); } #[cfg(target_os = "macos")] - if let Some(menu) = &mut self.2 { + if let Some(menu) = &mut self.3 { menu.process(&mut self.0); } self.0.guarded(|app| app.logic(ctx)); #[cfg(target_os = "macos")] - if let Some(menu) = &mut self.2 { + if let Some(menu) = &mut self.3 { menu.sync(&self.0); } // Files dropped on the window: audio on an instrument track or a Sampler window loads // the sampler; otherwise sessions open and audio/MIDI import. - let dropped: Vec = - self.0.take_dropped_files().iter().map(|f| f.path().to_string_lossy().into_owned()).filter(|s| !s.is_empty()).collect(); - for p in dropped { - open_path(&mut self.0, &p); + for f in self.0.take_dropped_files() { + if !f.path().as_os_str().is_empty() { + dialogs::open_path(&mut self.0, f.path()); + } } if self.0.quit_requested { ctx.send_viewport_cmd(egui::ViewportCommand::Close); @@ -72,7 +77,7 @@ impl eframe::App for App { self.0.ui.ui_scale = self.0.extra.ui_scale; // Saved now rather than at exit: the recent list matters most after a crash. if self.0.take_recent_changed() { - save_prefs(&self.0.ui); + save_prefs(&self.2, &self.0.ui); } // With the system menu bar there is no egui bar showing the window and dirty state, so the // title carries them; elsewhere the egui menu bar already does. @@ -98,7 +103,7 @@ impl eframe::App for App { } fn on_exit(&mut self) { self.0.close_autosave(); - save_prefs(&self.0.ui); + save_prefs(&self.2, &self.0.ui); if let Some(logger) = self.1 { logger.report_audio_thread(); } @@ -109,42 +114,16 @@ impl eframe::App for App { } } -fn open_path(app: &mut SoundApp, p: &str) { - let lower = p.to_ascii_lowercase(); - let r = if lower.ends_with(".scraft") { - dialogs::run_or_ask(app, "session.open", serde_json::json!({"path": p})) - } else if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { - app.run("file.import_midi", serde_json::json!({"path": p})) - } else { - // Decoded in the background so a long file doesn't freeze the window (#597). - let at = app.engine.session().edit.selection.start; - soundcraft_ui_egui::import::start(app, serde_json::json!({"path": p, "at": at})); - Ok(serde_json::Value::Null) - }; - if let Err(e) = r { - log::warn!("{p}: {e}"); - } -} - -/// The per-user settings directory: `ui.json`, `Autosave/`, `Presets/` and `logs/` live here. -fn config_dir() -> Option { - config::config_dir() -} - -fn prefs_path() -> Option { - config_dir().map(|b| b.join("ui.json")) +fn prefs_path(env: &Env) -> Option { + env.config_dir.as_ref().map(|b| b.join("ui.json")) } /// Runs without preferences (`SOUNDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. -fn prefs_enabled() -> bool { - std::env::var_os("SOUNDCRAFT_NO_PREFS").is_none() -} - -fn load_prefs() -> Option { - if !prefs_enabled() { +fn load_prefs(env: &Env) -> Option { + if !env.prefs_enabled() { return None; } - let path = prefs_path()?; + let path = prefs_path(env)?; match config::load_ui(&path) { Ok(state) => state, Err(error) => { @@ -154,11 +133,11 @@ fn load_prefs() -> Option { } } -fn save_prefs(ui: &UiState) { - if !prefs_enabled() { +fn save_prefs(env: &Env, ui: &UiState) { + if !env.prefs_enabled() { return; } - if let Some(path) = prefs_path() + if let Some(path) = prefs_path(env) && let Err(error) = config::save_ui(&path, ui) { log::warn!("{error}"); @@ -172,17 +151,13 @@ fn services() -> Services { let d = match purpose { "session.open" => d.add_filter("SoundCraft Session", &["scraft"]), "file.import_midi" => d.add_filter("MIDI", &["mid", "midi", "smf"]), - _ => d.add_filter( - "Audio", - &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac", "mp3", "ogg", "oga", "m4a", "m4b", "aac", "mp4", "caf", "mkv", "webm"], - ), + _ => d.add_filter("Audio", &FileFormat::readable_extensions()), }; - d.pick_file().map(|p| p.to_string_lossy().into_owned()) + d.pick_file() })), - pick_save: Some(Box::new(|purpose: &str, default: &str| { - let path = std::path::Path::new(default); + pick_save: Some(Box::new(|purpose: &str, path: &std::path::Path| { let mut d = match purpose { - "file.bounce_mix" => rfd::FileDialog::new().add_filter("Audio", &["wav", "aif", "aiff", "flac"]), + "file.bounce_mix" => rfd::FileDialog::new().add_filter("Audio", &FileFormat::writable_extensions()), _ => rfd::FileDialog::new().add_filter("SoundCraft Session", &["scraft"]), }; if let Some(dir) = path.parent().filter(|dir| dir.is_dir()) { @@ -191,11 +166,9 @@ fn services() -> Services { if let Some(n) = path.file_name().and_then(std::ffi::OsStr::to_str) { d = d.set_file_name(n); } - d.save_file().map(|p| p.to_string_lossy().into_owned()) - })), - pick_folder: Some(Box::new(|start: &str| { - rfd::FileDialog::new().set_directory(start).pick_folder().map(|p| p.to_string_lossy().into_owned()) + d.save_file() })), + pick_folder: Some(Box::new(|start: &std::path::Path| rfd::FileDialog::new().set_directory(start).pick_folder())), } } @@ -217,34 +190,22 @@ fn main() -> eframe::Result { } // First, so every start-up record (and the engine's panic hook, installed with the first // Engine) is captured; see `logging`. - let logger = logging::install(); - let args: Vec = std::env::args().skip(1).collect(); - if args.iter().any(|a| a == "--version" || a == "-V") { - println!("SoundCraft {}", env!("CARGO_PKG_VERSION")); - return Ok(()); - } - let demo = args.iter().any(|a| a == "--demo" || a == "--sample"); - let no_audio = args.iter().any(|a| a == "--no-audio"); - let control_port: Option = args - .iter() - .position(|a| a == "--control") - .and_then(|i| args.get(i + 1)) - .and_then(|p| p.parse().ok()) - .or_else(|| std::env::var("SOUNDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())); - let files: Vec = args - .iter() - .enumerate() - .filter(|(i, a)| !(a.starts_with("--") || (i > &0 && args.get(i - 1).is_some_and(|p| p == "--control")))) - .map(|(_, a)| a.clone()) - .collect(); - log::info!("SoundCraft {} ({} {})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH); + let logger = logging::install(env::rust_log().as_deref()); + // Help, version and usage errors print and exit here, before a window or a log file exists. + let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit()); + // After the arguments and the logger: reading resolves the settings folder, which creates it, + // and a malformed switch is logged. + let env = Env::read(); + let (demo, no_audio, control_port) = (launch.demo, launch.no_audio, launch.control_port); + let files = launch.files; + log::info!("SoundCraft {}", soundcraft_automation::args::long_version()); // The log file lives in the settings directory; opened after the arguments, so `--version` // leaves no file behind. Records logged until now are written to it first. Runs without // preferences (agents' test runs) log to standard error only, so they don't rotate away the // user's own logs. if let Some(logger) = logger { - match config_dir() { - _ if !prefs_enabled() => logger.no_file(), + match env.config_dir.as_deref() { + _ if !env.prefs_enabled() => logger.no_file(), Some(dir) => match logger.attach_dir(&dir.join(logging::LOG_DIR)) { Ok(path) => log::info!("log file {}", path.display()), Err(e) => log::warn!("no log file: {e}"), @@ -257,7 +218,7 @@ fn main() -> eframe::Result { } let engine = if demo { soundcraft_engine::demo::demo_engine() } else { Engine::default() }; - let prefs = load_prefs().unwrap_or_default(); + let prefs = load_prefs(&env).unwrap_or_default(); let mut options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_title("SoundCraft") @@ -278,7 +239,7 @@ fn main() -> eframe::Result { // winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file // manager showed a "no" cursor. Run through XWayland when it's there; SOUNDCRAFT_WAYLAND=1 // keeps the native Wayland backend. - if std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) && std::env::var_os("SOUNDCRAFT_WAYLAND").is_none() { + if env.use_xwayland(std::env::var_os("DISPLAY").as_ref()) { options.event_loop_builder = Some(Box::new(|b| { use winit::platform::x11::EventLoopBuilderExtX11; b.with_x11(); @@ -292,9 +253,10 @@ fn main() -> eframe::Result { if no_audio { None } else { Some(soundcraft_playback::Player::with_config(Arc::new(engine.session().clone()), &prefs.audio)) }; let mut app = SoundApp::new(engine, player, services()); app.set_startup_update_check(true); - app.autosave_dir = prefs_path().and_then(|p| p.parent().map(|d| d.join("Autosave"))); + app.set_system_fonts(env.system_fonts()); + app.autosave_dir = env.config_dir.as_ref().map(|d| d.join("Autosave")); app.leftovers = app.autosave_dir.as_deref().map(soundcraft_engine::autosave::leftovers).unwrap_or_default(); - app.preset_dir = prefs_path().and_then(|p| p.parent().map(|d| d.join("Presets"))); + app.preset_dir = env.config_dir.as_ref().map(|d| d.join("Presets")); app.extra.ui_scale = prefs.ui_scale; app.ui = prefs; if let Some(port) = control_port { @@ -302,7 +264,7 @@ fn main() -> eframe::Result { app = app.with_control(rx); } for f in &files { - open_path(&mut app, f); + dialogs::open_path(&mut app, f); } // If the system menu bar cannot be built, keep the egui menu bar rather than fail to start. #[cfg(target_os = "macos")] @@ -319,6 +281,7 @@ fn main() -> eframe::Result { Ok(Box::new(App( app, logger, + env, #[cfg(target_os = "macos")] menu, ))) diff --git a/apps/soundcraft/src/switch.rs b/apps/soundcraft/src/switch.rs new file mode 100644 index 00000000..91cacb23 --- /dev/null +++ b/apps/soundcraft/src/switch.rs @@ -0,0 +1,46 @@ +//! Boolean environment switches (`SOUNDCRAFT_WAYLAND`, `SOUNDCRAFT_NO_PREFS`, ...): one parser, so every +//! variable accepts the same spellings. + +/// `1/on/true/yes` or `0/off/false/no`, case- and space-insensitive. Blank or unset is `Default`; +/// anything else is `Default` and logged. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Switch { + On, + Off, + #[default] + Default, +} + +impl Switch { + /// Parse the value of the variable `name`; `name` only appears in the warning. + pub(crate) fn parse(name: &str, value: Option<&str>) -> Switch { + let Some(value) = value else { return Switch::Default }; + match value.trim().to_ascii_lowercase().as_str() { + "1" | "on" | "true" | "yes" => Switch::On, + "0" | "off" | "false" | "no" => Switch::Off, + "" => Switch::Default, + _ => { + log::warn!("{name}={value:?} is not 1/on/true/yes or 0/off/false/no; using the default"); + Switch::Default + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_every_spelling() { + for v in ["1", "on", "true", "yes", "ON", "True", " Yes ", "\t1\n"] { + assert_eq!(Switch::parse("X", Some(v)), Switch::On, "{v:?}"); + } + for v in ["0", "off", "false", "no", "OFF", "False", " No ", " 0 "] { + assert_eq!(Switch::parse("X", Some(v)), Switch::Off, "{v:?}"); + } + for v in [None, Some(""), Some(" "), Some("maybe"), Some("2"), Some("onn")] { + assert_eq!(Switch::parse("X", v), Switch::Default, "{v:?}"); + } + } +} diff --git a/apps/soundcraft/tests/launch_flags.rs b/apps/soundcraft/tests/launch_flags.rs new file mode 100644 index 00000000..f0400eb3 --- /dev/null +++ b/apps/soundcraft/tests/launch_flags.rs @@ -0,0 +1,55 @@ +//! The desktop binary's command line, run as a process: the variable fallback of `--control`. + +use std::process::{Command, Output}; + +fn soundcraft(args: &[&str], control_port: &str) -> Output { + Command::new(env!("CARGO_BIN_EXE_soundcraft")) + .args(args) + .env("SOUNDCRAFT_NO_PREFS", "1") + .env("SOUNDCRAFT_CONTROL_PORT", control_port) + .env_remove("RUST_LOG") + // Without a display the window cannot open, so a launch that passes parsing ends instead of + // staying up. + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .output() + .expect("run soundcraft") +} + +#[test] +fn a_bad_variable_is_a_usage_error_naming_it() { + let out = soundcraft(&["--no-audio"], "nope"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(2), "{stderr}"); + assert!(stderr.contains("invalid value 'nope' for 'SOUNDCRAFT_CONTROL_PORT'"), "{stderr}"); +} + +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn a_blank_variable_is_unset() { + let out = soundcraft(&["--no-audio"], " "); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_ne!(out.status.code(), Some(2), "{stderr}"); + assert!(!stderr.contains("SOUNDCRAFT_CONTROL_PORT"), "{stderr}"); +} + +/// `soundcraft-cli app` takes `host:port` from the same variable. +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn a_loopback_host_and_port_variable_is_accepted() { + let out = soundcraft(&["--no-audio"], "127.0.0.1:0"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_ne!(out.status.code(), Some(2), "{stderr}"); + assert!(!stderr.contains("SOUNDCRAFT_CONTROL_PORT"), "{stderr}"); +} + +/// The variable may point `soundcraft-cli app` at another machine: the app opens, with a warning +/// and no control server. +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn another_host_in_the_variable_is_ignored() { + let out = soundcraft(&["--no-audio"], "10.0.0.5:7979"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_ne!(out.status.code(), Some(2), "{stderr}"); + assert!(stderr.contains("SOUNDCRAFT_CONTROL_PORT=10.0.0.5:7979 names another host, so no control server starts"), "{stderr}"); +} diff --git a/clippy.toml b/clippy.toml index 4b6c79f5..2a016f24 100644 --- a/clippy.toml +++ b/clippy.toml @@ -2,3 +2,8 @@ allow-unwrap-in-tests = true allow-expect-in-tests = true allow-panic-in-tests = true allow-indexing-slicing-in-tests = true + +disallowed-types = [ + { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, +] +cognitive-complexity-threshold = 30 diff --git a/crates/au-host/Cargo.toml b/crates/au-host/Cargo.toml index af793163..122c4919 100644 --- a/crates/au-host/Cargo.toml +++ b/crates/au-host/Cargo.toml @@ -20,7 +20,9 @@ log.workspace = true unsafe_code = "deny" [lints.clippy] +cognitive_complexity = "deny" +wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" -too_many_arguments = "allow" +too_many_arguments = "deny" type_complexity = "allow" diff --git a/crates/audio-io/src/lib.rs b/crates/audio-io/src/lib.rs index f47f244a..bdb9d352 100644 --- a/crates/audio-io/src/lib.rs +++ b/crates/audio-io/src/lib.rs @@ -61,9 +61,110 @@ pub enum FileFormat { Aac, Alac, Caf, + /// Any other container `symphonia` reads: Matroska and WebM by name. Other, } +impl FileFormat { + /// The formats [`decode`] reads, found by extension. Contents decide when they disagree. + pub const READ: &'static [FileFormat] = + &[FileFormat::Wav, FileFormat::Aiff, FileFormat::Flac, FileFormat::Mp3, FileFormat::Ogg, FileFormat::Aac, FileFormat::Caf, FileFormat::Other]; + /// The formats [`encode`] writes. + pub const WRITE: &'static [FileFormat] = &[FileFormat::Wav, FileFormat::Aiff, FileFormat::Flac]; + + /// The extensions that name this format, lower case and without the dot; the first is the one + /// a new file gets. ALAC shares AAC's MP4 container, so a `.m4a` name reads as AAC until the + /// contents say otherwise. + pub fn extensions(self) -> &'static [&'static str] { + match self { + FileFormat::Wav => &["wav", "wave", "bwf", "rf64"], + FileFormat::Aiff => &["aif", "aiff", "aifc"], + FileFormat::Flac => &["flac"], + FileFormat::Mp3 => &["mp3", "mp2", "mp1"], + FileFormat::Ogg => &["ogg", "oga"], + FileFormat::Aac => &["m4a", "m4b", "aac", "mp4", "adts"], + FileFormat::Alac => &["m4a"], + FileFormat::Caf => &["caf"], + FileFormat::Other => &["mkv", "webm"], + } + } + + /// The name people know the format by, as menus show it. + pub fn name(self) -> &'static str { + match self { + FileFormat::Wav => "WAV", + FileFormat::Aiff => "AIFF", + FileFormat::Flac => "FLAC", + FileFormat::Mp3 => "MP3", + FileFormat::Ogg => "Ogg Vorbis", + FileFormat::Aac => "AAC", + FileFormat::Alac => "ALAC", + FileFormat::Caf => "CAF", + FileFormat::Other => "Other", + } + } + + /// The media type a file of this format is served or downloaded as. + pub fn mime_type(self) -> &'static str { + match self { + FileFormat::Wav => "audio/wav", + FileFormat::Aiff => "audio/aiff", + FileFormat::Flac => "audio/flac", + FileFormat::Mp3 => "audio/mpeg", + FileFormat::Ogg => "audio/ogg", + FileFormat::Aac | FileFormat::Alac => "audio/mp4", + FileFormat::Caf => "audio/x-caf", + FileFormat::Other => "application/octet-stream", + } + } + + /// The extension a new file of this format gets. + pub fn default_extension(self) -> &'static str { + self.extensions().first().copied().unwrap_or("bin") + } + + /// The readable format an extension or format name names (`wav`, `.AIFF`; ASCII + /// case-insensitive), or `None` when nothing reads it. + pub fn from_extension(ext: &str) -> Option { + let ext = ext.trim_start_matches('.'); + Self::READ.iter().copied().find(|f| f.extensions().iter().any(|x| x.eq_ignore_ascii_case(ext))) + } + + /// The readable format `path`'s extension names, or `None` without a known extension. + pub fn from_path(path: impl AsRef) -> Option { + path.as_ref().extension().and_then(std::ffi::OsStr::to_str).and_then(Self::from_extension) + } + + /// The extensions [`encode`] writes this format under: the names whose readers expect what it + /// writes. RF64 and AIFF-C names are left out because `encode` writes plain RIFF and AIFF + /// headers for them. + pub fn write_extensions(self) -> &'static [&'static str] { + match self { + FileFormat::Wav => &["wav", "wave", "bwf"], + FileFormat::Aiff => &["aif", "aiff"], + FileFormat::Flac => &["flac"], + _ => &[], + } + } + + /// The format [`encode`] writes for an extension or format name (ASCII case-insensitive), or + /// `None` when it writes none. + pub fn from_write_extension(ext: &str) -> Option { + let ext = ext.trim_start_matches('.'); + Self::WRITE.iter().copied().find(|f| f.write_extensions().iter().any(|x| x.eq_ignore_ascii_case(ext))) + } + + /// Every extension of [`FileFormat::READ`], in order: what file pickers and browsers filter by. + pub fn readable_extensions() -> Vec<&'static str> { + Self::READ.iter().flat_map(|f| f.extensions().iter().copied()).collect() + } + + /// Every extension of [`FileFormat::WRITE`], in order: what save dialogs, help and errors list. + pub fn writable_extensions() -> Vec<&'static str> { + Self::WRITE.iter().flat_map(|f| f.write_extensions().iter().copied()).collect() + } +} + /// Stored sample representation. #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum SampleFormat { @@ -192,22 +293,9 @@ fn detect_by_magic(b: &[u8], depth: u32) -> Option { None } -fn detect_by_ext(ext: &str) -> FileFormat { - match ext.trim_start_matches('.').to_ascii_lowercase().as_str() { - "wav" | "wave" | "bwf" | "rf64" => FileFormat::Wav, - "aif" | "aiff" | "aifc" => FileFormat::Aiff, - "flac" => FileFormat::Flac, - "mp3" | "mp2" | "mp1" => FileFormat::Mp3, - "ogg" | "oga" => FileFormat::Ogg, - "aac" | "m4a" | "m4b" | "mp4" | "adts" => FileFormat::Aac, - "caf" => FileFormat::Caf, - _ => FileFormat::Other, - } -} - /// Identify a file by its magic bytes, falling back to the extension hint (`"wav"`, `".flac"`). pub fn detect_format(bytes: &[u8], ext_hint: Option<&str>) -> FileFormat { - detect_by_magic(bytes, 0).unwrap_or_else(|| ext_hint.map(detect_by_ext).unwrap_or(FileFormat::Other)) + detect_by_magic(bytes, 0).unwrap_or_else(|| ext_hint.and_then(FileFormat::from_extension).unwrap_or(FileFormat::Other)) } /// Read a file's format, sample rate, channel count, length and BWF metadata. @@ -270,19 +358,6 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { } } -/// Formats [`encode`] can write, as the extensions that name them. -pub const ENCODE_EXTENSIONS: &str = "wav, aif, aiff, flac"; - -/// The format [`encode`] writes for a file extension or format name (`wav`, `aiff`, `flac`, case-insensitive), or `None` when it cannot write it. -pub fn encode_format_for(name: &str) -> Option { - match name.trim_start_matches('.').to_ascii_lowercase().as_str() { - "wav" | "wave" | "bwf" => Some(FileFormat::Wav), - "aif" | "aiff" => Some(FileFormat::Aiff), - "flac" => Some(FileFormat::Flac), - _ => None, - } -} - /// Encode a WAV file in the RF64 layout regardless of size (normally used only above 4 GiB). pub fn encode_wav_rf64(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { wav::encode(buf, opts.bit_depth, opts.dither, opts.bwf.as_ref(), true, None) diff --git a/crates/audio-io/src/pcm.rs b/crates/audio-io/src/pcm.rs index eaa9ca73..6bd4358d 100644 --- a/crates/audio-io/src/pcm.rs +++ b/crates/audio-io/src/pcm.rs @@ -159,10 +159,17 @@ impl Quantizer { v += self.uniform() - self.uniform(); } let max = scale - 1.0; - v.round().clamp(-scale, max) as i32 + round_half_away(v.clamp(-scale, max)) as i32 } } +#[inline] +fn round_half_away(v: f64) -> f64 { + let t = v as i64; + let f = v - t as f64; + (t + i64::from(f >= 0.5) - i64::from(f <= -0.5)) as f64 +} + /// Bits per sample at `depth`, and whether they are float. pub(crate) fn sample_format(depth: BitDepth) -> (u16, bool) { match depth { @@ -235,3 +242,38 @@ pub(crate) fn validate_layout(channels: usize, sample_rate: u32) -> Result<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_half_away_matches_f64_round_on_the_quantizer_range() { + let edges = [ + 0.0, + -0.0, + 0.5, + -0.5, + 1.5, + -1.5, + 2.5, + 0.499_999_999_999_999_94, + -0.499_999_999_999_999_94, + 8_388_607.5, + -8_388_608.0, + 2_147_483_647.0, + -2_147_483_648.0, + ]; + let mut x = 0x2545_f491_4f6c_dd1du64; + let spread = (0..10_000).map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 11) as f64 / (1u64 << 53) as f64 * 4_294_967_295.0 - 2_147_483_648.0 + }); + for v in edges.into_iter().chain(spread) { + assert!(round_half_away(v) == v.round(), "{v}"); + assert_eq!(round_half_away(v) as i32, v.round() as i32, "{v}"); + } + } +} diff --git a/crates/audio-io/tests/fixtures/README.md b/crates/audio-io/tests/fixtures/README.md new file mode 100644 index 00000000..3cc0985f --- /dev/null +++ b/crates/audio-io/tests/fixtures/README.md @@ -0,0 +1,17 @@ +Tiny fixtures for `tests/it/decode_read_list.rs`: one per container or codec the READ list names +that the crate cannot write itself. Made with ffmpeg 8.0 from a 0.1 s mono 440 Hz sine +(`F="-y -f lavfi -i sine=frequency=440:duration=0.1 -ac 1"`): + + ffmpeg $F -ar 8000 -c:a libmp3lame -b:a 16k tone.mp3 + ffmpeg $F -ar 24000 -c:a mp2 -b:a 32k tone.mp2 + ffmpeg $F -ar 8000 -c:a libvorbis -q:a -1 tone.ogg + ffmpeg $F -ar 8000 -c:a aac -b:a 16k tone.m4a + ffmpeg $F -ar 8000 -c:a aac -b:a 16k -f adts tone.aac + ffmpeg $F -ar 8000 -c:a pcm_s16le tone.caf + ffmpeg $F -ar 8000 -c:a pcm_s16le tone.mkv + ffmpeg $F -ar 8000 -c:a libvorbis -q:a -1 tone.webm + ffmpeg $F -ar 8000 -c:a pcm_s16le -f aiff tone.aifc # AIFF-C "sowt" + +`silence.mp1` has no ffmpeg encoder. It is four hand-built MPEG-1 Layer I frames (mono, 32 kHz, +32 kbit/s, 48 bytes each: header `FF FF 18 C0`, all subband allocations zero), which decode to +silence. diff --git a/crates/audio-io/tests/fixtures/silence.mp1 b/crates/audio-io/tests/fixtures/silence.mp1 new file mode 100644 index 00000000..b2641229 Binary files /dev/null and b/crates/audio-io/tests/fixtures/silence.mp1 differ diff --git a/crates/audio-io/tests/fixtures/tone.aac b/crates/audio-io/tests/fixtures/tone.aac new file mode 100644 index 00000000..98cb40c0 Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.aac differ diff --git a/crates/audio-io/tests/fixtures/tone.aifc b/crates/audio-io/tests/fixtures/tone.aifc new file mode 100644 index 00000000..628dee16 Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.aifc differ diff --git a/crates/audio-io/tests/fixtures/tone.caf b/crates/audio-io/tests/fixtures/tone.caf new file mode 100644 index 00000000..2d3707ee Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.caf differ diff --git a/crates/audio-io/tests/fixtures/tone.m4a b/crates/audio-io/tests/fixtures/tone.m4a new file mode 100644 index 00000000..8966d86f Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.m4a differ diff --git a/crates/audio-io/tests/fixtures/tone.mkv b/crates/audio-io/tests/fixtures/tone.mkv new file mode 100644 index 00000000..eaeab78e Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.mkv differ diff --git a/crates/audio-io/tests/fixtures/tone.mp2 b/crates/audio-io/tests/fixtures/tone.mp2 new file mode 100644 index 00000000..a324d263 Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.mp2 differ diff --git a/crates/audio-io/tests/fixtures/tone.mp3 b/crates/audio-io/tests/fixtures/tone.mp3 new file mode 100644 index 00000000..c6429ac0 Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.mp3 differ diff --git a/crates/audio-io/tests/fixtures/tone.ogg b/crates/audio-io/tests/fixtures/tone.ogg new file mode 100644 index 00000000..5ebd4a7d Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.ogg differ diff --git a/crates/audio-io/tests/fixtures/tone.webm b/crates/audio-io/tests/fixtures/tone.webm new file mode 100644 index 00000000..5dbbcfee Binary files /dev/null and b/crates/audio-io/tests/fixtures/tone.webm differ diff --git a/crates/audio-io/tests/it/decode_read_list.rs b/crates/audio-io/tests/it/decode_read_list.rs new file mode 100644 index 00000000..ae477ad9 --- /dev/null +++ b/crates/audio-io/tests/it/decode_read_list.rs @@ -0,0 +1,51 @@ +//! Every extension the format table reads decodes with the compiled-in `symphonia` features. + +use soundcraft_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileFormat, decode, encode, probe}; + +fn fixture(name: &str) -> Vec { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name); + std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +fn generated(format: FileFormat) -> Vec { + let tone: Vec = (0..800).map(|i| (i as f32 * 0.1).sin() * 0.5).collect(); + let buf = AudioBuffer { sample_rate: 8000, channels: vec![tone] }; + encode(&buf, &EncodeOptions { format, bit_depth: BitDepth::Int16, dither: false, bwf: None }).unwrap() +} + +fn bytes_for(ext: &str) -> Vec { + match ext { + "wav" | "wave" | "bwf" => generated(FileFormat::Wav), + "rf64" => { + let tone = AudioBuffer { sample_rate: 8000, channels: vec![vec![0.25; 800]] }; + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Int16, dither: false, bwf: None }; + soundcraft_audio_io::encode_wav_rf64(&tone, &opts).unwrap() + } + "aif" | "aiff" => generated(FileFormat::Aiff), + "aifc" => fixture("tone.aifc"), + "flac" => generated(FileFormat::Flac), + "mp3" => fixture("tone.mp3"), + "mp2" => fixture("tone.mp2"), + "mp1" => fixture("silence.mp1"), + "ogg" | "oga" => fixture("tone.ogg"), + "m4a" | "m4b" | "mp4" => fixture("tone.m4a"), + "aac" | "adts" => fixture("tone.aac"), + "caf" => fixture("tone.caf"), + "mkv" => fixture("tone.mkv"), + "webm" => fixture("tone.webm"), + other => panic!("no fixture for the READ extension {other:?}: add one"), + } +} + +#[test] +fn every_read_extension_probes_and_decodes() { + for &format in FileFormat::READ { + for ext in format.extensions() { + let bytes = bytes_for(ext); + let info = probe(&bytes, Some(ext)).unwrap_or_else(|e| panic!("probe .{ext}: {e}")); + let (_, buf) = decode(&bytes, Some(ext)).unwrap_or_else(|e| panic!("decode .{ext}: {e}")); + assert!(info.channels >= 1, ".{ext}"); + assert!(buf.frames() > 0, ".{ext}: no frames"); + } + } +} diff --git a/crates/audio-io/tests/it/encode_format.rs b/crates/audio-io/tests/it/encode_format.rs deleted file mode 100644 index 766d85b8..00000000 --- a/crates/audio-io/tests/it/encode_format.rs +++ /dev/null @@ -1,13 +0,0 @@ -use soundcraft_audio_io::{FileFormat, encode_format_for}; - -#[test] -fn only_formats_the_encoder_writes_are_named() { - assert_eq!(encode_format_for("wav"), Some(FileFormat::Wav)); - assert_eq!(encode_format_for("WAV"), Some(FileFormat::Wav)); - assert_eq!(encode_format_for(".aif"), Some(FileFormat::Aiff)); - assert_eq!(encode_format_for("aiff"), Some(FileFormat::Aiff)); - assert_eq!(encode_format_for("flac"), Some(FileFormat::Flac)); - for other in ["mp3", "ogg", "m4a", "xyz", ""] { - assert_eq!(encode_format_for(other), None, "{other}"); - } -} diff --git a/crates/audio-io/tests/it/file_format.rs b/crates/audio-io/tests/it/file_format.rs new file mode 100644 index 00000000..5e063a52 --- /dev/null +++ b/crates/audio-io/tests/it/file_format.rs @@ -0,0 +1,36 @@ +use soundcraft_audio_io::FileFormat; + +#[test] +fn every_read_and_write_format_round_trips_through_its_extensions() { + for &format in FileFormat::READ { + assert!(!format.extensions().is_empty(), "{format:?}"); + for ext in format.extensions() { + assert_eq!(FileFormat::from_extension(ext), Some(format), "{ext}"); + assert_eq!(FileFormat::from_extension(&format!(".{}", ext.to_ascii_uppercase())), Some(format), "{ext}"); + assert_eq!(FileFormat::from_path(format!("dir.x/Take 1.{ext}")), Some(format), "{ext}"); + } + } + for &format in FileFormat::WRITE { + assert!(!format.write_extensions().is_empty(), "{format:?}"); + for ext in format.write_extensions() { + assert_eq!(FileFormat::from_write_extension(ext), Some(format), "{ext}"); + assert_eq!(FileFormat::from_write_extension(&ext.to_ascii_uppercase()), Some(format), "{ext}"); + assert_eq!(FileFormat::from_extension(ext), Some(format), "{ext}: what is written reads back"); + } + assert!(format.write_extensions().contains(&format.default_extension()), "{format:?}"); + } +} + +#[test] +fn only_names_whose_readers_expect_the_encoder_output_are_writable() { + assert_eq!(FileFormat::writable_extensions(), ["wav", "wave", "bwf", "aif", "aiff", "flac"]); + for read_only in ["rf64", "aifc", "mp3", "ogg", "m4a", "mkv"] { + assert!(FileFormat::from_extension(read_only).is_some(), "{read_only}"); + assert_eq!(FileFormat::from_write_extension(read_only), None, "{read_only}"); + } + for unknown in ["xyz", "", "mid"] { + assert_eq!(FileFormat::from_extension(unknown), None, "{unknown}"); + } + assert_eq!(FileFormat::from_path("no-extension"), None); + assert_eq!(FileFormat::Aiff.default_extension(), "aif"); +} diff --git a/crates/audio-io/tests/it/main.rs b/crates/audio-io/tests/it/main.rs index 84b90aa1..d71617af 100644 --- a/crates/audio-io/tests/it/main.rs +++ b/crates/audio-io/tests/it/main.rs @@ -1,6 +1,7 @@ //! Integration tests, built as one test binary: each file is a module. -mod encode_format; +mod decode_read_list; +mod file_format; mod float_headroom; mod malformed; mod roundtrip; diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 2e3f3f85..f83234a0 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -9,9 +9,15 @@ repository.workspace = true [dependencies] soundcraft-engine.workspace = true +soundcraft-audio-io.workspace = true soundcraft-time.workspace = true serde_json.workspace = true log.workspace = true +thiserror.workspace = true + +# The launch flags (`args`): the web build has none. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +clap.workspace = true [lints] workspace = true diff --git a/crates/automation/src/args.rs b/crates/automation/src/args.rs new file mode 100644 index 00000000..3822bff5 --- /dev/null +++ b/crates/automation/src/args.rs @@ -0,0 +1,199 @@ +//! The control and automation launch options, as clap types, so each flag and its environment +//! variable are declared once for `soundcraft-cli` and the desktop app. A flag wins over its +//! variable. +//! +//! Parse with [`blank_env_is_unset`] applied to the arguments, so an empty variable counts as unset, +//! and pass a parse error through [`name_env_vars`], so a bad value names the variable it came from. +//! [`conflict`] reports two arguments that can't go together, each named as it was given, for a +//! conflict that depends on the mode, which clap's `conflicts_with` can't express. + +use std::ffi::OsString; +use std::path::PathBuf; +use std::sync::OnceLock; + +use clap::error::{ContextKind, ContextValue, ErrorKind}; +use clap::parser::ValueSource; +use clap::{Arg, ArgAction, ArgMatches, Args, Command}; + +use crate::ControlTarget; + +/// The running app a client calls (`soundcraft-cli app`). +#[derive(Args)] +pub struct ControlClientArgs { + /// The app's control port or host:port + #[arg(long, value_name = "P", env = "SOUNDCRAFT_CONTROL_PORT", default_value = "7979", value_parser = control_target)] + pub port: ControlTarget, +} + +/// The control server the desktop app starts. The same variable as [`ControlClientArgs`], so one +/// export connects the two. +#[derive(Args)] +pub struct ControlServerArgs { + /// Start the localhost JSON-lines control server on this port (0 picks a free port and prints + /// it) + // allow_negative_numbers makes `--control -1` a bad port rather than an unexpected argument. + #[arg(long, value_name = "PORT", env = "SOUNDCRAFT_CONTROL_PORT", value_parser = control_target, allow_negative_numbers = true)] + pub control: Option, +} + +/// The folders automation may touch. Once any root is given, files are confined to the roots, and +/// a kind left out grants none of its access. No variable stands in for them: one left exported +/// must not change what an agent may read or write. +#[derive(Args)] +pub struct AutomationArgs { + /// A folder the agent's commands may read from; repeat for several + #[arg(long, value_name = "DIR", action = ArgAction::Append)] + pub automation_read_root: Vec, + /// A folder the agent's commands may write to; repeat for several + #[arg(long, value_name = "DIR", action = ArgAction::Append)] + pub automation_write_root: Vec, +} + +/// A [`ControlTarget`], for clap's `value_parser`: `soundcraft-cli app --port`, `mcp --connect`, +/// `soundcraft --control`, and SOUNDCRAFT_CONTROL_PORT, which may carry spaces. +pub fn control_target(s: &str) -> Result { + let (host, port) = host_and_port(s.trim())?; + Ok(ControlTarget { host: host.map(str::to_owned), port }) +} + +/// `PORT` or `HOST:PORT`, split. An IPv6 host goes in brackets (`[::1]:7979`), as a socket address +/// is written: in `::1:7979` the host and port can't be told apart. +fn host_and_port(s: &str) -> Result<(Option<&str>, u16), NotATarget> { + let (host, port) = match s.rsplit_once(':') { + Some(("", _)) => return Err(NotATarget), + Some((host, _)) if host.contains(':') && !(host.starts_with('[') && host.ends_with(']')) => return Err(NotATarget), + Some((host, port)) => (Some(host), port), + None => (None, s), + }; + Ok((host, port.parse().map_err(|_| NotATarget)?)) +} + +/// A [`control_target`] value that is neither a port nor `host:port`. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("expected a port, 0-65535, or host:port")] +pub struct NotATarget; + +/// `0.1.0 (linux x86_64)`: the workspace version and the platform the binary was built for. Every +/// crate takes its version from the workspace, so the value is the same in both binaries. A +/// `const` can't build it: `concat!` accepts only literals, not `std::env::consts`. +pub fn long_version() -> &'static str { + static LONG: OnceLock = OnceLock::new(); + LONG.get_or_init(|| format!("{} ({} {})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH)) +} + +/// For `Command::mut_args`: an empty or blank variable counts as unset, so `SOUNDCRAFT_CONTROL_PORT=` +/// turns a fallback off without `unset`. clap would pass the empty value to the parser. +pub fn blank_env_is_unset(arg: Arg) -> Arg { + let blank = arg.get_env().and_then(std::env::var_os).is_some_and(|v| v.to_str().is_some_and(|v| v.trim().is_empty())); + if blank { arg.env(None::<&str>) } else { arg } +} + +/// clap names the flag when a value from its variable is bad or conflicts with another, as if the +/// flag had been given: name the variable instead when the flag isn't among `args` (without the +/// binary name; a first one naming a subcommand selects whose arguments to look in). +pub fn name_env_vars(mut error: clap::Error, cmd: &Command, args: &[OsString]) -> clap::Error { + // `--flag value` or `--flag=value`. + let given = + |long: &str| args.iter().filter_map(|a| a.to_str()?.strip_prefix("--")?.strip_prefix(long)).any(|r| r.is_empty() || r.starts_with('=')); + let sub = args.first().and_then(|name| cmd.find_subcommand(name)).unwrap_or(cmd); + for kind in [ContextKind::InvalidArg, ContextKind::PriorArg] { + let Some(ContextValue::String(shown)) = error.get(kind) else { continue }; + let Some(arg) = sub.get_arguments().find(|a| a.to_string() == *shown) else { continue }; + let (Some(long), Some(var)) = (arg.get_long(), arg.get_env()) else { continue }; + if !given(long) { + error.insert(kind, ContextValue::String(var.to_string_lossy().into_owned())); + } + } + error +} + +/// clap's own conflict error when `m`, parsed by `cmd`, has both `a` and `b`, each named as it was +/// given: the flag, or its variable. +pub fn conflict(cmd: &mut Command, m: &ArgMatches, a: &str, b: &str) -> Result<(), clap::Error> { + if m.value_source(a).is_none() || m.value_source(b).is_none() { + return Ok(()); + } + let shown = |id: &str| { + let arg = cmd.get_arguments().find(|arg| arg.get_id() == id); + match (m.value_source(id), arg.and_then(Arg::get_env)) { + (Some(ValueSource::EnvVariable), Some(var)) => var.to_string_lossy().into_owned(), + _ => arg.map_or_else(|| id.to_owned(), |arg| arg.to_string()), + } + }; + let (shown_a, shown_b) = (shown(a), shown(b)); + let mut error = clap::Error::new(ErrorKind::ArgumentConflict).with_cmd(cmd); + error.insert(ContextKind::InvalidArg, ContextValue::String(shown_a)); + error.insert(ContextKind::PriorArg, ContextValue::String(shown_b)); + error.insert(ContextKind::Usage, ContextValue::StyledStr(cmd.render_usage())); + Err(error) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn control_target_is_a_port_or_host_and_port() { + let target = |host: Option<&str>, port| Ok(ControlTarget { host: host.map(str::to_owned), port }); + assert_eq!(control_target("7979"), target(None, 7979)); + assert_eq!(control_target(" 0 "), target(None, 0)); + assert_eq!(control_target("localhost:7979 "), target(Some("localhost"), 7979)); + assert_eq!(control_target("10.0.0.5:1"), target(Some("10.0.0.5"), 1)); + assert_eq!(control_target("[::1]:7979"), target(Some("[::1]"), 7979)); + for bad in ["", "x", "78787", ":7979", "host:", "host:x", "-1", "::1:7979", "[::1:7979"] { + assert_eq!(control_target(bad), Err(NotATarget), "{bad:?}"); + } + } + + /// The control server listens on 127.0.0.1 only: `[::1]` is another address. + #[test] + fn a_loopback_target_is_a_port_127_0_0_1_or_localhost() { + for loopback in ["50494", "127.0.0.1:7979", "localhost:7979"] { + assert!(control_target(loopback).is_ok_and(|t| t.is_loopback()), "{loopback:?}"); + } + for remote in ["10.0.0.5:7979", "example.com:7979", "[::1]:7979"] { + assert!(control_target(remote).is_ok_and(|t| !t.is_loopback()), "{remote:?}"); + } + } + + #[test] + fn a_control_target_displays_as_a_socket_address() { + for (given, shown) in [("7979", "127.0.0.1:7979"), ("localhost:1", "localhost:1"), ("[::1]:7979", "[::1]:7979")] { + assert_eq!(control_target(given).map(|t| t.to_string()), Ok(shown.to_owned()), "{given:?}"); + } + } + + /// A command with one port flag backed by a variable no test sets. + fn port_command() -> Command { + Command::new("t").arg(Arg::new("port").long("port").env("SOUNDCRAFT_TEST_UNSET_PORT").value_parser(control_target)) + } + + #[test] + fn name_env_vars_names_the_variable_only_when_the_flag_was_not_given() { + let mut cmd = port_command(); + let e = cmd.try_get_matches_from_mut(["t", "--port", "x"]).unwrap_err(); + let flag = name_env_vars(e, &cmd, &["--port".into(), "x".into()]); + assert_eq!(flag.get(ContextKind::InvalidArg), Some(&ContextValue::String("--port ".into()))); + let e = cmd.try_get_matches_from_mut(["t", "--port=x"]).unwrap_err(); + // As the error from the variable would read: the flag is not among the arguments. + let var = name_env_vars(e, &cmd, &[]); + assert_eq!(var.get(ContextKind::InvalidArg), Some(&ContextValue::String("SOUNDCRAFT_TEST_UNSET_PORT".into()))); + } + + #[test] + fn blank_env_is_unset_keeps_an_unset_variable() { + let arg = blank_env_is_unset(Arg::new("port").env("SOUNDCRAFT_TEST_UNSET_PORT")); + assert_eq!(arg.get_env(), Some(std::ffi::OsStr::new("SOUNDCRAFT_TEST_UNSET_PORT"))); + } + + #[test] + fn conflict_is_a_clap_usage_error_naming_both_flags() { + let mut cmd = port_command().arg(Arg::new("connect").long("connect")); + let m = cmd.try_get_matches_from_mut(["t", "--port", "1", "--connect", "2"]).unwrap(); + let e = conflict(&mut cmd, &m, "port", "connect").unwrap_err(); + assert_eq!((e.kind(), e.exit_code()), (ErrorKind::ArgumentConflict, 2)); + assert!(e.to_string().starts_with("error: the argument '--port ' cannot be used with '--connect '\n\nUsage: t"), "{e}"); + let m = cmd.try_get_matches_from_mut(["t", "--port", "1"]).unwrap(); + assert!(conflict(&mut cmd, &m, "port", "connect").is_ok()); + } +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 352200d3..6955db33 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -5,14 +5,19 @@ //! running app's `--control` port. //! - [`mcp::Server`]: a Model Context Protocol server over stdio (newline-delimited JSON-RPC 2.0) //! exposing SoundCraft as tools and resources. +//! - [`args`]: the control and automation launch flags and their environment variables, as clap +//! types. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(not(target_arch = "wasm32"))] +pub mod args; pub mod mcp; use serde_json::{Value, json}; use soundcraft_engine::Engine; use soundcraft_engine::file_access::{self, AutomationRoots}; -use std::io::{BufRead, BufReader, Write}; +use std::fmt; +use std::io::{self, BufRead, BufReader, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::sync::Arc; use std::time::Duration; @@ -79,64 +84,151 @@ impl Backend for Headless { } } +/// Where a running app's control channel listens: what `soundcraft-cli app --port`, +/// `soundcraft-cli mcp --connect`, `soundcraft --control` and SOUNDCRAFT_CONTROL_PORT give, parsed +/// once (`args::control_target`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ControlTarget { + /// As given: a name, an IPv4 address, or an IPv6 address in brackets (`[::1]`). `None`: + /// 127.0.0.1. + pub host: Option, + pub port: u16, +} + +impl ControlTarget { + /// Can the desktop app's control server, which listens on 127.0.0.1 only, serve this target? + /// True for no host, `127.0.0.1` and `localhost`; `[::1]` is another address. + pub fn is_loopback(&self) -> bool { + self.host.as_deref().is_none_or(|host| ["127.0.0.1", "localhost"].contains(&host)) + } +} + +/// `host:port`, as a socket address is written. +impl fmt::Display for ControlTarget { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}:{}", self.host.as_deref().unwrap_or("127.0.0.1"), self.port) + } +} + +/// Why a [`Remote`] request failed. +#[derive(Debug, thiserror::Error)] +pub enum RemoteError { + /// The host name didn't resolve. + #[error("{addr}: {source}")] + Resolve { addr: String, source: io::Error }, + #[error("cannot reach SoundCraft at {addr}: no addresses found")] + NoAddress { addr: String }, + #[error("cannot reach SoundCraft at {addr}: {source}")] + Unreachable { addr: String, source: io::Error }, + /// Reading or writing the connection failed. + #[error(transparent)] + Io(#[from] io::Error), + /// The app closed the connection before it replied. + #[error("connection closed")] + Closed, + /// The reply isn't JSON. + #[error(transparent)] + Reply(#[from] serde_json::Error), + /// The app's reply to a request it refused. + #[error("{0}")] + App(String), + /// The connection was lost after a request that changes state went out: it isn't repeated, + /// since the app may already have executed it. + #[error("{source}; `{method}` may or may not have been executed, check the session before repeating it")] + Unconfirmed { method: String, source: Box }, +} + +impl RemoteError { + /// The connection went away, so a fresh one may succeed. + fn is_lost_connection(&self) -> bool { + match self { + RemoteError::Closed => true, + RemoteError::Io(e) => matches!(e.kind(), io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionAborted), + _ => false, + } + } +} + +type Connection = (TcpStream, BufReader); + /// A TCP client for a running app's control channel. pub struct Remote { + /// The target as `host:port`, for connecting and for messages. addr: String, - conn: Option<(TcpStream, BufReader)>, + conn: Option, next_id: u64, } impl Remote { - /// `target` is a port (`7979`) or `host:port`. - pub fn new(target: &str) -> Self { - let addr = if target.contains(':') { target.to_string() } else { format!("127.0.0.1:{target}") }; - Remote { addr, conn: None, next_id: 1 } + /// A client for the app at `target`; it connects on the first request. + pub fn new(target: &ControlTarget) -> Self { + Remote { addr: target.to_string(), conn: None, next_id: 1 } } - fn connect(&mut self) -> Result<(), String> { - if self.conn.is_some() { - return Ok(()); + /// The open connection, connecting first when there is none. + fn connection(&mut self) -> Result<&mut Connection, RemoteError> { + match self.conn { + Some(ref mut conn) => Ok(conn), + None => Ok(self.conn.insert(connect(&self.addr)?)), } - let socks: Vec<_> = self.addr.to_socket_addrs().map_err(|e| format!("{}: {e}", self.addr))?.collect(); - let mut last = "no addresses found".to_string(); - let mut stream = None; - for sock in &socks { - match TcpStream::connect_timeout(sock, Duration::from_millis(800)) { - Ok(s) => { - stream = Some(s); - break; - } - Err(e) => last = e.to_string(), - } - } - let s = stream.ok_or_else(|| format!("cannot reach SoundCraft at {}: {last}", self.addr))?; - s.set_read_timeout(Some(Duration::from_secs(120))).map_err(|e| e.to_string())?; - let r = s.try_clone().map_err(|e| e.to_string())?; - self.conn = Some((s, BufReader::new(r))); - Ok(()) } /// One request/reply exchange. On failure the flag says whether the request line was already /// written to the socket (so the app may have executed it). - fn roundtrip(&mut self, method: &str, params: &Value) -> Result { - self.connect().map_err(|e| (e, false))?; + fn roundtrip(&mut self, method: &str, params: &Value) -> Result { let id = self.next_id; self.next_id += 1; let line = json!({"id": id, "method": method, "params": params}).to_string(); - let (w, r) = self.conn.as_mut().ok_or_else(|| ("not connected".to_string(), false))?; - writeln!(w, "{line}").map_err(|e| (e.to_string(), false))?; + let (w, r) = self.connection().map_err(|e| (e, false))?; + writeln!(w, "{line}").map_err(|e| (e.into(), false))?; let mut buf = String::new(); - r.read_line(&mut buf).map_err(|e| (e.to_string(), true))?; + r.read_line(&mut buf).map_err(|e| (e.into(), true))?; if buf.is_empty() { - return Err(("connection closed".into(), true)); + return Err((RemoteError::Closed, true)); } - let v: Value = serde_json::from_str(&buf).map_err(|e| (e.to_string(), true))?; + let v: Value = serde_json::from_str(&buf).map_err(|e| (e.into(), true))?; if v.get("ok").and_then(Value::as_bool).unwrap_or(false) { Ok(v.get("result").cloned().unwrap_or(Value::Null)) } else { - Err((v.get("error").and_then(Value::as_str).unwrap_or("error").to_string(), true)) + Err((RemoteError::App(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string()), true)) } } + + /// Calls `method`. A request lost with its connection is sent once more on a fresh one when + /// it only reads state. + pub fn request(&mut self, method: &str, params: Value) -> Result { + match self.roundtrip(method, ¶ms) { + Ok(v) => Ok(v), + Err((e, sent)) if e.is_lost_connection() => { + self.conn = None; + if sent && !is_read_only(method) { + return Err(RemoteError::Unconfirmed { method: method.to_owned(), source: Box::new(e) }); + } + self.roundtrip(method, ¶ms).map_err(|(e, _)| e) + } + Err((e, _)) => Err(e), + } + } +} + +/// Connects to `addr` (`host:port`), trying each address it resolves to. +fn connect(addr: &str) -> Result { + let socks = addr.to_socket_addrs().map_err(|source| RemoteError::Resolve { addr: addr.to_owned(), source })?; + let mut last = None; + for sock in socks { + match TcpStream::connect_timeout(&sock, Duration::from_millis(800)) { + Ok(s) => { + s.set_read_timeout(Some(Duration::from_secs(120)))?; + let r = s.try_clone()?; + return Ok((s, BufReader::new(r))); + } + Err(e) => last = Some(e), + } + } + Err(match last { + Some(source) => RemoteError::Unreachable { addr: addr.to_owned(), source }, + None => RemoteError::NoAddress { addr: addr.to_owned() }, + }) } /// Methods that only read state, so repeating them after a lost reply is harmless. @@ -146,19 +238,7 @@ fn is_read_only(method: &str) -> bool { impl Backend for Remote { fn call(&mut self, method: &str, params: Value) -> Result { - match self.roundtrip(method, ¶ms) { - Ok(v) => Ok(v), - Err((e, sent)) if e.contains("closed") || e.contains("Broken pipe") || e.contains("reset") => { - self.conn = None; - if sent && !is_read_only(method) { - // The app may already have executed the request; repeating it could apply it twice. - return Err(format!("{e}; `{method}` may or may not have been executed, check the session before repeating it")); - } - // Retry once on a fresh connection. - self.roundtrip(method, ¶ms).map_err(|(e, _)| e) - } - Err((e, _)) => Err(e), - } + self.request(method, params).map_err(|e| e.to_string()) } fn has_ui(&self) -> bool { true @@ -185,23 +265,25 @@ mod tests { #[test] fn remote_reports_unreachable() { - let mut r = Remote::new("127.0.0.1:1"); - assert!(r.call("session.inspect", json!({})).is_err()); + let mut r = Remote::new(&ControlTarget { host: Some("127.0.0.1".into()), port: 1 }); + let e = r.request("session.inspect", json!({})).unwrap_err(); + assert!(matches!(e, RemoteError::Unreachable { .. }), "{e:?}"); + assert!(e.to_string().starts_with("cannot reach SoundCraft at 127.0.0.1:1: "), "{e}"); } #[test] fn remote_resolves_hostnames() { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); - let mut r = Remote::new(&format!("localhost:{port}")); - assert_eq!(r.connect(), Ok(())); + let mut r = Remote::new(&ControlTarget { host: Some("localhost".into()), port }); + assert!(r.connection().is_ok()); } /// Fake app: accepts one connection per entry in `replies`, counts the request line it reads, /// then either drops the connection (`false`) or answers ok (`true`). - fn fake_app(replies: Vec) -> (String, Arc) { + fn fake_app(replies: Vec) -> (ControlTarget, Arc) { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap().to_string(); + let addr = ControlTarget { host: None, port: listener.local_addr().unwrap().port() }; let seen = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let counter = seen.clone(); std::thread::spawn(move || { diff --git a/crates/automation/src/mcp.rs b/crates/automation/src/mcp.rs index 886b25d7..e4ac191a 100644 --- a/crates/automation/src/mcp.rs +++ b/crates/automation/src/mcp.rs @@ -2,6 +2,7 @@ use crate::Backend; use serde_json::{Value, json}; +use soundcraft_audio_io::FileFormat; use std::io::{BufRead, Write}; pub const PROTOCOL_VERSION: &str = "2025-06-18"; @@ -70,7 +71,7 @@ pub fn tool_definitions() -> Vec { tool( "bounce_mix", "Render the mix to an audio file. Returns peak dBFS and integrated LUFS.", - json!({"path": {"type": "string"}, "format": {"type": "string", "enum": ["wav", "aiff", "flac"]}, "bit_depth": {"type": "string"}, "start": {}, "end": {}, "normalize": {"type": "boolean"}}), + json!({"path": {"type": "string"}, "format": {"type": "string", "enum": FileFormat::writable_extensions()}, "bit_depth": {"type": "string"}, "start": {}, "end": {}, "normalize": {"type": "boolean"}}), &["path"], ), tool("parity", "Feature-parity report against the incumbent's menu catalog.", json!({}), &[]), diff --git a/crates/clap-host/Cargo.toml b/crates/clap-host/Cargo.toml index 96c7de7c..27eaf561 100644 --- a/crates/clap-host/Cargo.toml +++ b/crates/clap-host/Cargo.toml @@ -32,7 +32,9 @@ libloading = "0.9" unsafe_code = "deny" [lints.clippy] +cognitive_complexity = "deny" +wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" -too_many_arguments = "allow" +too_many_arguments = "deny" type_complexity = "allow" diff --git a/crates/clap-host/src/ffi.rs b/crates/clap-host/src/ffi.rs index ab589957..8ae25c52 100644 --- a/crates/clap-host/src/ffi.rs +++ b/crates/clap-host/src/ffi.rs @@ -54,7 +54,7 @@ pub(crate) use events::Event; #[cfg(test)] use events::transport_event; pub(crate) use gui::GuiLink; -pub(crate) use instance::{Instance, NotePort, PortBuffers, PortInfo, RawParam}; +pub(crate) use instance::{Instance, NotePort, PortBuffers, PortInfo, ProcessInput, RawParam}; /// Most plugins one factory may report (hostile-input cap). const MAX_PLUGINS_PER_FACTORY: u32 = 1024; diff --git a/crates/clap-host/src/ffi/bundle.rs b/crates/clap-host/src/ffi/bundle.rs index e3cdeddc..503b6391 100644 --- a/crates/clap-host/src/ffi/bundle.rs +++ b/crates/clap-host/src/ffi/bundle.rs @@ -1,7 +1,12 @@ use super::gui::{GuiInner, GuiLink}; use super::host::{HostState, host_get_extension, host_request_callback, host_request_process, host_request_restart}; use super::instance::Instance; -use super::*; +use super::{ + Arc, CLAP_EXT_AUDIO_PORTS, CLAP_EXT_GUI, CLAP_EXT_LATENCY, CLAP_EXT_NOTE_PORTS, CLAP_EXT_PARAMS, CLAP_EXT_STATE, CLAP_PLUGIN_FACTORY_ID, + CLAP_VERSION, CString, ClapError, EVENT_CAP, HashMap, MAX_FEATURES, MAX_PLUGINS_PER_FACTORY, Mutex, OnceLock, Path, PathBuf, PoisonError, c_void, + clap_host, clap_plugin_audio_ports, clap_plugin_entry, clap_plugin_factory, clap_plugin_gui, clap_plugin_latency, clap_plugin_note_ports, + clap_plugin_params, clap_plugin_state, clap_version_is_compatible, read_cstr, scan, +}; // ---- loaded binaries ----------------------------------------------------------------------- diff --git a/crates/clap-host/src/ffi/events.rs b/crates/clap-host/src/ffi/events.rs index 1bc2f3f8..d3bb04fe 100644 --- a/crates/clap-host/src/ffi/events.rs +++ b/crates/clap-host/src/ffi/events.rs @@ -1,4 +1,10 @@ -use super::*; +use super::{ + CLAP_BEATTIME_FACTOR, CLAP_CORE_EVENT_SPACE_ID, CLAP_EVENT_MIDI, CLAP_EVENT_NOTE_OFF, CLAP_EVENT_NOTE_ON, CLAP_EVENT_PARAM_VALUE, + CLAP_EVENT_TRANSPORT, CLAP_SECTIME_FACTOR, CLAP_TRANSPORT_HAS_BEATS_TIMELINE, CLAP_TRANSPORT_HAS_SECONDS_TIMELINE, CLAP_TRANSPORT_HAS_TEMPO, + CLAP_TRANSPORT_HAS_TIME_SIGNATURE, CLAP_TRANSPORT_IS_PLAYING, CLAP_TRANSPORT_IS_RECORDING, MAX_STATE_BYTES, Transport, c_void, clap_event_header, + clap_event_midi, clap_event_note, clap_event_param_value, clap_event_transport, clap_input_events, clap_istream, clap_ostream, + clap_output_events, +}; // ---- events -------------------------------------------------------------------------------- diff --git a/crates/clap-host/src/ffi/gui.rs b/crates/clap-host/src/ffi/gui.rs index 5a911a95..92619742 100644 --- a/crates/clap-host/src/ffi/gui.rs +++ b/crates/clap-host/src/ffi/gui.rs @@ -1,6 +1,9 @@ use super::events::ostream_write; use super::host::HostState; -use super::*; +use super::{ + Arc, CStr, CString, Mutex, Ordering, PoisonError, c_void, clap_ostream, clap_plugin, clap_plugin_gui, clap_plugin_state, clap_window, + clap_window_handle, hostwin, +}; // ---- editor (clap.gui) --------------------------------------------------------------------- diff --git a/crates/clap-host/src/ffi/host.rs b/crates/clap-host/src/ffi/host.rs index 882c0377..408546dc 100644 --- a/crates/clap-host/src/ffi/host.rs +++ b/crates/clap-host/src/ffi/host.rs @@ -1,4 +1,8 @@ -use super::*; +use super::{ + AtomicBool, AtomicU64, CLAP_EXT_GUI, CLAP_EXT_LATENCY, CLAP_EXT_LOG, CLAP_EXT_PARAMS, CLAP_EXT_STATE, CLAP_LOG_ERROR, CLAP_LOG_FATAL, + CLAP_LOG_WARNING, CStr, EDIT_CAP, Mutex, Ordering, c_char, c_void, clap_host, clap_host_gui, clap_host_latency, clap_host_log, clap_host_params, + clap_host_state, clap_id, clap_log_severity, clap_param_clear_flags, clap_param_rescan_flags, read_cstr, +}; // ---- host side ----------------------------------------------------------------------------- diff --git a/crates/clap-host/src/ffi/instance.rs b/crates/clap-host/src/ffi/instance.rs index fec2bd44..3a537fb6 100644 --- a/crates/clap-host/src/ffi/instance.rs +++ b/crates/clap-host/src/ffi/instance.rs @@ -2,7 +2,12 @@ use super::bundle::Bundle; use super::events::{Event, RawEvent, ReadCursor, in_events_get, in_events_size, istream_read, out_events_try_push, transport_event}; use super::gui::GuiLink; use super::host::HostState; -use super::*; +use super::{ + Arc, CLAP_AUDIO_PORT_IS_MAIN, CLAP_PROCESS_ERROR, CStr, ClapError, MAX_PARAMS, MAX_PORT_CHANNELS, MAX_PORTS, Ordering, Transport, c_char, c_void, + clap_audio_buffer, clap_audio_port_info, clap_host, clap_input_events, clap_istream, clap_note_port_info, clap_output_events, clap_param_info, + clap_plugin, clap_plugin_audio_ports, clap_plugin_latency, clap_plugin_note_ports, clap_plugin_params, clap_plugin_state, clap_process, + read_name, +}; // ---- audio buffers ------------------------------------------------------------------------- @@ -312,16 +317,8 @@ impl Instance { /// Runs one `clap_process` call over `frames` frames. Events must be sorted by time; their /// times are made relative to `offset`. Returns the CLAP process status. - pub fn process( - &mut self, - frames: usize, - steady_time: i64, - inputs: &mut PortBuffers, - outputs: &mut PortBuffers, - events: &[Event], - offset: u32, - transport: Option<&Transport>, - ) -> Result { + pub fn process(&mut self, input: ProcessInput<'_>) -> Result { + let ProcessInput { frames, steady_time, inputs, outputs, events, offset, transport } = input; if !self.active { return Err(ClapError::Process("not active".into())); } @@ -386,6 +383,16 @@ impl Instance { } } +pub(crate) struct ProcessInput<'a> { + pub frames: usize, + pub steady_time: i64, + pub inputs: &'a mut PortBuffers, + pub outputs: &'a mut PortBuffers, + pub events: &'a [Event], + pub offset: u32, + pub transport: Option<&'a Transport>, +} + impl Drop for Instance { fn drop(&mut self) { // Editors first (CLAP: destroy the GUI before the plugin), and no handle may call in after. diff --git a/crates/clap-host/src/plugin.rs b/crates/clap-host/src/plugin.rs index 4b685cf8..8e048e2a 100644 --- a/crates/clap-host/src/plugin.rs +++ b/crates/clap-host/src/plugin.rs @@ -1,6 +1,6 @@ //! `ClapPlugin`: a loaded CLAP instance behind the safe `soundcraft_dsp::Plugin` trait. -use crate::ffi::{EVENT_CAP, Event, GuiLink, Instance, NotePort, PortBuffers}; +use crate::ffi::{EVENT_CAP, Event, GuiLink, Instance, NotePort, PortBuffers, ProcessInput}; use clap_sys::ext::note_ports::{CLAP_NOTE_DIALECT_CLAP, CLAP_NOTE_DIALECT_MIDI}; use soundcraft_dsp::{Plugin, PluginEditor, PluginInfo, Transport}; use std::sync::Arc; @@ -231,7 +231,15 @@ impl Plugin for ClapPlugin { let k = self.queue.iter().position(|e| e.time() >= end).unwrap_or(self.queue.len()); let offset = u32::try_from(start).unwrap_or(u32::MAX); let events = self.queue.get(..k).unwrap_or(&[]); - let r = self.inst.process(n, self.steady, &mut self.inputs, &mut self.outputs, events, offset, self.transport.as_ref()); + let r = self.inst.process(ProcessInput { + frames: n, + steady_time: self.steady, + inputs: &mut self.inputs, + outputs: &mut self.outputs, + events, + offset, + transport: self.transport.as_ref(), + }); self.queue.drain(..k); self.steady = self.steady.saturating_add(i64::try_from(n).unwrap_or(0)); match (r, self.out_main) { diff --git a/crates/dsp/src/meter.rs b/crates/dsp/src/meter.rs index 3727f83e..442985d5 100644 --- a/crates/dsp/src/meter.rs +++ b/crates/dsp/src/meter.rs @@ -150,8 +150,9 @@ pub struct LoudnessMeter { sub_filled: usize, hist_count: Vec, hist_energy: Vec, - tp_coefs: [[f32; TP_TAPS]; TP_PHASES], - tp_hist: Vec<[f32; TP_TAPS]>, + tp_coefs: [[f32; TP_PHASES]; TP_TAPS], + tp_hist: Vec<[f32; 2 * TP_TAPS]>, + tp_pos: Vec, true_peak: f32, max_momentary: f32, } @@ -197,7 +198,7 @@ impl LoudnessMeter { let weights = if channels == 6 { vec![1.0, 1.0, 1.0, 0.0, 1.41, 1.41] } else { vec![1.0; channels] }; let [c1, c2] = k_weighting(sr); // Interpolation filter: windowed sinc at the original Nyquist, split into 4 phases. - let mut tp_coefs = [[0.0f32; TP_TAPS]; TP_PHASES]; + let mut tp_coefs = [[0.0f32; TP_PHASES]; TP_TAPS]; let total = TP_TAPS * TP_PHASES; let center = (total as f64 - 1.0) / 2.0; for i in 0..total { @@ -205,14 +206,14 @@ impl LoudnessMeter { let sinc = if t.abs() < 1e-12 { 1.0 } else { (std::f64::consts::PI * t).sin() / (std::f64::consts::PI * t) }; let x = i as f64 / (total as f64 - 1.0); let w = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * x).cos() + 0.08 * (4.0 * std::f64::consts::PI * x).cos(); - if let Some(slot) = tp_coefs.get_mut(i % TP_PHASES).and_then(|ph| ph.get_mut(i / TP_PHASES)) { + if let Some(slot) = tp_coefs.get_mut(i / TP_PHASES).and_then(|tap| tap.get_mut(i % TP_PHASES)) { *slot = (sinc * w) as f32; } } - for ph in &mut tp_coefs { - let s: f32 = ph.iter().sum(); + for p in 0..TP_PHASES { + let s: f32 = tp_coefs.iter().filter_map(|tap| tap.get(p)).sum(); if s.abs() > 1e-6 { - ph.iter_mut().for_each(|c| *c /= s); + tp_coefs.iter_mut().filter_map(|tap| tap.get_mut(p)).for_each(|c| *c /= s); } } Self { @@ -228,7 +229,8 @@ impl LoudnessMeter { hist_count: vec![0; HIST_BINS], hist_energy: vec![0.0; HIST_BINS], tp_coefs, - tp_hist: vec![[0.0; TP_TAPS]; channels], + tp_hist: vec![[0.0; 2 * TP_TAPS]; channels], + tp_pos: vec![0; channels], true_peak: 0.0, max_momentary: MIN_DB, } @@ -257,7 +259,8 @@ impl LoudnessMeter { self.sub_filled = 0; self.hist_count.iter_mut().for_each(|v| *v = 0); self.hist_energy.iter_mut().for_each(|v| *v = 0.0); - self.tp_hist.iter_mut().for_each(|h| *h = [0.0; TP_TAPS]); + self.tp_hist.iter_mut().for_each(|h| *h = [0.0; 2 * TP_TAPS]); + self.tp_pos.iter_mut().for_each(|p| *p = 0); self.true_peak = 0.0; self.max_momentary = MIN_DB; } @@ -285,13 +288,24 @@ impl LoudnessMeter { } fn true_peak_sample(&mut self, c: usize, x: f32) { - let Some(h) = self.tp_hist.get_mut(c) else { return }; - h.copy_within(0..TP_TAPS - 1, 1); - h[0] = x; + let (Some(h), Some(pos)) = (self.tp_hist.get_mut(c), self.tp_pos.get_mut(c)) else { return }; + *pos = (*pos + TP_TAPS - 1) % TP_TAPS; + let p = *pos; + for slot in [p, p + TP_TAPS] { + if let Some(v) = h.get_mut(slot) { + *v = x; + } + } + let Some(w) = h.get(p..p + TP_TAPS).and_then(|w| <&[f32; TP_TAPS]>::try_from(w).ok()) else { return }; + let mut y = [-0.0f32; TP_PHASES]; + for (cs, s) in self.tp_coefs.iter().zip(w) { + for (acc, k) in y.iter_mut().zip(cs) { + *acc += k * s; + } + } let mut peak = x.abs(); - for ph in &self.tp_coefs { - let y: f32 = ph.iter().zip(h.iter()).map(|(a, b)| a * b).sum(); - peak = peak.max(y.abs()); + for v in y { + peak = peak.max(v.abs()); } if peak > self.true_peak { self.true_peak = peak; diff --git a/crates/dsp/src/offline.rs b/crates/dsp/src/offline.rs index 7ed5779b..bc915375 100644 --- a/crates/dsp/src/offline.rs +++ b/crates/dsp/src/offline.rs @@ -54,7 +54,24 @@ fn max_len(ch: &[Vec]) -> usize { /// The largest finite sample magnitude in any channel. pub fn peak(ch: &[Vec]) -> f32 { - ch.iter().flatten().filter(|v| v.is_finite()).fold(0.0f32, |m, v| m.max(v.abs())) + ch.iter().map(|c| channel_peak(c)).fold(0.0f32, f32::max) +} + +/// Largest finite absolute sample of one channel (0 for none). +pub fn channel_peak(x: &[f32]) -> f32 { + let mut lanes = [0.0f32; 8]; + let (chunks, rest) = x.as_chunks::<8>(); + for c in chunks { + for (m, v) in lanes.iter_mut().zip(c) { + let a = v.abs(); + *m = if a < f32::INFINITY && a > *m { a } else { *m }; + } + } + for (m, v) in lanes.iter_mut().zip(rest) { + let a = v.abs(); + *m = if a < f32::INFINITY && a > *m { a } else { *m }; + } + lanes.into_iter().fold(0.0f32, f32::max) } /// Peak-normalizes to `target_db` dBFS, either all channels together or each on its own. diff --git a/crates/dsp/src/plugins/dynamics.rs b/crates/dsp/src/plugins/dynamics.rs index 514dd334..9d998e4c 100644 --- a/crates/dsp/src/plugins/dynamics.rs +++ b/crates/dsp/src/plugins/dynamics.rs @@ -502,7 +502,10 @@ pub struct Maximizer { sr: f32, la: usize, delay: Vec, - req: Vec, + win: Vec<(u64, f32)>, + win_head: usize, + win_len: usize, + clock: u64, smooth: Vec, idx: usize, sum: f64, @@ -526,7 +529,10 @@ impl Maximizer { sr: 48_000.0, la: 1, delay: Vec::new(), - req: vec![1.0], + win: vec![(0, 1.0)], + win_head: 0, + win_len: 0, + clock: 0, smooth: vec![1.0], idx: 0, sum: 1.0, @@ -547,6 +553,40 @@ impl Maximizer { self.ceiling.snap(); self.rel = time_coef(self.p.v(2), self.sr); } + + fn window_min(&mut self, req: f32, la: usize) -> f32 { + let cap = self.win.len(); + let t = self.clock; + self.clock = t.saturating_add(1); + if cap == 0 { + return req.min(1.0); + } + while self.win_len > 0 && self.win.get(self.win_head).is_some_and(|&(at, _)| at.saturating_add(la as u64) <= t) { + self.win_head = wrap(self.win_head + 1, cap); + self.win_len -= 1; + } + if !req.is_nan() { + while self.win_len > 0 && self.win.get(wrap(self.win_head + self.win_len - 1, cap)).is_some_and(|&(_, v)| v >= req) { + self.win_len -= 1; + } + if self.win_len == cap { + self.win_head = wrap(self.win_head + 1, cap); + self.win_len -= 1; + } + if let Some(slot) = self.win.get_mut(wrap(self.win_head + self.win_len, cap)) { + *slot = (t, req); + self.win_len += 1; + } + } + match self.win.get(self.win_head) { + Some(&(_, v)) if self.win_len > 0 => v.min(1.0), + _ => 1.0, + } + } +} + +fn wrap(i: usize, n: usize) -> usize { + if i < n { i } else { i % n } } impl Plugin for Maximizer { @@ -562,7 +602,7 @@ impl Plugin for Maximizer { d }) .collect(); - self.req = vec![1.0; self.la]; + self.win = vec![(0, 1.0); self.la]; self.smooth = vec![1.0; self.la]; self.drive.set_time(20.0, self.sr); self.ceiling.set_time(20.0, self.sr); @@ -572,7 +612,9 @@ impl Plugin for Maximizer { fn reset(&mut self) { self.delay.iter_mut().for_each(DelayLine::clear); - self.req.iter_mut().for_each(|v| *v = 1.0); + self.win_head = 0; + self.win_len = 0; + self.clock = 0; self.smooth.iter_mut().for_each(|v| *v = 1.0); self.sum = self.la as f64; self.held = 1.0; @@ -598,16 +640,13 @@ impl Plugin for Maximizer { peak = peak.max(x.abs()); } let req = if peak > ceil { ceil / peak } else { 1.0 }; - if let Some(r) = self.req.get_mut(self.idx) { - *r = req; - } - let hold = self.req.iter().copied().fold(1.0f32, f32::min); + let hold = self.window_min(req, la); self.held = if hold < self.held { hold } else { hold + (self.held - hold) * self.rel }; if let Some(s) = self.smooth.get_mut(self.idx) { self.sum += f64::from(self.held) - f64::from(*s); *s = self.held; } - self.idx = (self.idx + 1) % la; + self.idx = wrap(self.idx + 1, la); if self.idx == 0 { // Re-sum once per window to cancel floating-point drift. self.sum = self.smooth.iter().map(|&v| f64::from(v)).sum(); diff --git a/crates/dsp/src/util.rs b/crates/dsp/src/util.rs index d3b33afb..3ec2f705 100644 --- a/crates/dsp/src/util.rs +++ b/crates/dsp/src/util.rs @@ -34,7 +34,8 @@ pub(crate) fn time_coef(ms: f32, sr: f32) -> f32 { /// Flushes denormals and non-finite values in feedback paths to zero. #[inline] pub(crate) fn flush(x: f32) -> f32 { - if x.is_finite() && x.abs() > 1.0e-25 { x } else { 0.0 } + let a = x.abs(); + if (a > 1.0e-25) & (a < f32::INFINITY) { x } else { 0.0 } } /// Number of frames a plugin may safely touch. diff --git a/crates/dsp/tests/it/offline_meters.rs b/crates/dsp/tests/it/offline_meters.rs index 1f9bd9be..bfd8c65e 100644 --- a/crates/dsp/tests/it/offline_meters.rs +++ b/crates/dsp/tests/it/offline_meters.rs @@ -298,3 +298,94 @@ fn spectrum_edge_cases() { let m = magnitude_db(&[f32::NAN; 64], 64); assert!(m.iter().all(|v| v.is_finite())); } + +const PIN_LUFS: u32 = 3_215_227_935; +const PIN_TRUE_PEAK: u32 = 3_162_870_746; +fn noise(len: usize, seed: u64, amp: f32) -> Vec { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + ((x >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp + }) + .collect() +} +fn bits_hash(chans: &[Vec]) -> u64 { + chans.iter().flatten().fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x0100_0000_01b3)) +} +fn run_blocks(p: &mut dyn soundcraft_dsp::Plugin, input: &[Vec], block: usize) -> Vec> { + let len = input[0].len(); + let mut out = vec![Vec::with_capacity(len); input.len()]; + let mut i = 0; + while i < len { + let n = block.min(len - i); + let mut io: Vec> = input.iter().map(|c| c[i..i + n].to_vec()).collect(); + p.process(&mut io, n); + for (o, c) in out.iter_mut().zip(io) { + o.extend(c); + } + i += n; + } + out +} +#[test] +fn loudness_and_true_peak_do_not_depend_on_block_size() { + let sr = 48_000.0; + let len = 96_000; + let l: Vec = sine(997.0, 0.5, sr, len).iter().zip(noise(len, 1, 0.3)).map(|(a, b)| a + b).collect(); + let r: Vec = sine(11_025.0, 0.7, sr, len).iter().zip(noise(len, 2, 0.2)).map(|(a, b)| a + b).collect(); + let io = [l, r]; + let run = |block: usize| { + let mut m = LoudnessMeter::new(sr, 2); + let mut i = 0; + while i < len { + let n = block.min(len - i); + let chunk: Vec> = io.iter().map(|c| c[i..i + n].to_vec()).collect(); + m.process(&chunk, n); + i += n; + } + (m.integrated_lufs().to_bits(), m.true_peak_db().to_bits(), m.momentary_lufs().to_bits()) + }; + let whole = run(len); + for block in [1, 7, 1024, 4801] { + assert_eq!(run(block), whole, "block {block}"); + } + let near = |got: u32, pin: u32| (f32::from_bits(got) - f32::from_bits(pin)).abs() < 1e-3; + assert!(near(whole.0, PIN_LUFS) && near(whole.1, PIN_TRUE_PEAK), "lufs {} dB, true peak {} dB", f32::from_bits(whole.0), f32::from_bits(whole.1)); +} +#[test] +fn peak_skips_non_finite_samples_at_any_length() { + for len in 0..40 { + let mut x = noise(len, len as u64 + 3, 0.9); + for (at, v) in [(1, f32::NAN), (len.saturating_sub(1), f32::INFINITY), (len / 2, f32::NEG_INFINITY)] { + if len > 3 { + x[at] = v; + } + } + let naive = x.iter().filter(|v| v.is_finite()).fold(0.0f32, |m, v| m.max(v.abs())); + assert_eq!(offline::channel_peak(&x).to_bits(), naive.to_bits(), "len {len}"); + let y = noise(len, 99, 0.5); + let both = y.iter().fold(naive, |m, v| m.max(v.abs())); + assert_eq!(offline::peak(&[x, y]).to_bits(), both.to_bits(), "len {len}"); + } +} +#[test] +fn maximizer_and_plate_reverb_output_does_not_depend_on_block_size() { + let len = 48_000; + let loud = [noise(len, 5, 1.6), noise(len, 6, 1.2)]; + let mut burst = [noise(len, 7, 0.5), noise(len, 8, 0.5)]; + for c in &mut burst { + c[4_800..].iter_mut().for_each(|v| *v = 0.0); + } + for (id, input) in [("maximizer", &loud), ("plate_reverb", &burst)] { + let mut hashes = Vec::new(); + for block in [64, 1000, 4096] { + let mut p = create(id).unwrap(); + p.prepare(48_000.0, 4096, 2); + hashes.push(bits_hash(&run_blocks(p.as_mut(), input, block))); + } + assert!(hashes.iter().all(|h| *h == hashes[0]), "{id}: {hashes:x?}"); + } +} diff --git a/crates/engine/examples/bounce_bench.rs b/crates/engine/examples/bounce_bench.rs new file mode 100644 index 00000000..8174f82d --- /dev/null +++ b/crates/engine/examples/bounce_bench.rs @@ -0,0 +1,33 @@ +use serde_json::{Value, json}; +use std::time::Instant; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let Some(out) = args.first() else { + eprintln!("usage: bounce_bench OUT.wav [reps] [JSON params]"); + std::process::exit(2); + }; + let reps = args.get(1).and_then(|r| r.parse().ok()).unwrap_or(5usize); + let mut params = args.get(2).and_then(|p| serde_json::from_str::(p).ok()).unwrap_or_else(|| json!({})); + if let Some(m) = params.as_object_mut() { + m.insert("path".into(), json!(out)); + } + let mut e = soundcraft_engine::demo::demo_engine(); + let mut times = Vec::new(); + let mut last = Value::Null; + for _ in 0..reps { + let t0 = Instant::now(); + match e.execute("file.bounce_mix", ¶ms) { + Ok(v) => last = v, + Err(err) => { + eprintln!("bounce failed: {err}"); + std::process::exit(1); + } + } + times.push(t0.elapsed().as_secs_f64()); + } + let total: f64 = times.iter().sum(); + let min = times.iter().copied().fold(f64::INFINITY, f64::min); + println!("{last}"); + println!("total {total:.4} s, min {min:.4} s over {reps} bounces"); +} diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index 7c6c7c54..d725efec 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -310,7 +310,7 @@ pub fn recover(e: &mut Engine, left: &Leftover) -> Result> { let mut r = Engine::default(); let session = left.dir.join(SESSION); let links = left.origin.as_deref().map_or(session.as_path(), Path::new); - let mut missing = open_session_linked(&mut r, &session.to_string_lossy(), links)?; + let mut missing = open_session_linked(&mut r, &session, links)?; let mut s = r.session().clone(); let unfinished = unfinished_takes(left, &s, &mut missing); if let Some(home) = left.origin.as_deref().and_then(|o| Path::new(o).parent()) { @@ -535,7 +535,7 @@ mod tests { w.flush().unwrap(); let file = std::fs::read_dir(&root).unwrap().flatten().map(|d| d.path().join(SESSION)).collect::>(); let mut r = Engine::default(); - open_session(&mut r, &file[0].to_string_lossy()).unwrap(); + open_session(&mut r, &file[0]).unwrap(); assert_eq!((file.len(), r.session().sources.len()), (1, 5)); w.close(false); w.flush().unwrap(); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 2d75b33c..f221014c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -92,11 +92,9 @@ pub fn specs() -> Vec { let dir = str_param(p, "dir").ok_or_else(|| bad("file.bounce_stems", "`dir` required"))?.to_string(); let r = range_param(e, "file.bounce_stems", p)?; let r = if r.is_empty() { soundcraft_time::Range::new(0, e.session().content_end().max(1)) } else { r }; - let format = match str_param(p, "format") { - Some("aiff") | Some("aif") => soundcraft_audio_io::FileFormat::Aiff, - Some("flac") => soundcraft_audio_io::FileFormat::Flac, - _ => soundcraft_audio_io::FileFormat::Wav, - }; + let format = str_param(p, "format") + .and_then(soundcraft_audio_io::FileFormat::from_write_extension) + .unwrap_or(soundcraft_audio_io::FileFormat::Wav); let bit_depth = match p.get("bit_depth").map(|b| b.to_string().trim_matches('"').to_string()).as_deref() { Some("16") => soundcraft_audio_io::BitDepth::Int16, Some("32") | Some("32f") => soundcraft_audio_io::BitDepth::Float32, @@ -313,8 +311,9 @@ pub fn bounce_job(e: &Engine, p: &Value) -> Result { let r = if r.is_empty() { soundcraft_time::Range::new(0, e.session().content_end().max(1)) } else { r }; let ext = std::path::Path::new(&path).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("wav").to_ascii_lowercase(); let format_name = str_param(p, "format").unwrap_or(ext.as_str()); - let format = soundcraft_audio_io::encode_format_for(format_name).ok_or_else(|| { - bad("file.bounce_mix", format!("cannot write `{format_name}` files (supported: {})", soundcraft_audio_io::ENCODE_EXTENSIONS)) + let format = soundcraft_audio_io::FileFormat::from_write_extension(format_name).ok_or_else(|| { + let supported = soundcraft_audio_io::FileFormat::writable_extensions().join(", "); + bad("file.bounce_mix", format!("cannot write `{format_name}` files (supported: {supported})")) })?; let bit_depth = match p.get("bit_depth").map(|b| b.to_string().trim_matches('"').to_string()).as_deref() { Some("16") => soundcraft_audio_io::BitDepth::Int16, diff --git a/crates/engine/src/cmd/sampler.rs b/crates/engine/src/cmd/sampler.rs index f4634e3d..03799b02 100644 --- a/crates/engine/src/cmd/sampler.rs +++ b/crates/engine/src/cmd/sampler.rs @@ -232,7 +232,8 @@ mod tests { let buf = AudioBuffer { sample_rate: 96_000, channels: vec![tone.clone(), tone] }; let mut e = Engine::default(); let t = instrument_track(&mut e); - for (ext, format) in [("flac", FileFormat::Flac), ("aif", FileFormat::Aiff)] { + for format in [FileFormat::Flac, FileFormat::Aiff] { + let ext = format.default_extension(); let path = d.join(format!("tone.{ext}")); let opts = EncodeOptions { format, bit_depth: BitDepth::Int24, dither: false, bwf: None }; std::fs::write(&path, soundcraft_audio_io::encode(&buf, &opts).unwrap()).unwrap(); diff --git a/crates/engine/src/cmd/video.rs b/crates/engine/src/cmd/video.rs index b3a6402a..14476653 100644 --- a/crates/engine/src/cmd/video.rs +++ b/crates/engine/src/cmd/video.rs @@ -165,7 +165,7 @@ mod tests { let sess = dir.join("s.scraft"); e.execute("session.save_as", &json!({"path": sess.to_string_lossy()})).unwrap(); let mut e2 = Engine::default(); - let missing = crate::io::open_session(&mut e2, &sess.to_string_lossy()).unwrap(); + let missing = crate::io::open_session(&mut e2, &sess).unwrap(); assert!(missing.is_empty(), "{missing:?}"); assert_eq!(e2.session().tracks[0].clips()[0], clip); assert_eq!(e2.session().videos, e.session().videos); @@ -173,12 +173,12 @@ mod tests { std::fs::create_dir_all(dir.join("Video Files")).unwrap(); std::fs::rename(&movie, dir.join("Video Files").join("picture.mp4")).unwrap(); let mut e3 = Engine::default(); - assert!(crate::io::open_session(&mut e3, &sess.to_string_lossy()).unwrap().is_empty()); + assert!(crate::io::open_session(&mut e3, &sess).unwrap().is_empty()); assert!(e3.session().videos[0].path.contains("Video Files")); // Movie gone: the session still opens and reports it. std::fs::remove_file(dir.join("Video Files").join("picture.mp4")).unwrap(); let mut e4 = Engine::default(); - let missing = crate::io::open_session(&mut e4, &sess.to_string_lossy()).unwrap(); + let missing = crate::io::open_session(&mut e4, &sess).unwrap(); assert!(missing.iter().any(|m| m.contains("picture.mp4")), "{missing:?}"); assert!(e4.messages.iter().any(|m| m.contains("missing media"))); assert_eq!(e4.session().tracks[0].clips().len(), 1); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 98c11a9c..73e92c66 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -48,16 +48,28 @@ struct Root { shown: PathBuf, } +/// A root [`AutomationRoots::new`] can't open: missing, unreadable, or not a folder. +#[derive(Debug, thiserror::Error)] +#[error("cannot open the automation {} root `{}`: {source}", kind(.access), .path.display())] +pub struct RootError { + access: Access, + path: PathBuf, + source: std::io::Error, +} + +fn kind(access: &Access) -> &'static str { + match access { + Access::Read => "read", + Access::Write => "write", + } +} + impl Root { /// The folder at `path`, which must exist. - fn open(path: &Path, access: Access) -> Result { - let kind = match access { - Access::Read => "read", - Access::Write => "write", - }; + fn open(path: &Path, access: Access) -> Result { let resolved = std::fs::canonicalize(path) .and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) }) - .map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?; + .map_err(|source| RootError { access, path: path.to_owned(), source })?; Ok(Self { shown: plain(resolved.clone()), resolved }) } } @@ -65,11 +77,11 @@ impl Root { impl AutomationRoots { /// The roots `read` and `write`, which must be existing folders (one given twice counts once); /// `None` when neither kind has any (nothing is confined then). - pub fn new(read: &[&Path], write: &[&Path]) -> Result>, String> { + pub fn new(read: &[&Path], write: &[&Path]) -> Result>, RootError> { if read.is_empty() && write.is_empty() { return Ok(None); } - let open = |paths: &[&Path], access: Access| -> Result, String> { + let open = |paths: &[&Path], access: Access| -> Result, RootError> { let mut roots: Vec = Vec::with_capacity(paths.len()); for path in paths { let root = Root::open(path, access)?; @@ -354,15 +366,15 @@ mod tests { #[test] fn a_missing_root_is_an_error_and_none_is_no_confinement() { let (base, _) = folders("missing"); - let e = AutomationRoots::new(&[&base.join("nope")], &[]).unwrap_err(); + let e = AutomationRoots::new(&[&base.join("nope")], &[]).unwrap_err().to_string(); assert!(e.starts_with("cannot open the automation read root"), "{e}"); - let e = AutomationRoots::new(&[], &[&base.join("in/a.scraft")]).unwrap_err(); + let e = AutomationRoots::new(&[], &[&base.join("in/a.scraft")]).unwrap_err().to_string(); assert!( e.starts_with("cannot open the automation write root") && e.ends_with(&std::io::Error::from(std::io::ErrorKind::NotADirectory).to_string()), "{e}" ); - assert!(AutomationRoots::new(&[Path::new("")], &[]).unwrap_err().starts_with("cannot open the automation read root ``")); + assert!(AutomationRoots::new(&[Path::new("")], &[]).unwrap_err().to_string().starts_with("cannot open the automation read root ``")); assert!(AutomationRoots::new(&[], &[]).unwrap().is_none()); // One root alone grants only its own access. let read_only = AutomationRoots::new(&[&base.join("in")], &[]).unwrap().unwrap(); @@ -440,7 +452,7 @@ mod tests { let twice = AutomationRoots::new(&[&base.join("in"), &base.join("in/sub/..")], &[]).unwrap().unwrap(); assert!(!twice.describe().contains(", ") && twice.describe().ends_with("; write none"), "{}", twice.describe()); // A missing folder among several is an error. - let e = AutomationRoots::new(&[&base.join("in"), &base.join("nope")], &[]).unwrap_err(); + let e = AutomationRoots::new(&[&base.join("in"), &base.join("nope")], &[]).unwrap_err().to_string(); assert!(e.starts_with("cannot open the automation read root"), "{e}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 76a33c7d..c457dcf2 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -424,11 +424,7 @@ pub fn bounce_stems_with(e: &Engine, dir: &str, r: Range, opts: &EncodeOptions, return Err(EngineError::BadParams("file.bounce_stems".into(), "bounces are limited to 4 hours".into())); } make_dir(dir)?; - let ext = match opts.format { - FileFormat::Aiff => "aif", - FileFormat::Flac => "flac", - _ => "wav", - }; + let ext = opts.format.default_extension(); let mut out = Vec::new(); let stems: Vec<(TrackId, String)> = s .tracks diff --git a/crates/engine/src/io/bundle.rs b/crates/engine/src/io/bundle.rs index 27bad519..cfe6e0af 100644 --- a/crates/engine/src/io/bundle.rs +++ b/crates/engine/src/io/bundle.rs @@ -1,6 +1,6 @@ use super::render::sanitize_name; use super::session::decode_source; -use super::*; +use super::{Arc, EncodeOptions, Engine, EngineError, FileFormat, OsStr, Path, Result, Session, SourceAudio, read_bundle, write_file}; // ─── Hosts without a filesystem (the browser) ───────────────────────────────────────────────── diff --git a/crates/engine/src/io/import.rs b/crates/engine/src/io/import.rs index f34b5f29..a2011def 100644 --- a/crates/engine/src/io/import.rs +++ b/crates/engine/src/io/import.rs @@ -1,5 +1,8 @@ use super::render::sanitize_name; -use super::*; +use super::{ + Arc, AudioBuffer, ChannelFormat, Clip, Engine, EngineError, FileFormat, OsStr, Path, PathBuf, Result, Samples, Session, Source, SourceAudio, + SourceId, TrackId, TrackKind, Value, file_found, file_key, json, read_file, stored_path, +}; /// Largest import we accept (samples per channel × channels), ~4 GiB of f32. pub(crate) const MAX_IMPORT_SAMPLES: usize = 1 << 30; diff --git a/crates/engine/src/io/midi.rs b/crates/engine/src/io/midi.rs index 405f1282..f97b5709 100644 --- a/crates/engine/src/io/midi.rs +++ b/crates/engine/src/io/midi.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{ChannelFormat, Clip, ClipContent, Engine, EngineError, Result, Samples, TrackId, TrackKind}; /// Most meter changes a MIDI file may bring into the tempo map; scores have a handful. pub(super) const MAX_MIDI_METERS: usize = 10_000; diff --git a/crates/engine/src/io/record.rs b/crates/engine/src/io/record.rs index ece38abf..32e20420 100644 --- a/crates/engine/src/io/record.rs +++ b/crates/engine/src/io/record.rs @@ -1,7 +1,7 @@ use super::import::add_source; #[cfg(test)] use super::session::{save_copy, save_session}; -use super::*; +use super::{Clip, Engine, EngineError, FileFormat, OsStr, PathBuf, Range, Samples, TrackId, read_file}; /// A recording's plan, made when it starts: each record-enabled track's take file, where the /// takes start on the timeline, the loop length they split into when loop recording, and the @@ -117,6 +117,7 @@ pub fn live_span(start: Samples, pass: Option, punch: Option, le #[cfg(test)] mod record_tests { + use super::super::{AudioBuffer, Path, plan_takes}; use super::*; use serde_json::json; diff --git a/crates/engine/src/io/render.rs b/crates/engine/src/io/render.rs index cb8b42c5..5d0f0f94 100644 --- a/crates/engine/src/io/render.rs +++ b/crates/engine/src/io/render.rs @@ -1,7 +1,7 @@ use super::import::add_source; #[cfg(test)] use super::midi::{MAX_MIDI_METERS, import_midi_bytes}; -use super::*; +use super::{AudioBuffer, Clip, ClipContent, Engine, EngineError, FileFormat, Range, Result, Samples, Session, TrackId, TrackKind}; /// Consolidate `r` on a track into one new clip backed by a rendered source. The clip covers the /// whole range, silence included; a range too long to render is refused rather than shortened. diff --git a/crates/engine/src/io/session.rs b/crates/engine/src/io/session.rs index f92b8624..8fcd47f8 100644 --- a/crates/engine/src/io/session.rs +++ b/crates/engine/src/io/session.rs @@ -2,7 +2,9 @@ use super::bundle::save_session_bundle; #[cfg(test)] use super::import::add_source; use super::import::{MAX_IMPORT_SAMPLES, at_rate, relink_videos}; -use super::*; +use super::{ + Arc, Engine, EngineError, OsStr, Path, PathBuf, Result, Session, SourceAudio, file_key, read_file, read_text, stored_path, write_session, +}; /// Save the session to `path` (a `.scraft` file). Audio that only exists in memory is written /// as 32-bit float WAV into `Audio Files/` next to it. Returns how many audio files were written. @@ -34,16 +36,17 @@ pub fn save_session_copy(e: &Engine, path: &str) -> Result { } /// Open a `.scraft` session and decode its audio files (missing files are reported, not fatal). -pub fn open_session(e: &mut Engine, path: &str) -> Result> { - open_session_linked(e, path, Path::new(path)) +pub fn open_session(e: &mut Engine, path: impl AsRef) -> Result> { + let path = path.as_ref(); + open_session_linked(e, path, path) } /// [`open_session`], following the media paths in it as if they were stored in the session file /// `links` (crash recovery: the session written beside the autosave, its paths from the original). -pub(crate) fn open_session_linked(e: &mut Engine, path: &str, links: &Path) -> Result> { +pub(crate) fn open_session_linked(e: &mut Engine, path: &Path, links: &Path) -> Result> { let text = read_text(path)?; let mut s = Session::from_json(&text).map_err(|err| EngineError::Io(err.to_string()))?; - let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default(); + let dir = path.parent().map(Path::to_path_buf).unwrap_or_default(); let mut missing = Vec::new(); let mut files = DecodedFiles::new(); for src in &s.sources { @@ -57,7 +60,9 @@ pub(crate) fn open_session_linked(e: &mut Engine, path: &str, links: &Path) -> R missing.extend(relink_videos(&mut s, links)); s.folder = Some(dir); e.replace_session(s); - e.path = Some(path.to_string()); + // Save writes back to `e.path`, which is text: a session at a name that isn't valid Unicode + // opens as if never saved, rather than saving to a name with replacement characters. + e.path = path.to_str().map(str::to_owned); for m in &missing { e.message(format!("missing media: {m}")); } @@ -89,7 +94,9 @@ pub(crate) fn decode_file(files: &mut DecodedFiles, p: &Path, rate: u32) -> std: #[cfg(test)] mod save_tests { + use super::super::{AudioBuffer, ChannelFormat, Clip, Engine, FileFormat, Range, TrackKind, back_up, copy_new}; use super::*; + use serde_json::json; #[test] fn autosave_copy_leaves_document_untouched_and_reuses_audio() { @@ -192,11 +199,11 @@ mod save_tests { assert_eq!(level(&reopen(&path("B/B.scraft"))), 0.5); std::fs::remove_file(dir.join("A/Audio Files/Audio 1_02.wav")).unwrap(); let mut missing = Engine::default(); - open_session(&mut missing, &path("A/A.scraft")).unwrap(); + open_session(&mut missing, path("A/A.scraft")).unwrap(); save_session(&mut missing, &path("B/Moved.scraft")).unwrap(); let mut r = Engine::default(); assert_eq!( - open_session(&mut r, &path("B/Moved.scraft")).unwrap(), + open_session(&mut r, path("B/Moved.scraft")).unwrap(), vec![dir.join("A").join("Audio Files").join("Audio 1_02.wav").display().to_string()] ); let _ = std::fs::remove_dir_all(&dir); @@ -222,7 +229,7 @@ mod save_tests { Engine::default().execute("session.save_as", &json!({"path": dir.join("New/New.scraft")})).unwrap(); std::fs::copy(&path, dir.join("Song")).unwrap(); let mut bare = Engine::default(); - open_session(&mut bare, &dir.join("Song").to_string_lossy()).unwrap(); + open_session(&mut bare, dir.join("Song")).unwrap(); bare.execute("session.save", &json!({})).unwrap(); second.execute("session.save_as", &json!({"path": path, "replace": true})).unwrap(); let r = reopen(&path); @@ -312,7 +319,9 @@ mod save_tests { #[cfg(test)] mod open_tests { + use super::super::{AudioBuffer, ChannelFormat, Clip, EncodeOptions, Engine, FileFormat, SourceId, TrackKind}; use super::*; + use serde_json::json; #[test] fn a_file_named_by_many_sources_is_decoded_once() { @@ -425,7 +434,9 @@ mod open_tests { #[cfg(all(test, unix))] mod pipe_tests { + use super::super::{AudioBuffer, FileFormat}; use super::*; + use serde_json::json; #[test] fn a_pipe_named_as_media_is_refused_not_waited_on() { diff --git a/crates/engine/src/io/strip.rs b/crates/engine/src/io/strip.rs index 6591b873..ec808241 100644 --- a/crates/engine/src/io/strip.rs +++ b/crates/engine/src/io/strip.rs @@ -1,6 +1,6 @@ #[cfg(test)] use super::import::add_source; -use super::*; +use super::{Arc, AtomicBool, Clip, EngineError, Ordering, Range, Result, Samples, Session, TrackId}; /// Limit a range used for rendering to the track's material (plus a second), so a huge /// selection never renders hours of silence. @@ -244,7 +244,9 @@ fn non_silent( #[cfg(test)] mod strip_tests { + use super::super::{AudioBuffer, Engine, FileFormat, Value}; use super::*; + use serde_json::json; /// A stereo track with `length`-long clips at `starts`, each playing a second of steady tone. fn tones(starts: &[Samples], length: Samples) -> (Engine, TrackId) { diff --git a/crates/engine/tests/it/bounce.rs b/crates/engine/tests/it/bounce.rs index 688be40d..36630319 100644 --- a/crates/engine/tests/it/bounce.rs +++ b/crates/engine/tests/it/bounce.rs @@ -137,3 +137,27 @@ fn dropping_an_unfinished_bounce_cancels_it_and_keeps_the_old_file() { assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); let _ = std::fs::remove_dir_all(&dir); } + +const PINNED: [[u32; 3]; 2] = [[0xc195_6706, 0xc093_0031, 0xc093_0031], [0xc162_e790, 0xbdcc_ccbf, 0xbdcc_ccbf]]; + +#[test] +fn demo_bounce_levels_are_pinned() { + let mut e = soundcraft_engine::demo::demo_engine(); + let dir = scratch("bounce-demo-pinned"); + let mut got = Vec::new(); + for (name, extra) in [("Mix.wav", serde_json::json!({})), ("Norm.wav", serde_json::json!({"normalize": true, "bit_depth": 16}))] { + let path = dir.join(name); + let mut p = serde_json::json!({"path": path, "start": 1_296_000, "end": 1_440_000}); + if let (Some(m), Some(x)) = (p.as_object_mut(), extra.as_object()) { + m.extend(x.clone()); + } + let r = e.execute("file.bounce_mix", &p).unwrap(); + assert!(std::fs::metadata(&path).unwrap().len() > 44, "{name} has audio"); + let level = |k: &str| r[k].as_f64().unwrap() as f32; + got.push([level("lufs"), level("true_peak_db"), level("peak_db")]); + } + let _ = std::fs::remove_dir_all(&dir); + for (g, pin) in got.iter().zip(PINNED) { + assert!(g.iter().zip(pin).all(|(v, p)| (v - f32::from_bits(p)).abs() < 1e-3), "{got:?}"); + } +} diff --git a/crates/mix/src/automation.rs b/crates/mix/src/automation.rs index 0c273bc7..12a17f9e 100644 --- a/crates/mix/src/automation.rs +++ b/crates/mix/src/automation.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{AutoParam, Samples, Session, TICKS_PER_QUARTER, Track, Transport, db_to_gain}; pub(crate) fn transport_at(s: &Session, pos: Samples, playing: bool, recording: bool) -> Transport { let sr = s.sample_rate; @@ -70,8 +70,20 @@ pub(crate) fn send_level(t: &Track, i: usize, base: f32, pos: Samples) -> f32 { base } -pub(crate) fn lerp_gain(db0: f32, db1: f32, i: usize, n: usize) -> f32 { - let g0 = db_to_gain(db0); - let g1 = db_to_gain(db1); - if n == 0 { g0 } else { g0 + (g1 - g0) * (i as f32 / n as f32) } +#[derive(Debug, Clone, Copy)] +pub(crate) struct GainRamp { + g0: f32, + g1: f32, + n: usize, +} + +impl GainRamp { + pub(crate) fn new(db0: f32, db1: f32, n: usize) -> Self { + GainRamp { g0: db_to_gain(db0), g1: db_to_gain(db1), n } + } + + #[inline] + pub(crate) fn at(&self, i: usize) -> f32 { + if self.n == 0 { self.g0 } else { self.g0 + (self.g1 - self.g0) * (i as f32 / self.n as f32) } + } } diff --git a/crates/mix/src/clips.rs b/crates/mix/src/clips.rs index 03449de8..807f64a7 100644 --- a/crates/mix/src/clips.rs +++ b/crates/mix/src/clips.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Bound, Clip, ClipContent, Plugin, Range, Samples, Session, db_to_gain}; /// Clip Effects: an EQ and a compressor per clip, configured from `edit.values` /// (`clip_fx..eq.`, `clip_fx..comp.`, `clip_fx..gain`). diff --git a/crates/mix/src/instances.rs b/crates/mix/src/instances.rs index 5050007e..8bb5dbf9 100644 --- a/crates/mix/src/instances.rs +++ b/crates/mix/src/instances.rs @@ -1,5 +1,5 @@ use super::strip::strip_channels; -use super::*; +use super::{Plugin, Session, TrackId, main_channels}; /// Slot index used for a track's instrument plugin in [`InstanceSpec`] and [`PreparedInstance`] /// (insert slots use their index). diff --git a/crates/mix/src/lib.rs b/crates/mix/src/lib.rs index d3f2eec3..3dbd9d0c 100644 --- a/crates/mix/src/lib.rs +++ b/crates/mix/src/lib.rs @@ -59,7 +59,6 @@ use soundcraft_model::{ use soundcraft_time::{Range, Samples, TICKS_PER_QUARTER}; use std::collections::HashMap; use std::ops::Bound; -use std::sync::Arc; mod automation; mod clips; @@ -72,7 +71,7 @@ mod routing; mod strip; mod threads; -use automation::{lerp_gain, pan_at, pan_segment, send_level, transport_at, volume_db_at}; +use automation::{GainRamp, pan_at, pan_segment, send_level, transport_at, volume_db_at}; pub use instances::{INSTRUMENT_SLOT, InstanceSpec, NewInstance, PluginFailures, PreparedInstance, create_instance, instance_specs, is_third_party}; pub use meter::StripMeter; use midi::sync_sample; @@ -82,7 +81,9 @@ pub use offline::{ pub use pan::itu_stereo_fold; use pan::{PanSpec, apply_matrix, apply_matrix_span, build_matrix}; use routing::{processing_order, structure_fingerprint}; -use strip::{BusBuf, LiveInput, SlotCtx, Strip, apply_params, contain_failure, note_insert_latency, process_strip, strip_channels, strip_format}; +use strip::{ + Block, BusBuf, LiveInput, SlotCtx, Strip, apply_params, contain_failure, note_insert_latency, process_strip, strip_channels, strip_format, +}; #[cfg(test)] use strip::{DelayLine, MAX_LATENCY}; use threads::run_strips; @@ -349,6 +350,44 @@ impl MixEngine { /// Render `frames` (≤ max_block) samples starting at `pos` into `out` (≥ 2 channels). pub fn render(&mut self, s: &Session, pos: Samples, frames: usize, out: &mut [Vec]) { let frames = frames.min(self.max_block); + self.begin_block(s, pos, frames); + let blk = Block { pos, frames, any_solo: s.tracks.iter().any(|t| t.mixer.solo && !t.inactive) }; + let order = std::mem::take(&mut self.order); + // Phase 1: independent strips (audio, instrument, MIDI) in parallel. + let mut work = std::mem::take(&mut self.work); + work.clear(); + for &i in &order { + let Some(t) = s.tracks.get(i).filter(|t| is_live(t) && !is_aux(t)) else { continue }; + if let Some(st) = self.strips.remove(&t.id) { + work.push((i, st)); + } + } + for (_, st) in work.iter_mut() { + if st.scratch.len() < self.max_block { + st.scratch.resize(self.max_block, 0.0); + } + } + let busses = std::mem::take(&mut self.busses); + let live_in = LiveInput { input: &self.input, monitor_only: self.monitor_only, recording: self.recording }; + run_strips(&mut work, |(i, st)| { + if let Some(t) = s.tracks.get(*i) { + process_strip(s, t, st, &busses, &live_in, blk); + } + }); + self.busses = busses; + // Delay compensation: align every strip to the slowest. Direct-to-main outputs also wait + // for the slowest aux return. Aux latency has to be read before those outputs are routed, + // or the first block (and a one-block bounce probe) still sees zero. + self.compensate_delay(s, &mut work, blk); + self.work = work; + self.render_auxes(s, &order, blk); + self.order = order; + self.render_masters(s, blk); + self.write_output(s, blk, out); + } + + /// Silence what a seek leaves ringing, sync to the session and clear the block's accumulators. + fn begin_block(&mut self, s: &Session, pos: Samples, frames: usize) { if pos != self.last_end { // Seek: silence held notes and ringing plugins. for st in self.strips.values_mut() { @@ -369,35 +408,11 @@ impl MixEngine { for c in &mut self.main { c.iter_mut().take(frames).for_each(|x| *x = 0.0); } - let any_solo = s.tracks.iter().any(|t| t.mixer.solo && !t.inactive); - let order = std::mem::take(&mut self.order); - let live = |t: &Track| !(t.kind == TrackKind::Master || t.inactive || t.kind == TrackKind::Vca); - let is_aux = |t: &Track| matches!(t.kind, TrackKind::Aux | TrackKind::Folder); - // Phase 1: independent strips (audio, instrument, MIDI) in parallel. - let mut work = std::mem::take(&mut self.work); - work.clear(); - for &i in &order { - let Some(t) = s.tracks.get(i).filter(|t| live(t) && !is_aux(t)) else { continue }; - if let Some(st) = self.strips.remove(&t.id) { - work.push((i, st)); - } - } - for (_, st) in work.iter_mut() { - if st.scratch.len() < self.max_block { - st.scratch.resize(self.max_block, 0.0); - } - } - let busses = std::mem::take(&mut self.busses); - let live_in = LiveInput { input: &self.input, monitor_only: self.monitor_only, recording: self.recording }; - run_strips(&mut work, |(i, st)| { - if let Some(t) = s.tracks.get(*i) { - process_strip(s, t, st, &busses, &live_in, pos, frames, any_solo); - } - }); - self.busses = busses; - // Delay compensation: align every strip to the slowest. Direct-to-main outputs also wait - // for the slowest aux return. Aux latency has to be read before those outputs are routed, - // or the first block (and a one-block bounce probe) still sees zero. + } + + /// Delay compensation for the independent strips (`work`), then route them back into the engine. + fn compensate_delay(&mut self, s: &Session, work: &mut Vec<(usize, Strip)>, blk: Block) { + let Block { pos, frames, .. } = blk; let pdc = s.edit.delay_compensation; if pdc { for t in s.tracks.iter().filter(|t| is_aux(t) && !t.inactive) { @@ -427,7 +442,7 @@ impl MixEngine { self.aux_latency = lmax_a; self.aux_fed.clear(); if pdc { - for t in s.tracks.iter().filter(|t| is_aux(t) && live(t)) { + for t in s.tracks.iter().filter(|t| is_aux(t) && is_live(t)) { if let Route::Bus(b) = &t.mixer.output && !self.aux_fed.contains(b) { @@ -461,16 +476,20 @@ impl MixEngine { self.strips.insert(t.id, st); } } - self.work = work; - let is_aux = |t: &Track| matches!(t.kind, TrackKind::Aux | TrackKind::Folder); - // Phase 2: auxes in dependency order (they read busses). - for t in order.iter().filter_map(|&i| s.tracks.get(i)).filter(|t| live(t)).filter(|t| is_aux(t)) { + } + + /// Phase 2: auxes in dependency order (they read busses). + fn render_auxes(&mut self, s: &Session, order: &[usize], blk: Block) { + let Block { pos, frames, .. } = blk; + let pdc = s.edit.delay_compensation; + let lmax_a = self.aux_latency; + for t in order.iter().filter_map(|&i| s.tracks.get(i)).filter(|t| is_live(t)).filter(|t| is_aux(t)) { let Some(mut st) = self.strips.remove(&t.id) else { continue }; if st.scratch.len() < self.max_block { st.scratch.resize(self.max_block, 0.0); } let live_in = LiveInput { input: &self.input, monitor_only: self.monitor_only, recording: self.recording }; - process_strip(s, t, &mut st, &self.busses, &live_in, pos, frames, any_solo); + process_strip(s, t, &mut st, &self.busses, &live_in, blk); let ch = st.buf.len(); st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch); st.align.process(&mut st.buf, frames); @@ -478,7 +497,11 @@ impl MixEngine { self.route_strip(t, &mut st, pos, frames); self.strips.insert(t.id, st); } - self.order = order; + } + + /// Master faders process the main mix. + fn render_masters(&mut self, s: &Session, blk: Block) { + let Block { pos, frames, .. } = blk; // Master faders process the main mix. let transport = transport_at(s, pos, !self.monitor_only, self.recording); for t in s.tracks.iter().filter(|t| t.kind == TrackKind::Master && !t.inactive) { @@ -506,10 +529,11 @@ impl MixEngine { let last = pos.saturating_add(frames.saturating_sub(1) as i64); let v0 = volume_db_at(t, pos); let v1 = volume_db_at(t, last); + let ramp = GainRamp::new(v0, v1, frames.saturating_sub(1)); for (ch, src) in strip.buf.iter().enumerate().take(self.main.len()) { if let Some(m) = self.main.get_mut(ch) { for i in 0..frames { - let g = lerp_gain(v0, v1, i, frames.saturating_sub(1)); + let g = ramp.at(i); if let (Some(d), Some(x)) = (m.get_mut(i), src.get(i)) { *d = x * g; } @@ -521,6 +545,11 @@ impl MixEngine { m.plugin_failures = strip.failures; } } + } + + /// Add the metronome and copy the main mix to `out`. + fn write_output(&mut self, s: &Session, blk: Block, out: &mut [Vec]) { + let Block { pos, frames, .. } = blk; // Metronome: summed after the master fader, so it reaches the speakers without passing // through any track, send or insert. Only the playback engine sets `metronome`. // Not while monitoring only (transport stopped): the position does not advance there, so the @@ -628,6 +657,14 @@ std::thread_local! { static AUDIO_THREAD: std::cell::Cell = const { std::cell::Cell::new(false) }; } +fn is_live(t: &Track) -> bool { + !(t.kind == TrackKind::Master || t.inactive || t.kind == TrackKind::Vca) +} + +fn is_aux(t: &Track) -> bool { + matches!(t.kind, TrackKind::Aux | TrackKind::Folder) +} + /// Metronome: a short synthesized blip on every beat of the tempo map, accented on beat 1 of /// each bar. Settings come from `setup.click_countoff` (`click.*` values). mod click; diff --git a/crates/mix/src/meter.rs b/crates/mix/src/meter.rs index a8b98e7e..221cee89 100644 --- a/crates/mix/src/meter.rs +++ b/crates/mix/src/meter.rs @@ -75,5 +75,5 @@ fn max_level(a: f32, b: f32) -> f32 { } fn peak(x: &[f32]) -> f32 { - x.iter().fold(0.0f32, |m, v| if v.is_finite() { m.max(v.abs()) } else { m }) + soundcraft_dsp::offline::channel_peak(x) } diff --git a/crates/mix/src/midi.rs b/crates/mix/src/midi.rs index 2e49790c..3b182956 100644 --- a/crates/mix/src/midi.rs +++ b/crates/mix/src/midi.rs @@ -1,6 +1,7 @@ use super::clips::Key; use super::strip::{PluginSlot, Strip}; -use super::*; +use super::{ClipContent, CtrlKind, Range, SampleSource, Samples, Session, SourceAudio, Track}; +use std::sync::Arc; /// The track's MIDI Track Offset (`midi.offset.` in the edit values), in samples. Looked up /// without formatting the key, since this runs on the audio thread every block. diff --git a/crates/mix/src/offline.rs b/crates/mix/src/offline.rs index ad70b918..d544b0fc 100644 --- a/crates/mix/src/offline.rs +++ b/crates/mix/src/offline.rs @@ -1,6 +1,6 @@ use super::clips::{ClipFx, clip_fx_params, render_clip}; use super::pan::itu_stereo_fold; -use super::*; +use super::{AutoParam, BusId, ChannelFormat, MixEngine, Range, Route, Samples, Session, TrackId, main_channels}; /// Ceiling on one in-memory offline render (samples summed over channels): 2^29 f32 = 2 GiB, about /// 93 minutes of stereo at 48 kHz. Longer requests are truncated rather than exhausting memory; diff --git a/crates/mix/src/pan.rs b/crates/mix/src/pan.rs index 0734866b..cb8047a7 100644 --- a/crates/mix/src/pan.rs +++ b/crates/mix/src/pan.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains}; /// Per-block routing gains: `m[src][dst]`. type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS]; @@ -48,6 +48,22 @@ fn surround_params(sp: &SurroundPan, dx: f32) -> SurroundParams { SurroundParams { x: (sp.x + dx).clamp(-1.0, 1.0), y: sp.y, z: sp.z, divergence: sp.divergence, center: sp.center / 100.0 } } +/// One source → destination routing: channel counts and formats, plus how the source is panned. +struct Link<'a> { + src_fmt: ChannelFormat, + ns: usize, + dst_fmt: ChannelFormat, + nd: usize, + pan: &'a PanSpec<'a>, + law: PanLaw, +} + +fn add_gain(m: &mut Matrix, s: usize, d: usize, g: f32) { + if let Some(x) = m.get_mut(s).and_then(|r| r.get_mut(d)) { + *x += g; + } +} + /// Routing gains from a source (`ns` channels of `src_fmt`) into a destination (`nd` channels of /// `dst_fmt`). See the crate docs for the rules. pub(crate) fn build_matrix(src_fmt: ChannelFormat, ns: usize, dst_fmt: ChannelFormat, nd: usize, pan: &PanSpec<'_>, law: PanLaw) -> Matrix { @@ -56,11 +72,6 @@ pub(crate) fn build_matrix(src_fmt: ChannelFormat, ns: usize, dst_fmt: ChannelFo if ns == 0 || nd == 0 { return m; } - let set = |m: &mut Matrix, s: usize, d: usize, g: f32| { - if let Some(x) = m.get_mut(s).and_then(|r| r.get_mut(d)) { - *x += g; - } - }; if nd == 1 { // Mono destination: the stereo routing summed at -6 dB. let st = build_matrix(src_fmt, ns, ChannelFormat::Stereo, 2, pan, law); @@ -69,131 +80,168 @@ pub(crate) fn build_matrix(src_fmt: ChannelFormat, ns: usize, dst_fmt: ChannelFo } return m; } - let src_sp = src_fmt.speakers(); + let link = Link { src_fmt, ns, dst_fmt, nd, pan, law }; let src_amb = src_fmt.is_ambisonic() && ns >= 4; if nd == 2 && !dst_fmt.is_ambisonic() { - match ns { - 1 => { - let (gl, gr) = gains(pan.stereo[0], law); - m[0][0] = gl; - m[0][1] = gr; - } - 2 if !src_amb => { - let (a_l, a_r) = gains(pan.stereo[0], PanLaw::Zero); - let (b_l, b_r) = gains(pan.stereo[1], PanLaw::Zero); - m[0] = [0.0; MAX_CHANNELS]; - m[0][0] = a_l; - m[0][1] = a_r; - m[1][0] = b_l; - m[1][1] = b_r; - } - _ if src_amb => { - for (d, az) in [(0usize, -30.0f32), (1, 30.0)] { - let g = soundcraft_dsp::pan::ambisonic_decode(az, 0.0, 2); - for (c, gc) in g.iter().enumerate() { - set(&mut m, c, d, *gc); - } - } - } - _ if src_sp.len() == ns => { - for (s, sp) in src_sp.iter().enumerate() { - let (l, r) = itu_stereo_fold(*sp); - set(&mut m, s, 0, l); - set(&mut m, s, 1, r); - } - } - _ => { - // Unknown layout: first two channels to L/R, the rest to the centre. - let h = std::f32::consts::FRAC_1_SQRT_2; - m[0][0] = 1.0; - m[1][1] = 1.0; - for row in m.iter_mut().take(ns).skip(2) { - row[0] = h; - row[1] = h; - } - } - } - return m; + return stereo_dest(&link, src_amb); } if ns > 2 && src_fmt == dst_fmt && ns == nd { return identity_matrix(ns); } - // Multichannel destination. - let mut layout = [SpeakerPos::default(); MAX_CHANNELS]; - let nl = layout_of(dst_fmt, &mut layout); - let layout = layout.get(..nl).unwrap_or(&[]); - let dst_sp = dst_fmt.speakers(); - let dst_amb = dst_fmt.is_ambisonic(); - let find = |sp: Speaker| dst_sp.iter().position(|x| *x == sp).filter(|i| *i < nd); - let mut g = [0.0f32; MAX_CHANNELS]; - if dst_amb { - if src_amb || (src_fmt.is_ambisonic() && ns > 2) { - return identity_matrix(ns.min(nd)); - } - let mut enc = |m: &mut Matrix, s: usize, az: f32, el: f32, spread: f32| { - soundcraft_dsp::pan::ambisonic_encode(az, el, spread, &mut g); - for (d, gd) in g.iter().enumerate().take(nd) { - set(m, s, d, *gd); - } - }; - match (ns, pan.surround) { - (1 | 2, Some(sp)) => { - for s in 0..ns { - let dx = if ns == 2 { if s == 0 { -1.0 } else { 1.0 } } else { 0.0 }; - let p = surround_params(sp, dx); - enc(&mut m, s, soundcraft_dsp::pan::puck_azimuth(&[], p.x, p.y), p.z * 90.0, p.divergence); - } - } - (1, None) => enc(&mut m, 0, pan.stereo[0].clamp(-1.0, 1.0) * 30.0, 0.0, 0.0), - (2, None) => { - enc(&mut m, 0, -30.0, 0.0, 0.0); - enc(&mut m, 1, 30.0, 0.0, 0.0); - } - _ => { - for (s, sp) in src_sp.iter().enumerate().take(ns) { - if !sp.is_lfe() { - enc(&mut m, s, sp.azimuth(), sp.elevation(), 0.0); - } - } - } - } - return m; + if dst_fmt.is_ambisonic() { + return ambisonic_dest(&link, src_amb); } + layout_dest(&link, src_amb) +} + +/// Routing into a stereo destination. +fn stereo_dest(l: &Link<'_>, src_amb: bool) -> Matrix { + let mut m = [[0.0f32; MAX_CHANNELS]; MAX_CHANNELS]; + let src_sp = l.src_fmt.speakers(); + match l.ns { + 1 => { + let (gl, gr) = gains(l.pan.stereo[0], l.law); + m[0][0] = gl; + m[0][1] = gr; + } + 2 if !src_amb => { + let (a_l, a_r) = gains(l.pan.stereo[0], PanLaw::Zero); + let (b_l, b_r) = gains(l.pan.stereo[1], PanLaw::Zero); + m[0] = [0.0; MAX_CHANNELS]; + m[0][0] = a_l; + m[0][1] = a_r; + m[1][0] = b_l; + m[1][1] = b_r; + } + _ if src_amb => { + for (d, az) in [(0usize, -30.0f32), (1, 30.0)] { + let g = soundcraft_dsp::pan::ambisonic_decode(az, 0.0, 2); + for (c, gc) in g.iter().enumerate() { + add_gain(&mut m, c, d, *gc); + } + } + } + ns if src_sp.len() == ns => { + for (s, sp) in src_sp.iter().enumerate() { + let (left, right) = itu_stereo_fold(*sp); + add_gain(&mut m, s, 0, left); + add_gain(&mut m, s, 1, right); + } + } + ns => { + // Unknown layout: first two channels to L/R, the rest to the centre. + let h = std::f32::consts::FRAC_1_SQRT_2; + m[0][0] = 1.0; + m[1][1] = 1.0; + for row in m.iter_mut().take(ns).skip(2) { + row[0] = h; + row[1] = h; + } + } + } + m +} + +/// `±1` offset spreading a stereo source's two channels left and right of the surround pan. +fn spread_dx(ns: usize, s: usize) -> f32 { + if ns != 2 { + 0.0 + } else if s == 0 { + -1.0 + } else { + 1.0 + } +} + +/// Routing into an ambisonic destination. +fn ambisonic_dest(l: &Link<'_>, src_amb: bool) -> Matrix { + let mut m = [[0.0f32; MAX_CHANNELS]; MAX_CHANNELS]; + let (ns, nd) = (l.ns, l.nd); + if src_amb || (l.src_fmt.is_ambisonic() && ns > 2) { + return identity_matrix(ns.min(nd)); + } + let src_sp = l.src_fmt.speakers(); + let mut g = [0.0f32; MAX_CHANNELS]; + let mut enc = |m: &mut Matrix, s: usize, az: f32, el: f32, spread: f32| { + soundcraft_dsp::pan::ambisonic_encode(az, el, spread, &mut g); + for (d, gd) in g.iter().enumerate().take(nd) { + add_gain(m, s, d, *gd); + } + }; + match (ns, l.pan.surround) { + (1 | 2, Some(sp)) => { + for s in 0..ns { + let p = surround_params(sp, spread_dx(ns, s)); + enc(&mut m, s, soundcraft_dsp::pan::puck_azimuth(&[], p.x, p.y), p.z * 90.0, p.divergence); + } + } + (1, None) => enc(&mut m, 0, l.pan.stereo[0].clamp(-1.0, 1.0) * 30.0, 0.0, 0.0), + (2, None) => { + enc(&mut m, 0, -30.0, 0.0, 0.0); + enc(&mut m, 1, 30.0, 0.0, 0.0); + } + _ => { + for (s, sp) in src_sp.iter().enumerate().take(ns) { + if !sp.is_lfe() { + enc(&mut m, s, sp.azimuth(), sp.elevation(), 0.0); + } + } + } + } + m +} + +/// A surround-panned mono or stereo source into a speaker layout, plus its LFE send. +fn surround_into_layout(m: &mut Matrix, l: &Link<'_>, layout: &[SpeakerPos], sp: &SurroundPan) { + let (ns, nd) = (l.ns, l.nd); + let dst_sp = l.dst_fmt.speakers(); + let mut g = [0.0f32; MAX_CHANNELS]; + for s in 0..ns { + soundcraft_dsp::pan::surround_gains(layout, &surround_params(sp, spread_dx(ns, s)), &mut g); + for (d, gd) in g.iter().enumerate().take(nd) { + add_gain(m, s, d, *gd); + } + if let Some(lfe) = dst_sp.iter().position(|x| *x == Speaker::Lfe).filter(|i| *i < nd) + && sp.lfe_db > -143.9 + { + add_gain(m, s, lfe, db_to_gain(sp.lfe_db.min(12.0)) / ns as f32); + } + } +} + +/// Routing into a speaker layout other than stereo or ambisonic. +fn layout_dest(l: &Link<'_>, src_amb: bool) -> Matrix { + let mut m = [[0.0f32; MAX_CHANNELS]; MAX_CHANNELS]; + let (ns, nd) = (l.ns, l.nd); + let src_sp = l.src_fmt.speakers(); + let mut layout = [SpeakerPos::default(); MAX_CHANNELS]; + let nl = layout_of(l.dst_fmt, &mut layout); + let layout = layout.get(..nl).unwrap_or(&[]); + let dst_sp = l.dst_fmt.speakers(); if dst_sp.len() != nd { // No layout to pan on: channel for channel. return identity_matrix(ns.min(nd)); } + let find = |sp: Speaker| dst_sp.iter().position(|x| *x == sp).filter(|i| *i < nd); let (li, ri) = (find(Speaker::L), find(Speaker::R)); - match (ns, pan.surround) { - (1 | 2, Some(sp)) if !src_amb => { - for s in 0..ns { - let dx = if ns == 2 { if s == 0 { -1.0 } else { 1.0 } } else { 0.0 }; - soundcraft_dsp::pan::surround_gains(layout, &surround_params(sp, dx), &mut g); - for (d, gd) in g.iter().enumerate().take(nd) { - set(&mut m, s, d, *gd); - } - if let Some(lfe) = find(Speaker::Lfe) - && sp.lfe_db > -143.9 - { - set(&mut m, s, lfe, db_to_gain(sp.lfe_db.min(12.0)) / ns as f32); - } - } - } + let mut g = [0.0f32; MAX_CHANNELS]; + match (ns, l.pan.surround) { + (1 | 2, Some(sp)) if !src_amb => surround_into_layout(&mut m, l, layout, sp), (1, None) => { - let (gl, gr) = gains(pan.stereo[0], law); - if let (Some(l), Some(r)) = (li, ri) { - set(&mut m, 0, l, gl); - set(&mut m, 0, r, gr); + let (gl, gr) = gains(l.pan.stereo[0], l.law); + if let (Some(left), Some(right)) = (li, ri) { + add_gain(&mut m, 0, left, gl); + add_gain(&mut m, 0, right, gr); } } (2, None) if !src_amb => { - let (a_l, a_r) = gains(pan.stereo[0], PanLaw::Zero); - let (b_l, b_r) = gains(pan.stereo[1], PanLaw::Zero); - if let (Some(l), Some(r)) = (li, ri) { - set(&mut m, 0, l, a_l); - set(&mut m, 0, r, a_r); - set(&mut m, 1, l, b_l); - set(&mut m, 1, r, b_r); + let (a_l, a_r) = gains(l.pan.stereo[0], PanLaw::Zero); + let (b_l, b_r) = gains(l.pan.stereo[1], PanLaw::Zero); + if let (Some(left), Some(right)) = (li, ri) { + add_gain(&mut m, 0, left, a_l); + add_gain(&mut m, 0, right, a_r); + add_gain(&mut m, 1, left, b_l); + add_gain(&mut m, 1, right, b_r); } } _ if src_amb => { @@ -204,20 +252,19 @@ pub(crate) fn build_matrix(src_fmt: ChannelFormat, ns: usize, dst_fmt: ChannelFo } let dec = soundcraft_dsp::pan::ambisonic_decode(sp.azimuth(), sp.elevation(), n_spk); for (c, gc) in dec.iter().enumerate() { - set(&mut m, c, d, *gc); + add_gain(&mut m, c, d, *gc); } } } _ if src_sp.len() == ns => { for (s, sp) in src_sp.iter().enumerate() { if let Some(d) = find(*sp) { - set(&mut m, s, d, 1.0); - } else if sp.is_lfe() { - // No LFE in the destination: dropped. - } else { + add_gain(&mut m, s, d, 1.0); + } else if !sp.is_lfe() { + // (An LFE with no LFE in the destination is dropped.) soundcraft_dsp::pan::direction_gains(layout, sp.azimuth(), sp.elevation(), &mut g); for (d, gd) in g.iter().enumerate().take(nd) { - set(&mut m, s, d, *gd); + add_gain(&mut m, s, d, *gd); } } } @@ -251,6 +298,33 @@ pub(crate) fn apply_matrix_span(src: &[Vec], span: std::ops::Range, if taps.is_empty() { continue; } + let end = span.end.min(out.len()); + let Some(dst) = out.get_mut(span.start..end) else { continue }; + let lane = |s: usize| src.get(s).and_then(|c| c.get(span.start..end)); + match *taps { + [(s0, g0)] => { + if let Some(x0) = lane(s0) { + for (o, a) in dst.iter_mut().zip(x0) { + let mut acc = 0.0f32; + acc += a * gain * g0; + *o += acc; + } + continue; + } + } + [(s0, g0), (s1, g1)] => { + if let (Some(x0), Some(x1)) = (lane(s0), lane(s1)) { + for ((o, a), b) in dst.iter_mut().zip(x0).zip(x1) { + let mut acc = 0.0f32; + acc += a * gain * g0; + acc += b * gain * g1; + *o += acc; + } + continue; + } + } + _ => {} + } for (i, o) in out.iter_mut().enumerate().take(span.end).skip(span.start) { let mut acc = 0.0f32; for &(s, g) in taps { diff --git a/crates/mix/src/routing.rs b/crates/mix/src/routing.rs index 5b924d50..fcebca85 100644 --- a/crates/mix/src/routing.rs +++ b/crates/mix/src/routing.rs @@ -1,4 +1,6 @@ -use super::*; +use super::{BusId, Route, Session, Track, TrackKind}; +use std::collections::HashMap; +use std::sync::Arc; /// Hash of everything `sync`/`processing_order` depend on (tracks, kinds, routing, plugins, sends). pub(crate) fn structure_fingerprint(s: &Session) -> usize { @@ -153,6 +155,7 @@ pub(crate) fn receives_solo(s: &Session, t: &Track) -> bool { #[allow(clippy::unwrap_used)] mod processing_order_tests { use super::*; + use soundcraft_model::ChannelFormat; use soundcraft_model::SendSlot; #[test] diff --git a/crates/mix/src/strip.rs b/crates/mix/src/strip.rs index f77f5b40..01f4a11a 100644 --- a/crates/mix/src/strip.rs +++ b/crates/mix/src/strip.rs @@ -1,10 +1,15 @@ -use super::automation::{lerp_gain, transport_at, volume_db_at}; +use super::automation::{GainRamp, transport_at, volume_db_at}; use super::clips::{ClipFx, clip_fx_params, render_clip}; use super::instances::{INSTRUMENT_SLOT, PluginFailures, PreparedInstance, create_instance, is_third_party}; use super::midi::{chase_controllers, schedule_notes}; use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix}; use super::routing::receives_solo; -use super::*; +use super::{ + AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport, + db_to_gain, +}; +use std::collections::HashMap; +use std::sync::Arc; /// A bus: its format and one buffer per channel. pub(crate) struct BusBuf { @@ -199,131 +204,130 @@ pub(crate) struct LiveInput<'a> { pub(crate) recording: bool, } -pub(crate) fn process_strip( - s: &Session, - t: &Track, - strip: &mut Strip, - busses: &HashMap, - live: &LiveInput<'_>, - pos: Samples, - frames: usize, - any_solo: bool, -) { - for c in strip.buf.iter_mut() { +/// The block being rendered: where it starts, its length, and whether any track is soloed. +#[derive(Clone, Copy)] +pub(crate) struct Block { + pub(crate) pos: Samples, + pub(crate) frames: usize, + pub(crate) any_solo: bool, +} + +fn zero_buf(buf: &mut [Vec], frames: usize) { + for c in buf.iter_mut() { c.iter_mut().take(frames).for_each(|x| *x = 0.0); } - let transport = transport_at(s, pos, !live.monitor_only, live.recording); - match t.kind { - TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => { - // Input monitoring: the track hears its hardware input instead of its clips. - let first = match &t.mixer.input { - Route::Hardware(h) => { - h.trim_start_matches("In ").split(['-', ' ']).next().and_then(|n| n.parse::().ok()).map_or(0, |n| n.saturating_sub(1)) - } - _ => 0, - }; - let n_in = live.input.len().max(1); - for (k, dst) in strip.buf.iter_mut().enumerate() { - if let Some(src) = live.input.get((first + k) % n_in) { - for (d, x) in dst.iter_mut().zip(src.iter()).take(frames) { - *d = *x; - } - } - } +} + +/// Input monitoring: the track hears its hardware input instead of its clips. +fn monitor_input(t: &Track, strip: &mut Strip, live: &LiveInput<'_>, frames: usize) { + let first = match &t.mixer.input { + Route::Hardware(h) => { + h.trim_start_matches("In ").split(['-', ' ']).next().and_then(|n| n.parse::().ok()).map_or(0, |n| n.saturating_sub(1)) } - TrackKind::Audio if live.monitor_only => {} - TrackKind::Instrument | TrackKind::Midi if live.monitor_only => {} - TrackKind::Audio => { - let block = Range { start: pos, end: pos.saturating_add(frames as i64) }; - for clip in t.clips() { - if clip.muted || !clip.is_audio() || !clip.range().overlaps(&block) { - continue; - } - match clip_fx_params(s, clip.id.0) { - None => render_clip(s, clip, pos, frames, &mut strip.buf, &mut strip.scratch), - Some(params) => { - let nch = strip.buf.len(); - if strip.clipbuf.len() != nch || strip.clipbuf.first().map_or(0, Vec::len) < frames { - strip.clipbuf = vec![vec![0.0; frames.max(strip.scratch.len())]; nch]; - } - for c in strip.clipbuf.iter_mut() { - c.iter_mut().take(frames).for_each(|x| *x = 0.0); - } - render_clip(s, clip, pos, frames, &mut strip.clipbuf, &mut strip.scratch); - let fx = strip.clip_fx.entry(clip.id.0).or_insert_with(|| ClipFx::new(s.sample_rate.as_f64() as f32, nch)); - fx.configure(params); - fx.process(&mut strip.clipbuf, frames); - for (d, c) in strip.buf.iter_mut().zip(strip.clipbuf.iter()) { - for (x, y) in d.iter_mut().zip(c.iter()).take(frames) { - *x += *y; - } - } - } - } + _ => 0, + }; + let n_in = live.input.len().max(1); + for (k, dst) in strip.buf.iter_mut().enumerate() { + if let Some(src) = live.input.get((first + k) % n_in) { + for (d, x) in dst.iter_mut().zip(src.iter()).take(frames) { + *d = *x; } } - TrackKind::Aux | TrackKind::Folder => { - if let Route::Bus(b) = &t.mixer.input - && let Some(src) = busses.get(b) - { - let (ns, nd) = (src.buf.len(), strip.buf.len()); - let dst_fmt = strip_format(t, nd); - let m = if src.fmt == dst_fmt && ns == nd { - identity_matrix(ns) - } else if ns == 1 && nd == 2 { - // A mono bus feeds both sides of a stereo aux. - let mut m = [[0.0; MAX_CHANNELS]; MAX_CHANNELS]; - m[0][0] = 1.0; - m[0][1] = 1.0; - m - } else { - let stereo = if ns == 1 { [0.0, 0.0] } else { [-1.0, 1.0] }; - build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3) - }; - apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0); - } - } - TrackKind::Instrument | TrackKind::Midi => { - if let Some(inst) = strip.instrument.as_mut().filter(|i| !i.failed) { - // #152: push the instrument's stored parameter values into the live plugin - // before processing, the same way inserts do below. Without this, the values - // loaded from a session (or set via `mix.insert_state`) never reach the plugin - // instance and the rendered audio matches the plugin's defaults — e.g. a saved - // `level = -12 dB` sounds the same as `level = -6 dB`. - if let Some(ins) = &t.instrument { - apply_params(inst, ins, t, INSTRUMENT_SLOT, pos); - } - inst.plugin.set_transport(&transport); - if std::mem::take(&mut strip.chase) { - chase_controllers(s, t, pos, inst); - } - schedule_notes(s, t, pos, frames, inst, &mut strip.held); - if strip.buf.len() >= 2 { - inst.plugin.process(&mut strip.buf, frames); - } else if let Some(c0) = strip.buf.first_mut() { - // Mono MIDI track: render the instrument in stereo and fold. - let mut st = [std::mem::take(c0), std::mem::take(&mut strip.scratch)]; - inst.plugin.process(&mut st, frames); - let [a, b] = st; - *c0 = a; - strip.scratch = b; - for (x, y) in c0.iter_mut().zip(strip.scratch.iter()).take(frames) { - *x = 0.5 * (*x + *y); - } - } - if contain_failure(inst, &mut strip.buf, frames) { - strip.failures.record(INSTRUMENT_SLOT); - } - } - } - _ => {} - } - let trim = db_to_gain(t.mixer.trim_db) * if t.mixer.phase_invert { -1.0 } else { 1.0 }; - if (trim - 1.0).abs() > f32::EPSILON { - for c in strip.buf.iter_mut() { - c.iter_mut().take(frames).for_each(|x| *x *= trim); - } } +} + +/// Render the audio clips overlapping the block into the strip, through their clip effects. +fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) { + let Block { pos, frames, .. } = blk; + let block = Range { start: pos, end: pos.saturating_add(frames as i64) }; + for clip in t.clips() { + if clip.muted || !clip.is_audio() || !clip.range().overlaps(&block) { + continue; + } + match clip_fx_params(s, clip.id.0) { + None => render_clip(s, clip, pos, frames, &mut strip.buf, &mut strip.scratch), + Some(params) => { + let nch = strip.buf.len(); + if strip.clipbuf.len() != nch || strip.clipbuf.first().map_or(0, Vec::len) < frames { + strip.clipbuf = vec![vec![0.0; frames.max(strip.scratch.len())]; nch]; + } + zero_buf(&mut strip.clipbuf, frames); + render_clip(s, clip, pos, frames, &mut strip.clipbuf, &mut strip.scratch); + let fx = strip.clip_fx.entry(clip.id.0).or_insert_with(|| ClipFx::new(s.sample_rate.as_f64() as f32, nch)); + fx.configure(params); + fx.process(&mut strip.clipbuf, frames); + for (d, c) in strip.buf.iter_mut().zip(strip.clipbuf.iter()) { + for (x, y) in d.iter_mut().zip(c.iter()).take(frames) { + *x += *y; + } + } + } + } + } +} + +/// An aux or folder reads the bus its input is routed from. +fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap, frames: usize) { + if let Route::Bus(b) = &t.mixer.input + && let Some(src) = busses.get(b) + { + let (ns, nd) = (src.buf.len(), strip.buf.len()); + let dst_fmt = strip_format(t, nd); + let m = if src.fmt == dst_fmt && ns == nd { + identity_matrix(ns) + } else if ns == 1 && nd == 2 { + // A mono bus feeds both sides of a stereo aux. + let mut m = [[0.0; MAX_CHANNELS]; MAX_CHANNELS]; + m[0][0] = 1.0; + m[0][1] = 1.0; + m + } else { + let stereo = if ns == 1 { [0.0, 0.0] } else { [-1.0, 1.0] }; + build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3) + }; + apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0); + } +} + +/// Render the track's instrument into the strip. +fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) { + let Block { pos, frames, .. } = blk; + if let Some(inst) = strip.instrument.as_mut().filter(|i| !i.failed) { + // #152: push the instrument's stored parameter values into the live plugin + // before processing, the same way inserts do below. Without this, the values + // loaded from a session (or set via `mix.insert_state`) never reach the plugin + // instance and the rendered audio matches the plugin's defaults — e.g. a saved + // `level = -12 dB` sounds the same as `level = -6 dB`. + if let Some(ins) = &t.instrument { + apply_params(inst, ins, t, INSTRUMENT_SLOT, pos); + } + inst.plugin.set_transport(transport); + if std::mem::take(&mut strip.chase) { + chase_controllers(s, t, pos, inst); + } + schedule_notes(s, t, pos, frames, inst, &mut strip.held); + if strip.buf.len() >= 2 { + inst.plugin.process(&mut strip.buf, frames); + } else if let Some(c0) = strip.buf.first_mut() { + // Mono MIDI track: render the instrument in stereo and fold. + let mut st = [std::mem::take(c0), std::mem::take(&mut strip.scratch)]; + inst.plugin.process(&mut st, frames); + let [a, b] = st; + *c0 = a; + strip.scratch = b; + for (x, y) in c0.iter_mut().zip(strip.scratch.iter()).take(frames) { + *x = 0.5 * (*x + *y); + } + } + if contain_failure(inst, &mut strip.buf, frames) { + strip.failures.record(INSTRUMENT_SLOT); + } + } +} + +/// Run the active inserts in order; records their latency and the first gain reduction. +fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) { + let Block { pos, frames, .. } = blk; let mut gr = 0.0f32; let mut latency = 0usize; for (i, ins) in t.mixer.inserts.iter().enumerate() { @@ -332,7 +336,7 @@ pub(crate) fn process_strip( continue; } apply_params(slot, ins, t, i, pos); - slot.plugin.set_transport(&transport); + slot.plugin.set_transport(transport); slot.plugin.process(&mut strip.buf, frames); if contain_failure(slot, &mut strip.buf, frames) { strip.failures.record(i); @@ -345,15 +349,11 @@ pub(crate) fn process_strip( } strip.gr = gr; strip.latency = latency.min(MAX_LATENCY); - let soloed_out = any_solo && !t.mixer.solo && !t.mixer.solo_safe && !receives_solo(s, t); - strip.muted = t.mixer.mute || soloed_out; - if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) { - strip.pre.resize_with(strip.buf.len(), Vec::new); - for (d, src) in strip.pre.iter_mut().zip(strip.buf.iter()) { - d.clear(); - d.extend_from_slice(src.get(..frames).unwrap_or(&[])); - } - } +} + +/// Fader gain (volume, trim and VCA automation), ramped across the block. +fn apply_fader(s: &Session, t: &Track, strip: &mut Strip, blk: Block) { + let Block { pos, frames, .. } = blk; // Endpoints are the first and last sample of this block. The next block starts on its own // first sample, so a breakpoint there does not ramp the block before it. let last = pos.saturating_add(frames.saturating_sub(1) as i64); @@ -380,16 +380,19 @@ pub(crate) fn process_strip( } } let (g0, g1) = if strip.muted { (-144.0, -144.0) } else { (v0.min(12.0), v1.min(12.0)) }; + let ramp = GainRamp::new(g0, g1, frames.saturating_sub(1)); for c in strip.buf.iter_mut() { - for i in 0..frames { - if let Some(x) = c.get_mut(i) { - *x *= lerp_gain(g0, g1, i, frames.saturating_sub(1)); - } + for (i, x) in c.iter_mut().enumerate().take(frames) { + *x *= ramp.at(i); } } - // Track mute gates the audio and its pre-fader tap without splitting processor blocks. - // Keep the existing curve interpolation, first-lane and mode policy, and render-position - // clock. Processor/bus age and Master/VCA automation policy are separate concerns. +} + +/// Track mute gates the audio and its pre-fader tap without splitting processor blocks. +/// Keep the existing curve interpolation, first-lane and mode policy, and render-position +/// clock. Processor/bus age and Master/VCA automation policy are separate concerns. +fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) { + let Block { pos, frames, .. } = blk; if t.mixer.automation_mode.reads() && let Some(lane) = t.lane(&AutoParam::Mute).filter(|lane| !lane.points.is_empty()) { @@ -406,6 +409,41 @@ pub(crate) fn process_strip( } } +pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap, live: &LiveInput<'_>, blk: Block) { + let Block { pos, frames, any_solo } = blk; + zero_buf(&mut strip.buf, frames); + let transport = transport_at(s, pos, !live.monitor_only, live.recording); + match t.kind { + TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => { + monitor_input(t, strip, live, frames); + } + TrackKind::Audio if live.monitor_only => {} + TrackKind::Instrument | TrackKind::Midi if live.monitor_only => {} + TrackKind::Audio => render_audio_clips(s, t, strip, blk), + TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames), + TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, blk, &transport), + _ => {} + } + let trim = db_to_gain(t.mixer.trim_db) * if t.mixer.phase_invert { -1.0 } else { 1.0 }; + if (trim - 1.0).abs() > f32::EPSILON { + for c in strip.buf.iter_mut() { + c.iter_mut().take(frames).for_each(|x| *x *= trim); + } + } + run_inserts(t, strip, blk, &transport); + let soloed_out = any_solo && !t.mixer.solo && !t.mixer.solo_safe && !receives_solo(s, t); + strip.muted = t.mixer.mute || soloed_out; + if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) { + strip.pre.resize_with(strip.buf.len(), Vec::new); + for (d, src) in strip.pre.iter_mut().zip(strip.buf.iter()) { + d.clear(); + d.extend_from_slice(src.get(..frames).unwrap_or(&[])); + } + } + apply_fader(s, t, strip, blk); + gate_mute_automation(t, strip, blk); +} + /// Silences a block the plugin filled with NaN or infinity and takes the plugin out until the /// next [`MixEngine::reset`]. True then. pub(crate) fn contain_failure(slot: &mut PluginSlot, buf: &mut [Vec], frames: usize) -> bool { diff --git a/crates/mix/src/tests.rs b/crates/mix/src/tests.rs index 564db692..5ebc6db1 100644 --- a/crates/mix/src/tests.rs +++ b/crates/mix/src/tests.rs @@ -1150,3 +1150,40 @@ fn surround_upmix_and_downmix_between_layouts() { let e_ls = out[4][100].powi(2) + out[6][100].powi(2); assert!((e_ls - x(4).powi(2)).abs() < 1e-5, "Ls energy is preserved"); } + +#[test] +fn apply_matrix_span_matches_the_plain_per_sample_sum() { + let src: Vec> = (0..3).map(|c| (0..300).map(|i| ((i * 7 + c * 13) % 23) as f32 * 0.037 - 0.4).collect()).collect(); + let short = vec![src[0].clone(), src[1][..150].to_vec(), src[2].clone()]; + let mut layouts: Vec> = + vec![vec![(0, 0, 0.7)], vec![(0, 0, 0.7), (1, 1, -0.3)], vec![(0, 0, 0.6), (1, 0, 0.45), (1, 1, 1.0)]]; + layouts.push(vec![(0, 0, 0.5), (1, 0, 0.25), (2, 0, 0.125), (2, 1, 0.9)]); + for taps in &layouts { + let mut m = [[0.0f32; MAX_CHANNELS]; MAX_CHANNELS]; + for &(s, d, g) in taps { + m[s][d] = g; + } + for input in [&src, &short] { + for span in [0..300, 17..211, 140..160, 250..400, 5..5] { + let mut got: Vec> = (0..2).map(|d| (0..300).map(|i| (i + d) as f32 * 1e-3).collect()).collect(); + let mut want = got.clone(); + pan::apply_matrix_span(input, span.clone(), &mut got, &m, 0.8); + for (d, out) in want.iter_mut().enumerate() { + for (i, o) in out.iter_mut().enumerate().take(span.end).skip(span.start) { + let mut acc = 0.0f32; + for (s, row) in m.iter().enumerate().take(input.len()) { + if row[d] != 0.0 { + acc += input[s].get(i).copied().unwrap_or(0.0) * 0.8 * row[d]; + } + } + if m.iter().take(input.len()).any(|row| row[d] != 0.0) { + *o += acc; + } + } + } + let bits = |v: &Vec>| v.iter().flatten().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&got), bits(&want), "taps {taps:?}, span {span:?}"); + } + } + } +} diff --git a/crates/mix/src/threads.rs b/crates/mix/src/threads.rs index cfb2dd98..c71fb3fc 100644 --- a/crates/mix/src/threads.rs +++ b/crates/mix/src/threads.rs @@ -1,4 +1,4 @@ -use super::*; +use super::AUDIO_THREAD; /// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks /// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads diff --git a/crates/playback/src/callback.rs b/crates/playback/src/callback.rs index fc89c16e..5e931fe0 100644 --- a/crates/playback/src/callback.rs +++ b/crates/playback/src/callback.rs @@ -1,4 +1,8 @@ -use super::*; +use super::{ + Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin, + PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId, + itu_stereo_fold, main_channels, record, sync_channel, +}; /// How the audio output is doing, for the UI. #[derive(Default)] diff --git a/crates/playback/src/stream.rs b/crates/playback/src/stream.rs index af90a912..a1f78530 100644 --- a/crates/playback/src/stream.rs +++ b/crates/playback/src/stream.rs @@ -1,5 +1,5 @@ use super::callback::{AudioState, Fault, guarded_block}; -use super::*; +use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread}; /// Start a freshly built output stream. `false` when the device refuses to start it, so the caller /// treats it like a stream that failed to build and tries the next configuration. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c3289263..35ca5974 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,6 +1,10 @@ use super::services::Services; use super::state::MainWindow; -use super::*; +use super::{ + ControlRequest, Engine, Gesture, HashMap, MeterDisplay, OutputTrouble, Player, Range, Receiver, Samples, SoundApp, TrackId, TransportRequest, + Trouble, UiState, Value, VecDeque, bounce, dialogs, edit_window, extra_windows, fonts, import, json, menus, midi_editor, mix_window, ops_windows, + palette, panels, recovery, sampler_window, score_editor, shortcuts, theme, updates_ui, video_track, video_window, windows, +}; mod audio; mod commands; @@ -16,6 +20,12 @@ pub(crate) use playback::automation_step_due; pub(crate) use plugins::{editor_changes, editor_states_due, failed_plugin_status}; impl SoundApp { + /// Whether fonts installed from the system are used besides the bundled ones (on by default). + /// Takes effect only before the first frame installs the fonts. + pub fn set_system_fonts(&mut self, on: bool) { + self.system_fonts = on; + } + /// Build an app around an engine and optional player, initialising UI, recording, autosave, control and /// synthetic-input state. pub fn new(engine: Engine, player: Option, services: Services) -> Self { @@ -87,6 +97,7 @@ impl SoundApp { last_rev: 0, fonts_ready: false, fonts_installed: false, + system_fonts: true, theme_applied: None, docking_context: None, sim: None, @@ -130,7 +141,7 @@ impl SoundApp { if self.fonts_installed { self.fonts_ready = true; } else { - fonts::install(ctx); + fonts::install(ctx, self.system_fonts); self.fonts_installed = true; ctx.request_repaint(); } diff --git a/crates/ui-egui/src/app/audio.rs b/crates/ui-egui/src/app/audio.rs index 7a9f9bf1..3ec92849 100644 --- a/crates/ui-egui/src/app/audio.rs +++ b/crates/ui-egui/src/app/audio.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{MeterDisplay, OutputTrouble, Player, SoundApp, Trouble}; impl SoundApp { /// Whether the meters are live: while playing, and while armed or input-monitored tracks are heard. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 2ae62f9b..422ff784 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, Value, bounce, menus}; impl SoundApp { /// Run a command; errors go to the status line. Returns the result. diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index ab5f91a6..1ba17caf 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, Value, json}; use crate::control; impl SoundApp { diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 22ce03dd..6b230d34 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, midi_editor}; impl SoundApp { /// The open document was replaced outside [`Self::run`] (Recover, a session the browser read diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 73ba2a5d..c6167d5a 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, json, sampler_window}; impl SoundApp { /// Feed queued synthetic input (from the control channel) into egui: one pointer event per @@ -139,18 +139,22 @@ impl SoundApp { } let mut claimed = false; for (file, pos) in std::mem::take(&mut self.pending_drops) { - let path = file.path().to_string_lossy().into_owned(); // As before, one dropped audio file goes to the sampler under the pointer; the rest // are left to the shell. - let claim = !claimed && sampler_window::is_audio_name(&path); + let claim = !claimed && sampler_window::is_audio_name(file.path()); let Some(track) = self.drop_track(pos).filter(|_| claim) else { self.host_drops.push(file); continue; }; claimed = true; if file.path().is_absolute() { - let r = self.run("mix.sampler_load", json!({"track": track.0, "path": path})); - self.sample_loaded(track, &path, r); + match crate::dialogs::unicode(file.path()) { + Ok(path) => { + let r = self.run("mix.sampler_load", json!({"track": track.0, "path": path})); + self.sample_loaded(track, path, r); + } + Err(e) => self.ui.status = e.to_string(), + } } else { self.sample_reads.push(sampler_window::SampleRead { track, file }); } diff --git a/crates/ui-egui/src/app/playback.rs b/crates/ui-egui/src/app/playback.rs index fd17adc4..65c6c194 100644 --- a/crates/ui-egui/src/app/playback.rs +++ b/crates/ui-egui/src/app/playback.rs @@ -1,6 +1,6 @@ use super::audio::feed_meter; use super::plugins::failed_plugin_status; -use super::*; +use super::{Gesture, MainWindow, MeterDisplay, Range, Samples, SoundApp, TrackId, TransportRequest, json}; /// Whether another automation-write pass is due: the transport moved at least /// `step` since `last` in either direction. `last == i64::MIN` marks "never diff --git a/crates/ui-egui/src/app/plugins.rs b/crates/ui-egui/src/app/plugins.rs index da316f9b..19feaee7 100644 --- a/crates/ui-egui/src/app/plugins.rs +++ b/crates/ui-egui/src/app/plugins.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, TrackId, json, mix_window}; /// The plugins whose state the session takes this frame, out of those changed in their editors /// (`pending`, kept across frames). A plugin editor doesn't say when a gesture ends: a plugin's diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index b8940897..c22c4720 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -221,7 +221,7 @@ fn contributors_toolbar(ui: &mut egui::Ui, v: &mut View) { } ui.separator(); let sort = ui.label("Sort"); - let combo = egui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| { + let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| { for k in SortKey::ALL { if ui.selectable_label(v.key == k, k.label().0).clicked() { v.key = k; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 58d80ecd..fc18e173 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4,6 +4,7 @@ use crate::SoundApp; use crate::theme::{Tokens, bold}; use egui::{Align2, vec2}; use serde_json::{Value, json}; +use soundcraft_audio_io::FileFormat; use soundcraft_engine::Engine; use soundcraft_engine::io::StripNames; use soundcraft_model::{ClipId, GroupId, Session, SourceId, TrackId}; @@ -17,8 +18,8 @@ mod strip_silence; #[cfg(test)] use audiosuite::SPEED_RAMP_CHOICES; use audiosuite::audiosuite_window; +pub use files::{NotUnicode, ask_to_save, open_path, open_session_bytes, run_or_ask, takes_path, unicode}; use files::{OPEN_PENDING, default_dir, open_pending_session, path_dialog}; -pub use files::{ask_to_save, open_session_bytes, run_or_ask, takes_path}; use strip_silence::{AUTO_NAME_LABELS, STRIP_NAME_LABELS, StripRectangles, auto_rename_action, strip_name_fields, strip_silence_action}; pub use strip_silence::{StripRects, strip_silence_rectangles}; @@ -31,7 +32,7 @@ pub mod spot; pub enum Dialog { NewTracks { count: u32, format: String, kind: String, timebase: String, name: String }, NewSession { name: String, sample_rate: u32, demo: bool }, - Bounce { path: String, format: String, bit_depth: String, normalize: bool, dither: bool }, + Bounce { path: String, format: FileFormat, bit_depth: String, normalize: bool, dither: bool }, RenameTrack { id: TrackId, name: String }, RenameClip { id: ClipId, name: String }, RenameMarker { id: soundcraft_model::MarkerId, name: String }, @@ -178,7 +179,7 @@ impl Dialogs { .map_or(home.clone(), |d| d.display().to_string()); Dialog::Bounce { path: format!("{dir}/{name} Bounce.wav"), - format: "wav".into(), + format: FileFormat::Wav, bit_depth: "24".into(), normalize: false, dither: false, @@ -280,6 +281,175 @@ fn clear_message(s: &Session, clips: &[ClipId], sources: &[SourceId]) -> Option< Some(text) } +/// The New Tracks form; the command to run once Create is pressed. +fn new_tracks_form( + ui: &mut egui::Ui, + count: &mut u32, + format: &mut String, + kind: &mut String, + timebase: &mut String, + name: &mut String, + enter: bool, +) -> Option<(String, Value)> { + ui.horizontal(|ui| { + let create = ui.label("Create"); + ui.add(egui::DragValue::new(count).range(1..=128)).labelled_by(create.id); + ui.label("new"); + let fmt = craft_ui::ComboBox::from_id_salt("nt_fmt").selected_text(format.as_str()).show_ui(ui, |ui| { + for f in soundcraft_model::ChannelFormat::ALL { + ui.selectable_value(format, f.label().to_string(), f.label()); + } + }); + fmt.response.accessible_name("Channel format"); + let kind_combo = craft_ui::ComboBox::from_id_salt("nt_kind") + .selected_text(soundcraft_model::TrackKind::from_id(kind).map_or("Audio Track", |k| k.label())) + .show_ui(ui, |ui| { + for k in soundcraft_model::TrackKind::ALL { + if ui.selectable_label(kind == k.id(), k.label()).clicked() { + *kind = k.id().to_string(); + *name = k.default_name().to_string(); + } + } + }); + kind_combo.response.accessible_name("Track kind"); + ui.label("in"); + let tb = craft_ui::ComboBox::from_id_salt("nt_tb").selected_text(if timebase == "ticks" { "Ticks" } else { "Samples" }).show_ui(ui, |ui| { + ui.selectable_value(timebase, "samples".to_string(), "Samples"); + ui.selectable_value(timebase, "ticks".to_string(), "Ticks"); + }); + tb.response.accessible_name("Timebase"); + }); + ui.horizontal(|ui| { + ui.label("Name:"); + crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(name).desired_width(240.0)), "Name"); + }); + if buttons(ui, "Create", enter) { + return Some(("track.new".into(), json!({"count": count, "format": format, "kind": kind, "timebase": timebase, "name": name}))); + } + None +} + +/// The Bounce form's file row: a path field and a Browse button that also picks the format. +fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, format: &mut FileFormat) { + ui.horizontal(|ui| { + ui.label("File"); + crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "File"); + if let Some(pick) = &app.services.pick_save + && ui.button("Browse…").clicked() + && let Some(p) = pick("file.bounce_mix", std::path::Path::new(path.as_str())) + { + match unicode(&p) { + Ok(text) => { + *path = text.to_owned(); + if let Some(picked) = p.extension().and_then(std::ffi::OsStr::to_str).and_then(FileFormat::from_write_extension) { + *format = picked; + } + } + Err(e) => app.ui.status = e.to_string(), + } + } + }); +} + +/// The path prompt's form; the command to run once it is confirmed. +fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut String, key: &str, enter: bool) -> Option<(String, Value)> { + crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "Path"); + let mut picked = None; + if let Some(pick) = &app.services.pick_open + && cmd != "session.save_as" + && cmd != "session.save_copy" + && key != "dir" + && ui.button("Browse…").clicked() + && let Some(p) = pick(cmd, &[]) + { + picked = Some(p); + } + if let Some(pick) = &app.services.pick_folder + && key == "dir" + && ui.button("Browse…").clicked() + && let Some(p) = pick(std::path::Path::new(path.as_str())) + { + picked = Some(p); + } + if let Some(pick) = &app.services.pick_save + && (cmd == "session.save_as" || cmd == "session.save_copy") + && ui.button("Browse…").clicked() + && let Some(p) = pick(cmd, std::path::Path::new(path.as_str())) + { + picked = Some(p); + } + match picked.as_deref().map(unicode) { + Some(Ok(text)) => *path = text.to_owned(), + Some(Err(e)) => app.ui.status = e.to_string(), + None => {} + } + let file = soundcraft_engine::io::session_file(path); + let replaces = soundcraft_engine::io::replaces(&app.engine, cmd, &file); + if replaces { + ui.label(format!("“{}” already exists. Do you want to replace it?", file.file_name().unwrap_or_default().to_string_lossy())); + } + if buttons(ui, if replaces { "Replace" } else { "OK" }, enter && !replaces) { + let mut v = json!({}); + v[key] = json!(path); + if replaces { + v["replace"] = json!(true); + } + return Some((cmd.to_string(), v)); + } + None +} + +/// The Strip Silence form: the Strip Silence command to run, or the values to carry into Rename. +fn strip_silence_form( + ui: &mut egui::Ui, + values: &mut [f64; 4], + strip_names: &StripNames, + enter: bool, +) -> (Option<(String, Value)>, Option<[f64; 4]>) { + let mut action = None; + let mut rename_from = None; + let [threshold, min_ms, pre_ms, post_ms] = values; + let before = [*threshold, *min_ms, *pre_ms, *post_ms]; + ui.add(egui::Slider::new(threshold, -96.0..=0.0).text("Threshold dB")); + ui.add(egui::Slider::new(min_ms, 0.0..=4000.0).text("Min strip duration ms")); + ui.add(egui::Slider::new(pre_ms, 0.0..=500.0).text("Clip start pad ms")); + ui.add(egui::Slider::new(post_ms, 0.0..=2000.0).text("Clip end pad ms")); + let values = [*threshold, *min_ms, *pre_ms, *post_ms]; + // The Edit window is drawn before this window, so it draws the rectangles for new values in the next frame. + if values != before { + ui.ctx().request_repaint(); + } + if !strip_names.name.trim().is_empty() { + let names = format!("New clips are named {}, {} and so on.", strip_names.clip_name(0), strip_names.clip_name(1)); + ui.label(egui::RichText::new(names).small().color(Tokens::current().text_dim)); + } + ui.separator(); + ui.horizontal(|ui| { + let mut mode = None; + let mut rename = false; + if ui.button("Extract").clicked() { + mode = Some("extract"); + } + if ui.button("Rename…").clicked() { + rename = true; + } + if ui.button("Separate").clicked() { + mode = Some("separate"); + } + // Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked. + if buttons(ui, "Strip", enter) && mode.is_none() { + mode = Some("strip"); + } + // Enter on a focused Rename… also presses Strip, so Rename… goes first. + if rename { + rename_from = Some(values); + } else if let Some(mode) = mode { + action = Some(strip_silence_action(mode, values, strip_names)); + } + }); + (action, rename_from) +} + /// Show the open dialog, if any. pub fn show(app: &mut SoundApp, ctx: &egui::Context) { audiosuite_window(app, ctx); @@ -327,44 +497,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { ui.spacing_mut().item_spacing = vec2(8.0, 8.0); match &mut d { Dialog::NewTracks { count, format, kind, timebase, name } => { - ui.horizontal(|ui| { - let create = ui.label("Create"); - ui.add(egui::DragValue::new(count).range(1..=128)).labelled_by(create.id); - ui.label("new"); - let fmt = egui::ComboBox::from_id_salt("nt_fmt").selected_text(format.as_str()).show_ui(ui, |ui| { - for f in soundcraft_model::ChannelFormat::ALL { - ui.selectable_value(format, f.label().to_string(), f.label()); - } - }); - fmt.response.accessible_name("Channel format"); - let kind_combo = egui::ComboBox::from_id_salt("nt_kind") - .selected_text(soundcraft_model::TrackKind::from_id(kind).map_or("Audio Track", |k| k.label())) - .show_ui(ui, |ui| { - for k in soundcraft_model::TrackKind::ALL { - if ui.selectable_label(kind == k.id(), k.label()).clicked() { - *kind = k.id().to_string(); - *name = k.default_name().to_string(); - } - } - }); - kind_combo.response.accessible_name("Track kind"); - ui.label("in"); - let tb = egui::ComboBox::from_id_salt("nt_tb").selected_text(if timebase == "ticks" { "Ticks" } else { "Samples" }).show_ui( - ui, - |ui| { - ui.selectable_value(timebase, "samples".to_string(), "Samples"); - ui.selectable_value(timebase, "ticks".to_string(), "Ticks"); - }, - ); - tb.response.accessible_name("Timebase"); - }); - ui.horizontal(|ui| { - ui.label("Name:"); - crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(name).desired_width(240.0)), "Name"); - }); - if buttons(ui, "Create", enter) { - action = - Some(("track.new".into(), json!({"count": count, "format": format, "kind": kind, "timebase": timebase, "name": name}))); + if let Some(cmd) = new_tracks_form(ui, count, format, kind, timebase, name, enter) { + action = Some(cmd); } } Dialog::NewSession { name, sample_rate, demo } => { @@ -372,7 +506,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { ui.label("Name"); crate::widgets::named_text_field(ui.text_edit_singleline(name), "Name"); }); - egui::ComboBox::from_label("Sample Rate").selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Sample Rate").selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| { for r in soundcraft_time::SampleRate::COMMON { ui.selectable_value(sample_rate, r, format!("{r} Hz")); } @@ -386,29 +520,14 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { } } Dialog::Bounce { path, format, bit_depth, normalize, dither } => { + bounce_file_row(app, ui, path, format); ui.horizontal(|ui| { - ui.label("File"); - crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "File"); - if let Some(pick) = &app.services.pick_save - && ui.button("Browse…").clicked() - && let Some(p) = pick("file.bounce_mix", path) - { - *path = p; - match std::path::Path::new(path.as_str()).extension().map(|x| x.to_string_lossy().to_lowercase()).as_deref() { - Some("wav") => *format = "wav".into(), - Some("aif" | "aiff") => *format = "aiff".into(), - Some("flac") => *format = "flac".into(), - _ => {} - } - } - }); - ui.horizontal(|ui| { - egui::ComboBox::from_label("Format").selected_text(format.to_uppercase()).show_ui(ui, |ui| { - for f in ["wav", "aiff", "flac"] { - ui.selectable_value(format, f.to_string(), f.to_uppercase()); + craft_ui::ComboBox::from_label("Format").selected_text(format.name()).show_ui(ui, |ui| { + for &f in FileFormat::WRITE { + ui.selectable_value(format, f, f.name()); } }); - egui::ComboBox::from_label("Bit Depth").selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Bit Depth").selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| { for b in ["16", "24", "32f"] { ui.selectable_value(bit_depth, b.to_string(), format!("{b}-bit")); } @@ -426,10 +545,10 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { .color(Tokens::current().text_dim), ); if buttons(ui, "Bounce", enter) { - let p = std::path::Path::new(path.as_str()).with_extension(if format == "aiff" { "aif" } else { format.as_str() }); + let p = std::path::Path::new(path.as_str()).with_extension(format.default_extension()); crate::bounce::start( app, - &json!({"path": p.to_string_lossy(), "format": format, "bit_depth": bit_depth, "normalize": normalize, "dither": *dither && bit_depth.as_str() != "32f"}), + &json!({"path": p.to_string_lossy(), "format": format.default_extension(), "bit_depth": bit_depth, "normalize": normalize, "dither": *dither && bit_depth.as_str() != "32f"}), ); keep = false; } @@ -460,42 +579,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { } } Dialog::PathPrompt { cmd, path, key, .. } => { - crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "Path"); - if let Some(pick) = &app.services.pick_open - && cmd != "session.save_as" - && cmd != "session.save_copy" - && key != "dir" - && ui.button("Browse…").clicked() - && let Some(p) = pick(cmd, &[]) - { - *path = p; - } - if let Some(pick) = &app.services.pick_folder - && key == "dir" - && ui.button("Browse…").clicked() - && let Some(p) = pick(path) - { - *path = p; - } - if let Some(pick) = &app.services.pick_save - && (cmd == "session.save_as" || cmd == "session.save_copy") - && ui.button("Browse…").clicked() - && let Some(p) = pick(cmd, path) - { - *path = p; - } - let file = soundcraft_engine::io::session_file(path); - let replaces = soundcraft_engine::io::replaces(&app.engine, cmd, &file); - if replaces { - ui.label(format!("“{}” already exists. Do you want to replace it?", file.file_name().unwrap_or_default().to_string_lossy())); - } - if buttons(ui, if replaces { "Replace" } else { "OK" }, enter && !replaces) { - let mut v = json!({}); - v[key.as_str()] = json!(path); - if replaces { - v["replace"] = json!(true); - } - action = Some((cmd.clone(), v)); + if let Some(c) = path_prompt_form(app, ui, cmd, path, key, enter) { + action = Some(c); } } Dialog::Number { cmd, key, value, suffix, .. } => { @@ -534,44 +619,11 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { } } Dialog::StripSilence { threshold, min_ms, pre_ms, post_ms } => { - let before = [*threshold, *min_ms, *pre_ms, *post_ms]; - ui.add(egui::Slider::new(threshold, -96.0..=0.0).text("Threshold dB")); - ui.add(egui::Slider::new(min_ms, 0.0..=4000.0).text("Min strip duration ms")); - ui.add(egui::Slider::new(pre_ms, 0.0..=500.0).text("Clip start pad ms")); - ui.add(egui::Slider::new(post_ms, 0.0..=2000.0).text("Clip end pad ms")); - let values = [*threshold, *min_ms, *pre_ms, *post_ms]; - // The Edit window is drawn before this window, so it draws the rectangles for new values in the next frame. - if values != before { - ui.ctx().request_repaint(); - } - if !strip_names.name.trim().is_empty() { - let names = format!("New clips are named {}, {} and so on.", strip_names.clip_name(0), strip_names.clip_name(1)); - ui.label(egui::RichText::new(names).small().color(Tokens::current().text_dim)); - } - ui.separator(); - ui.horizontal(|ui| { - let mut mode = None; - let mut rename = false; - if ui.button("Extract").clicked() { - mode = Some("extract"); - } - if ui.button("Rename…").clicked() { - rename = true; - } - if ui.button("Separate").clicked() { - mode = Some("separate"); - } - // Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked. - if buttons(ui, "Strip", enter) && mode.is_none() { - mode = Some("strip"); - } - // Enter on a focused Rename… also presses Strip, so Rename… goes first. - if rename { - rename_from = Some(values); - } else if let Some(mode) = mode { - action = Some(strip_silence_action(mode, values, &strip_names)); - } - }); + let mut values = [*threshold, *min_ms, *pre_ms, *post_ms]; + let (a, r) = strip_silence_form(ui, &mut values, &strip_names, enter); + [*threshold, *min_ms, *pre_ms, *post_ms] = values; + action = a.or(action.take()); + rename_from = r.or(rename_from); } Dialog::StripSilenceRename { names, .. } => { strip_name_fields(ui, names, STRIP_NAME_LABELS); @@ -621,12 +673,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { } } Dialog::Session { frame_rate, bit_depth } => { - egui::ComboBox::from_label("Timecode Rate").selected_text(frame_rate.as_str()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Timecode Rate").selected_text(frame_rate.as_str()).show_ui(ui, |ui| { for r in soundcraft_time::FrameRate::ALL { ui.selectable_value(frame_rate, r.label().to_string(), r.label()); } }); - egui::ComboBox::from_label("Bit Depth").selected_text(bit_depth.as_str()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Bit Depth").selected_text(bit_depth.as_str()).show_ui(ui, |ui| { for b in ["16", "24", "32f"] { ui.selectable_value(bit_depth, b.to_string(), b); } @@ -860,6 +912,21 @@ fn loop_length(s: &Session, text: &str, format: soundcraft_time::TimeFormat, sta mod tests { use super::*; + /// A name that is not valid Unicode is not opened under a lossy rendering (another file): the + /// status line names its bytes. + #[cfg(unix)] + #[test] + fn non_unicode_paths_are_reported_not_mangled() { + use std::os::unix::ffi::OsStrExt; + assert_eq!(unicode(std::path::Path::new("/a/café.wav")), Ok("/a/café.wav")); + let latin1 = std::path::Path::new(std::ffi::OsStr::from_bytes(b"/a/caf\xe9.scraft")); + assert_eq!(unicode(latin1), Err(NotUnicode(latin1.to_path_buf()))); + let mut app = SoundApp::new(Engine::default(), None, crate::Services::default()); + open_path(&mut app, latin1); + assert_eq!(app.ui.status, r#""/a/caf\xE9.scraft" is not valid Unicode"#); + assert!(app.engine.path.is_none() && app.dialogs.open.is_none()); + } + #[test] fn file_commands_get_path_prompts_with_sensible_names() { let e = soundcraft_engine::demo::demo_engine(); diff --git a/crates/ui-egui/src/dialogs/audiosuite.rs b/crates/ui-egui/src/dialogs/audiosuite.rs index fbc650e6..759565a8 100644 --- a/crates/ui-egui/src/dialogs/audiosuite.rs +++ b/crates/ui-egui/src/dialogs/audiosuite.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, Value, json}; /// The speed ramp's choices in the AudioSuite window: param id, label, default, and (value, name) pairs. pub(super) const SPEED_RAMP_CHOICES: [(&str, &str, f32, &[(f32, &str)]); 3] = [ diff --git a/crates/ui-egui/src/dialogs/files.rs b/crates/ui-egui/src/dialogs/files.rs index 4906f27a..4c8e4281 100644 --- a/crates/ui-egui/src/dialogs/files.rs +++ b/crates/ui-egui/src/dialogs/files.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Dialog, SoundApp, Value, json}; /// When `id` would close a session with unsaved changes, ask first; true when the question is /// open instead. A take in progress is stopped first, so it counts as a change. @@ -26,6 +26,51 @@ pub fn run_or_ask(app: &mut SoundApp, id: &str, params: Value) -> Result) -> std::fmt::Result { + write!(f, "{:?} is not valid Unicode", self.0) + } +} + +impl std::error::Error for NotUnicode {} + +/// `path` as the text the engine's commands take. Convert only where a command gets the path: +/// a lossy rendering would name another file. +pub fn unicode(path: &std::path::Path) -> Result<&str, NotUnicode> { + path.to_str().ok_or_else(|| NotUnicode(path.to_path_buf())) +} + +/// Opens a dropped, picked or command-line file by its extension: a session opens (asking to save +/// first), MIDI imports, and anything else imports as audio, decoded in the background so a long +/// file doesn't freeze the window (#597). A name that is not valid Unicode goes on the status line. +pub fn open_path(app: &mut SoundApp, path: &std::path::Path) { + let p = match unicode(path) { + Ok(p) => p, + Err(e) => { + log::warn!("{e}"); + app.ui.status = e.to_string(); + return; + } + }; + let lower = p.to_ascii_lowercase(); + let r = if lower.ends_with(".scraft") { + run_or_ask(app, "session.open", json!({"path": p})) + } else if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { + app.run("file.import_midi", json!({"path": p})) + } else { + let at = app.engine.session().edit.selection.start; + crate::import::start(app, json!({"path": p, "at": at})); + Ok(Value::Null) + }; + if let Err(e) = r { + log::warn!("{p}: {e}"); + } +} + /// What `SaveChanges` carries on with to open the session the browser read. pub(super) const OPEN_PENDING: &str = "ui.open_pending_session"; diff --git a/crates/ui-egui/src/dialogs/ops_windows.rs b/crates/ui-egui/src/dialogs/ops_windows.rs index ec0f3f7d..4d71d0c0 100644 --- a/crates/ui-egui/src/dialogs/ops_windows.rs +++ b/crates/ui-egui/src/dialogs/ops_windows.rs @@ -153,7 +153,7 @@ fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) { return; } egui::Window::new("Tempo Operations").open(&mut open).default_size(vec2(360.0, 200.0)).show(ctx, |ui| { - egui::ComboBox::from_label("Curve").selected_text(app.ops.tempo_curve.clone()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Curve").selected_text(app.ops.tempo_curve.clone()).show_ui(ui, |ui| { for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] { ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), c); } @@ -183,7 +183,7 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) { return; } egui::Window::new("Time Operations").open(&mut open).default_size(vec2(360.0, 200.0)).show(ctx, |ui| { - egui::ComboBox::from_label("Operation").selected_text(app.ops.time_op.clone()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Operation").selected_text(app.ops.time_op.clone()).show_ui(ui, |ui| { for c in ["insert", "cut", "change meter", "move song start"] { ui.selectable_value(&mut app.ops.time_op, c.to_string(), c); } @@ -193,7 +193,7 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64)).accessible_name("Meter numerator"); ui.label("/"); - let den = egui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| { + let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| { for d in [2u32, 4, 8, 16] { ui.selectable_value(&mut app.ops.meter_den, d, d.to_string()); } @@ -228,14 +228,14 @@ fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) { return; } egui::Window::new("MIDI Operations").open(&mut open).default_size(vec2(360.0, 220.0)).show(ctx, |ui| { - egui::ComboBox::from_label("Operation").selected_text(app.ops.midi_op.clone()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Operation").selected_text(app.ops.midi_op.clone()).show_ui(ui, |ui| { for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] { ui.selectable_value(&mut app.ops.midi_op, c.to_string(), c); } }); match app.ops.midi_op.as_str() { "quantize" => { - egui::ComboBox::from_label("Grid").selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Grid").selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| { for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] { ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g); } diff --git a/crates/ui-egui/src/dialogs/spot.rs b/crates/ui-egui/src/dialogs/spot.rs index cd927baa..88f361c2 100644 --- a/crates/ui-egui/src/dialogs/spot.rs +++ b/crates/ui-egui/src/dialogs/spot.rs @@ -155,7 +155,7 @@ fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples) pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) { egui::Grid::new("spot").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| { let scale = ui.label("Time Scale"); - let time_scale = egui::ComboBox::from_id_salt("spot_scale").selected_text(d.format.label()).show_ui(ui, |ui| { + let time_scale = craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(d.format.label()).show_ui(ui, |ui| { for f in TimeFormat::ALL { ui.selectable_value(&mut d.format, f, f.label()); } diff --git a/crates/ui-egui/src/dialogs/strip_silence.rs b/crates/ui-egui/src/dialogs/strip_silence.rs index a128436c..2d5b98e9 100644 --- a/crates/ui-egui/src/dialogs/strip_silence.rs +++ b/crates/ui-egui/src/dialogs/strip_silence.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Arc, ClipId, Dialog, SoundApp, StripNames, Tokens, TrackId, Value, json, vec2}; /// What Strip keeps on each track: the Strip Silence rectangles. pub type StripRects = Arc)>>; diff --git a/crates/ui-egui/src/edit_window.rs b/crates/ui-egui/src/edit_window.rs index eb4cfcf3..4934d2e9 100644 --- a/crates/ui-egui/src/edit_window.rs +++ b/crates/ui-egui/src/edit_window.rs @@ -42,7 +42,9 @@ use layout::COLUMN_TITLES_H; #[cfg(test)] use layout::lane_rect; pub use layout::{COLUMN_W, EditLayout, HEADER_W, LANE_H, RULER_H, edit_columns, header_width, rect, sample_at, track_height, x_of}; -use overlay::{overlay, playhead_colour}; +use overlay::overlay; +#[cfg(test)] +use overlay::playhead_colour; pub use rulers::ruler_height; use rulers::{column_titles, draw_rulers, views_button}; pub use scroll::zoom_toggle; diff --git a/crates/ui-egui/src/edit_window/automation.rs b/crates/ui-egui/src/edit_window/automation.rs index 61d2b3a5..d3127982 100644 --- a/crates/ui-egui/src/edit_window/automation.rs +++ b/crates/ui-egui/src/edit_window/automation.rs @@ -1,5 +1,5 @@ use super::layout::{sample_at, x_of}; -use super::*; +use super::{Align2, AutoParam, Color32, Pos2, Rect, Samples, Session, Shape, Stroke, Tokens, Track, TrackKind, pos2, regular}; pub(super) fn draw_automation(painter: &egui::Painter, s: &Session, track: &Track, p: &AutoParam, tl: Rect, lane: Rect) { let t = Tokens::current(); diff --git a/crates/ui-egui/src/edit_window/clips.rs b/crates/ui-egui/src/edit_window/clips.rs index 6445c95c..5887132d 100644 --- a/crates/ui-egui/src/edit_window/clips.rs +++ b/crates/ui-egui/src/edit_window/clips.rs @@ -1,7 +1,10 @@ use super::drag::fade_drag_preview; use super::input::{clip_gain_icon, near_fade_midpoint}; use super::layout::{sample_at, x_of}; -use super::*; +use super::{ + Align2, AutoParam, Clip, ClipContent, Color32, CornerRadius, Gesture, GridValue, NoteValue, Pos2, Range, Rect, Session, Shape, SoundApp, Stroke, + StrokeKind, TimeFormat, Tokens, Tool, Track, bold, clip_colors, format_position, pos2, regular, vec2, +}; /// The outline of the Strip Silence rectangles. pub fn strip_silence_stroke() -> Stroke { @@ -138,18 +141,39 @@ fn grid_veil(line: Color32, bg: Color32) -> Color32 { } } -/// `sorted`: whether `track.clips()` is sorted by start (worked out once per track and frame). -pub(super) fn draw_clip( - app: &SoundApp, - painter: &egui::Painter, - s: &Session, - track: &Track, - sorted: bool, - clip: &Clip, - tl: Rect, - lane: Rect, +/// What `draw_clip` draws into: the app, painter and session, and the track lane the clips sit on. +#[derive(Clone, Copy)] +pub(super) struct ClipLane<'a> { + pub(super) app: &'a SoundApp, + pub(super) painter: &'a egui::Painter, + pub(super) s: &'a Session, + pub(super) track: &'a Track, + /// Whether `track.clips()` is sorted by start (worked out once per track and frame). + pub(super) sorted: bool, + pub(super) tl: Rect, + pub(super) lane: Rect, +} + +/// Where and in what colours one clip is drawn, shared by the parts of `draw_clip`. +#[derive(Clone, Copy)] +struct ClipGeom<'a> { + r: Rect, + body_r: Rect, + vis: Rect, + x0: f32, + x1: f32, + name_h: f32, + body: Color32, + wave: Color32, + selected: bool, dim: bool, -) { + fade_in: soundcraft_model::Fade, + fade_out: soundcraft_model::Fade, + prev: Option<&'a Clip>, +} + +pub(super) fn draw_clip(cl: &ClipLane<'_>, clip: &Clip, dim: bool) { + let ClipLane { app, painter, s, track, tl, lane, .. } = *cl; let x0 = x_of(s, tl, clip.start); let x1 = x_of(s, tl, clip.end()).max(x0 + 1.0); let r = Rect::from_min_max(pos2(x0, lane.min.y + 1.0), pos2(x1, lane.max.y - 1.0)); @@ -186,6 +210,19 @@ pub(super) fn draw_clip( let vis = body_r.intersect(lane); // The waveform and fade curve share the same temporary envelope every frame. let (fade_in, fade_out) = clip_preview_fades(clip, app.gesture.as_ref().filter(|_| !dim)); + let prev = crossfade_partner(track, clip); + let g = ClipGeom { r, body_r, vis, x0, x1, name_h, body, wave, selected, dim, fade_in, fade_out, prev }; + draw_clip_content(cl, clip, &g); + draw_crossfade_tail(cl, &g); + draw_gain_line(cl, clip, &g); + draw_fades(cl, clip, &g); + draw_clip_overlays(cl, clip, &g); +} + +/// The clip body: waveform, MIDI notes or the offline notice. +fn draw_clip_content(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) { + let ClipLane { painter, s, track, tl, .. } = *cl; + let ClipGeom { body_r, vis, body, wave, selected, fade_in, fade_out, .. } = *g; match &clip.content { _ if track.view == "blocks" => {} ClipContent::Audio { source, .. } => { @@ -247,7 +284,12 @@ pub(super) fn draw_clip( } } } - let prev = crossfade_partner(track, clip); +} + +/// The waveform of the clip this one crossfades with, drawn over the overlap. +fn draw_crossfade_tail(cl: &ClipLane<'_>, g: &ClipGeom<'_>) { + let ClipLane { painter, s, track, tl, .. } = *cl; + let ClipGeom { body_r, vis, x0, x1, dim, prev, .. } = *g; if s.edit.flag("waveform.overlapped_crossfades") && track.view != "blocks" && let Some(prev) = prev @@ -262,6 +304,12 @@ pub(super) fn draw_clip( }; crate::waveform::draw(crate::waveform::Canvas { painter: &painter.with_clip_rect(xf), s, tl }, prev, audio, track.channels(), body_r, tail); } +} + +/// The clip gain line and its icon. +fn draw_gain_line(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) { + let ClipLane { painter, s, track, tl, lane, .. } = *cl; + let ClipGeom { body_r, x0, x1, dim, .. } = *g; // Clip gain line. let show_gain = s.edit.flag("view.clip.gain_line") && (!clip.gain_env.is_empty() || clip.gain_db.abs() > 0.01 || track.view == "clip_gain"); if show_gain && body_r.height() > 12.0 { @@ -286,6 +334,12 @@ pub(super) fn draw_clip( painter.rect_filled(Rect::from_center_size(pos2(icon.center().x, icon.center().y + 2.0), vec2(icon.width(), 3.0)), 1.0, col); painter.text(pos2(icon.max.x + 3.0, icon.center().y), Align2::LEFT_CENTER, format!("{:+.1} dB", clip.gain_db), regular(9.5), col); } +} + +/// The fade curves, their midpoint handles and the crossfade partner's fade-out. +fn draw_fades(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) { + let ClipLane { app, painter, s, track, tl, .. } = *cl; + let ClipGeom { body_r, vis, x0, x1, body, dim, fade_in, fade_out, prev, .. } = *g; let fade_col = Color32::from_rgba_unmultiplied(255, 255, 255, 90); for (side, fade) in [(true, fade_in), (false, fade_out)] { if fade.len <= 0 { @@ -309,6 +363,12 @@ pub(super) fn draw_clip( let pts = fade_curve_points(c.fade_out, false, a, b, body_r, painter.ctx().pixels_per_point()); painter.with_clip_rect(vis).add(Shape::line(pts, Stroke::new(1.2, fade_col))); } +} + +/// Optional clip overlays (View › Clip). +fn draw_clip_overlays(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) { + let ClipLane { painter, s, track, sorted, tl, lane, .. } = *cl; + let ClipGeom { r, name_h, .. } = *g; // Optional clip overlays (View › Clip). let ov = Color32::from_rgb(16, 16, 16); if s.edit.flag("view.clip.rating") && clip.rating > 0 && name_h > 0.0 { @@ -323,23 +383,7 @@ pub(super) fn draw_clip( )); painter.line_segment([pos2(x, r.min.y + name_h), pos2(x, r.max.y)], Stroke::new(1.0, Color32::from_rgba_unmultiplied(255, 255, 255, 90))); } - let time_text = if s.edit.flag("view.clip.time.current") { - Some(s.format_position(clip.start, s.edit.main_counter)) - } else if s.edit.flag("view.clip.time.original") || s.edit.flag("view.clip.time.user") { - clip.source().and_then(|src| s.source(src)).map(|src| { - format_position( - i64::try_from(src.time_reference).unwrap_or(0).saturating_add(clip.source_offset()).saturating_sub(s.timecode_start), - TimeFormat::Timecode, - s.sample_rate, - &s.tempo, - s.frame_rate, - 0, - 0, - ) - }) - } else { - None - }; + let time_text = clip_time_text(s, clip); if let Some(tt) = time_text && r.height() > 30.0 { @@ -369,7 +413,27 @@ pub(super) fn draw_clip( if clip.edit_locked || clip.time_locked { painter.text(pos2(r.max.x - 10.0, r.min.y + 7.0), Align2::CENTER_CENTER, "🔒", regular(9.0), Color32::WHITE); } - let _ = app; +} + +/// The clip's start (or original) time label for the overlays, when one is shown. +fn clip_time_text(s: &Session, clip: &Clip) -> Option { + if s.edit.flag("view.clip.time.current") { + Some(s.format_position(clip.start, s.edit.main_counter)) + } else if s.edit.flag("view.clip.time.original") || s.edit.flag("view.clip.time.user") { + clip.source().and_then(|src| s.source(src)).map(|src| { + format_position( + i64::try_from(src.time_reference).unwrap_or(0).saturating_add(clip.source_offset()).saturating_sub(s.timecode_start), + TimeFormat::Timecode, + s.sample_rate, + &s.tempo, + s.frame_rate, + 0, + 0, + ) + }) + } else { + None + } } /// The earlier clip of a crossfade pair: the one before `clip` in its playlist, overlapping its start. diff --git a/crates/ui-egui/src/edit_window/drag.rs b/crates/ui-egui/src/edit_window/drag.rs index 09c6b326..9ec78710 100644 --- a/crates/ui-egui/src/edit_window/drag.rs +++ b/crates/ui-egui/src/edit_window/drag.rs @@ -1,7 +1,9 @@ use super::automation::{auto_value, automation_id, lane_range, plugin_range}; use super::input::{new_midi_clip, snap}; use super::layout::{lane_rect, rect, sample_at}; -use super::*; +use super::{ + Arc, AutoParam, Clip, ClipId, Dialog, EditMode, Gesture, HashSet, Pos2, Range, Rect, Samples, Session, SoundApp, Spot, TrackId, json, ops, pos2, +}; /// The same bounded range drives the preview and the committed fade. pub(super) fn fade_drag_range(clip: &Clip, fade_in: bool, to: Samples) -> Option { diff --git a/crates/ui-egui/src/edit_window/header.rs b/crates/ui-egui/src/edit_window/header.rs index df0d1905..f8a002a2 100644 --- a/crates/ui-egui/src/edit_window/header.rs +++ b/crates/ui-egui/src/edit_window/header.rs @@ -1,12 +1,34 @@ use super::tracks::{click_track, folder_depth, height_targets, in_edit_window, track_context_menu, view_label, view_menu}; -use super::*; +use super::{ + Align2, AutoParam, Color32, Pos2, Rect, Sense, Shape, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, bold, groove, json, + level_pos, meter_pos, pos2, raised_key, regular, rgb, shade, vec2, +}; /// Draw one track header: resize edge, selection and context menu, folder/options control, automation-lane toggle, /// name and the remaining track controls. pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, selected: bool, head_bg: Color32) { - let t = Tokens::current(); let id = track.id; - // Drag the bottom edge to resize (snaps to the height presets). + // Click on header background selects the track. + let bg = ui.interact(head, ui.scope_id().with(("hdr", id.0)), Sense::click()); + if bg.clicked() { + click_track(app, id, ui.input(|i| i.modifiers), in_edit_window); + } + bg.context_menu(|ui| track_context_menu(app, ui, id)); + resize_edge(app, ui, track, head); + strip_buttons(app, ui, track, head); + name_plate(app, ui, track, head, selected); + playlist_menu(app, ui, track, head, head_bg); + toggle_keys(app, ui, track, head); + view_selector(app, ui, track, head); + voice_row(app, ui, track, head); + field_row(app, ui, track, head, head_bg); + let md = app.meters.get(&id).copied().unwrap_or_default(); + header_meter(ui, Rect::from_min_max(pos2(head.max.x - 8.0, head.min.y + 1.0), pos2(head.max.x, head.max.y - 1.5)), &md, track.channels() >= 2); +} + +/// Drag the bottom edge of the header to resize the track (snaps to the height presets). +fn resize_edge(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) { + let id = track.id; let edge = Rect::from_min_max(pos2(head.min.x, head.max.y - 4.0), pos2(head.max.x, head.max.y + 2.0)); let eresp = ui.interact(edge, ui.scope_id().with(("hedge", id.0)), Sense::drag()); if eresp.hovered() || eresp.dragged() { @@ -34,17 +56,15 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: ui.ctx().request_repaint(); } } +} + +/// The strip's round options/folder button and the automation-lane toggle. +fn strip_buttons(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) { + let id = track.id; let h = head.height(); - // Click on header background selects the track. - let bg = ui.interact(head, ui.scope_id().with(("hdr", id.0)), Sense::click()); - if bg.clicked() { - click_track(app, id, ui.input(|i| i.modifiers), in_edit_window); - } - bg.context_menu(|ui| track_context_menu(app, ui, id)); let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); let strip = rgb(track.color); let ink = shade(strip, -0.8); - // The strip's round button opens a folder, or any other track's options. let round = at(2.0, 2.0, 10.0, 10.0); let rresp = ui.interact(round, ui.scope_id().with(("options", id.0)), Sense::click()); ui.painter().circle_filled(round.center(), 5.0, shade(strip, if rresp.hovered() { 0.6 } else { 0.45 })); @@ -76,7 +96,13 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: let _ = app.run("track.view", json!({"track": id.0, "view": view})); } } - // Name, highlighted when the track is selected, and the playlist menu beside it. +} + +/// The track name, highlighted when selected, with click, rename and drag-to-reorder. +fn name_plate(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, selected: bool) { + let t = Tokens::current(); + let id = track.id; + let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); let indent = folder_depth(app.engine.session(), track) as f32 * 10.0; let name_r = at(16.0 + indent, 1.5, 97.0 - indent, 15.0); if selected { @@ -128,6 +154,13 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: let _ = app.run("track.move", json!({"track": id.0, "to": to})); } } +} + +/// The playlist menu button beside the name. +fn playlist_menu(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, head_bg: Color32) { + let t = Tokens::current(); + let id = track.id; + let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); let pl_r = at(114.0, 1.0, 11.0, 14.5); let presp = ui.interact(pl_r, ui.scope_id().with(("pl", id.0)), Sense::click()); ui.painter().rect_filled(pl_r, 1.5, shade(head_bg, if presp.hovered() { -0.2 } else { -0.35 })); @@ -149,6 +182,13 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: } } }); +} + +/// Record, input, solo and mute keys. +fn toggle_keys(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) { + let id = track.id; + let h = head.height(); + let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); let m = &track.mixer; if h >= 37.0 { let (records, mixes) = (track.kind.has_playlist(), track.kind != TrackKind::Master); @@ -165,6 +205,14 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: } } } +} + +/// The track view selector. +fn view_selector(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) { + let t = Tokens::current(); + let id = track.id; + let h = head.height(); + let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); if h >= 58.0 { let vresp = header_selector( ui, @@ -177,6 +225,15 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: ); egui::Popup::menu(&vresp).show(|ui| view_menu(app, ui, track)); } +} + +/// Freeze, voice and automation mode. +fn voice_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) { + let t = Tokens::current(); + let id = track.id; + let h = head.height(); + let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); + let m = &track.mixer; if h >= 76.0 { if matches!(track.kind, TrackKind::Audio | TrackKind::Instrument | TrackKind::Aux) { let r = at(17.0, 57.0, 13.0, 17.0); @@ -220,6 +277,14 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: } }); } +} + +/// Timebase key and the instrument or elastic field. +fn field_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, head_bg: Color32) { + let t = Tokens::current(); + let id = track.id; + let h = head.height(); + let at = |x: f32, y: f32, w: f32, h: f32| Rect::from_min_size(pos2(head.min.x + x, head.min.y + y), vec2(w, h)); if h >= 94.0 { if track.kind.has_playlist() { let r = at(17.0, 75.0, 13.0, 17.0); @@ -277,8 +342,6 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: } } } - let md = app.meters.get(&id).copied().unwrap_or_default(); - header_meter(ui, Rect::from_min_max(pos2(head.max.x - 8.0, head.min.y + 1.0), pos2(head.max.x, head.max.y - 1.5)), &md, track.channels() >= 2); } /// A small menu arrow, pointing down, or right for a closed folder. diff --git a/crates/ui-egui/src/edit_window/input.rs b/crates/ui-egui/src/edit_window/input.rs index 9875a1e6..88538b99 100644 --- a/crates/ui-egui/src/edit_window/input.rs +++ b/crates/ui-egui/src/edit_window/input.rs @@ -2,7 +2,10 @@ use super::automation::{automation_id, breakpoint_at, plugin_range, shown_automa use super::clips::{clip_name_height, fade_control_position}; use super::drag::{drag_snap, fade_curve_drag_value, fade_drag_range, spot_or_run}; use super::layout::{sample_at, x_of}; -use super::*; +use super::{ + Align2, AutoParam, Clip, ClipContent, ClipId, Color32, Dialog, EditMode, Gesture, GridValue, NoteValue, Pos2, Range, Rect, Samples, Sense, + Session, SoundApp, Spot, Stroke, StrokeKind, Tokens, Tool, Track, TrackId, Ui, json, ops, pos2, regular, vec2, +}; // ---- interaction ----------------------------------------------------------------------------- @@ -86,9 +89,40 @@ fn clip_gain_popup(ctx: &egui::Context, fader_bottom: Pos2, pos: f32) { p.text(pos2(panel.center().x, panel.min.y + 12.0), Align2::CENTER_CENTER, format!("{db:+.1}"), regular(10.5), t.counter_text); } -/// Handle one track lane: clip context menus, drag-and-drop sources, sampler drops, and the active tool's selection, -/// trim, fade, automation and clip editing. -pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, lane: Rect, tl: Rect) { +/// What a lane interaction knows before it hit-tests: the lane, the session and the press point. +struct LaneInput<'a> { + track: &'a Track, + lane: Rect, + tl: Rect, + s: &'a Session, + tool: Tool, + origin: Pos2, + at_origin: Samples, + auto_view: Option, +} + +/// What is under the pointer: a breakpoint, fade handles and the clip body. +struct LaneHits<'a> { + point_hit: Option<(AutoParam, Samples)>, + fade_handle: Option<(&'a Clip, bool)>, + curve_handle: Option<(&'a Clip, bool)>, + hit: Option, +} + +/// Everything the lane's gesture, click and cursor handling reads. +struct LaneCtx<'a> { + inp: LaneInput<'a>, + hits: LaneHits<'a>, + mods: egui::Modifiers, + p: Pos2, + at: Samples, + eff: Tool, + fade_corner: Option, + selector_press: bool, +} + +/// The lane's response, with its clip context menu and the drops it accepts. +fn lane_menu_and_drops(app: &mut SoundApp, ui: &mut Ui, track: &Track, lane: Rect, tl: Rect) -> egui::Response { let id = ui.scope_id().with(("lane", track.id.0)); let resp = ui.interact(lane, id, Sense::click_and_drag()); // The clip menu is attached before the early return below: once the menu is open the pointer @@ -121,16 +155,15 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l if track.kind == soundcraft_model::TrackKind::Instrument { crate::sampler_window::drop_target(app, ui.ctx(), lane, track.id); } - let s = app.engine.session_arc(); - let tool = s.edit.tool; - let mods = ui.input(|i| i.modifiers); - let Some(p) = resp.interact_pointer_pos().or_else(|| resp.hover_pos()) else { return }; - let at = sample_at(&s, tl, p.x).max(0); - let origin = if resp.drag_started() { ui.input(|i| i.pointer.press_origin()).unwrap_or(p) } else { p }; - let at_origin = sample_at(&s, tl, origin.x).max(0); - let auto_view = AutoParam::parse(&track.view); + resp +} + +/// Hit-test the press point against breakpoints, fade handles and clip bodies. +fn hit_test<'a>(inp: &LaneInput<'a>) -> LaneHits<'a> { + let (track, lane, tl, s, tool, origin, at_origin) = (inp.track, inp.lane, inp.tl, inp.s, inp.tool, inp.origin, inp.at_origin); + let auto_view = &inp.auto_view; let point_hit = if matches!(tool, Tool::Smart | Tool::Grabber | Tool::Pencil) { - shown_automation(track).and_then(|param| breakpoint_at(&s, tl, lane, track, ¶m, origin).map(|at| (param, at))) + shown_automation(track).and_then(|param| breakpoint_at(s, tl, lane, track, ¶m, origin).map(|at| (param, at))) } else { None }; @@ -143,34 +176,40 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l .iter() .rev() .filter(|c| body_hit.is_none_or(|front| front.id == c.id || front.start == c.end())) - .find_map(|c| fade_handle_at(&s, tl, lane, c, origin).map(|side| (c, side))) + .find_map(|c| fade_handle_at(s, tl, lane, c, origin).map(|side| (c, side))) } else { None }; let curve_handle = if tool == Tool::Smart && auto_view.is_none() && fade_handle.is_none() { - body_hit.and_then(|c| fade_curve_handle_at(&s, tl, lane, c, origin).map(|side| (c, side))) + body_hit.and_then(|c| fade_curve_handle_at(s, tl, lane, c, origin).map(|side| (c, side))) } else { None }; let hit = fade_handle.or(curve_handle).map(|(c, _)| c).or(body_hit).cloned(); - let upper = origin.y < lane.center().y; - let near_edge = |c: &Clip| -> Option { - let xs = x_of(&s, tl, c.start); - let xe = x_of(&s, tl, c.end()); - if (origin.x - xs).abs() < 6.0 { - Some(true) - } else if (origin.x - xe).abs() < 6.0 { - Some(false) - } else { - None - } - }; - // Effective tool under the Smart tool; on a breakpoint every tool that edits one grabs it. - let eff = match tool { - _ if point_hit.is_some() => Tool::Grabber, + LaneHits { point_hit, fade_handle, curve_handle, hit } +} + +/// Which edge of `c` the press point is within a few points of: `Some(true)` the start, `Some(false)` the end. +fn near_edge(inp: &LaneInput<'_>, c: &Clip) -> Option { + let xs = x_of(inp.s, inp.tl, c.start); + let xe = x_of(inp.s, inp.tl, c.end()); + if (inp.origin.x - xs).abs() < 6.0 { + Some(true) + } else if (inp.origin.x - xe).abs() < 6.0 { + Some(false) + } else { + None + } +} + +/// Effective tool under the Smart tool; on a breakpoint every tool that edits one grabs it. +fn effective_tool(inp: &LaneInput<'_>, hits: &LaneHits<'_>) -> Tool { + let upper = inp.origin.y < inp.lane.center().y; + match inp.tool { + _ if hits.point_hit.is_some() => Tool::Grabber, Tool::Smart => { - if let Some(c) = &hit { - if near_edge(c).is_some() { + if let Some(c) = &hits.hit { + if near_edge(inp, c).is_some() { Tool::Trim } else if upper { Tool::Selector @@ -182,23 +221,18 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l } } other => other, - }; - if resp.hovered() { - let icon = match eff { - Tool::Trim => egui::CursorIcon::ResizeHorizontal, - Tool::Grabber => egui::CursorIcon::Grab, - Tool::Selector => egui::CursorIcon::Text, - Tool::Zoom => egui::CursorIcon::ZoomIn, - Tool::Pencil => egui::CursorIcon::Crosshair, - _ => egui::CursorIcon::Default, - }; - ui.ctx().set_cursor_icon(icon); } - let fade_corner = if tool == Tool::Smart && point_hit.is_none() { +} + +/// The fade corner (`true` for the fade-in) the Smart tool is pressing, if any. +fn fade_corner_at(inp: &LaneInput<'_>, hits: &LaneHits<'_>) -> Option { + let (s, tl, lane, origin) = (inp.s, inp.tl, inp.lane, inp.origin); + let (tool, point_hit, fade_handle, hit) = (inp.tool, &hits.point_hit, hits.fade_handle, &hits.hit); + if tool == Tool::Smart && point_hit.is_none() { fade_handle.map(|(_, side)| side).or_else(|| { hit.as_ref().and_then(|c| { - let xs = x_of(&s, tl, c.start); - let xe = x_of(&s, tl, c.end()); + let xs = x_of(s, tl, c.start); + let xe = x_of(s, tl, c.end()); let top = origin.y < lane.min.y + lane.height() * 0.28; if !top { None @@ -213,25 +247,15 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l }) } else { None - }; - if fade_corner.is_some() && resp.hovered() { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeNwSe); } - if curve_handle.is_some() && resp.hovered() { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); - } - let gain_icon_at = |q: Pos2| { - let c = clip_at(track, sample_at(&s, tl, q.x).max(0)).filter(|_| auto_view.is_none())?; - clip_gain_icon(&s, tl, lane, c).filter(|r| r.contains(q)).map(|_| c.clone()) - }; - if resp.hovered() && gain_icon_at(p).is_some() { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); - } - let selector_press = eff == Tool::Selector && fade_corner.is_none() && curve_handle.is_none() && gain_icon_at(origin).is_none(); - if selector_press && resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) { - place_insertion(app, ui, &s, track.id, at, mods.shift); - } - let gain_drag = if resp.drag_started() { gain_icon_at(origin) } else { None }; +} + +/// Start the gesture a press begins: a breakpoint, clip gain, a fade or the tool's own. +fn start_gesture(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::Response, gain_drag: Option) { + let LaneCtx { inp, hits, mods, p, at, eff, fade_corner, .. } = c; + let (track, lane, s, origin, at_origin, auto_view) = (inp.track, inp.lane, inp.s, inp.origin, inp.at_origin, &inp.auto_view); + let (point_hit, curve_handle, hit) = (&hits.point_hit, hits.curve_handle, &hits.hit); + let (mods, p, at, eff, fade_corner) = (*mods, *p, *at, *eff, *fade_corner); if resp.drag_started() && let Some((param, at)) = &point_hit { @@ -252,7 +276,7 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l { let fade = if fade_in { c.fade_in } else { c.fade_out }; let anchor = (origin.y, fade.gain(0.5)); - let height = (lane.height() - 2.0 - clip_name_height(&s, lane)).max(1.0); + let height = (lane.height() - 2.0 - clip_name_height(s, lane)).max(1.0); app.gesture = Some(Gesture::FadeCurve { clip: c.id, fade_in, curvature: fade_curve_drag_value(fade, anchor, height, p.y), anchor, height }); ui.ctx().request_repaint(); } else if resp.drag_started() @@ -267,12 +291,12 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l ui.ctx().request_repaint(); } else if resp.drag_started() { app.gesture = match eff { - Tool::Selector | Tool::Smart => Some(Gesture::Select { track: track.id, anchor: snap(&s, at_origin), tracks: vec![track.id] }), + Tool::Selector | Tool::Smart => Some(Gesture::Select { track: track.id, anchor: snap(s, at_origin), tracks: vec![track.id] }), Tool::Grabber => hit.as_ref().map(|c| { let clips = if s.edit.selected_clips.contains(&c.id) { s.edit.selected_clips.clone() } else { vec![c.id] }; Gesture::MoveClips { clips, grab_at: at_origin, delta: 0, from_track: track.id, to_track: track.id } }), - Tool::Trim => hit.as_ref().map(|c| match near_edge(c) { + Tool::Trim => hit.as_ref().map(|c| match near_edge(inp, c) { Some(false) => Gesture::TrimEnd { clip: c.id, track: track.id, to: c.end() }, _ if at_origin - c.start < c.end() - at_origin => Gesture::TrimStart { clip: c.id, track: track.id, to: c.start }, _ => Gesture::TrimEnd { clip: c.id, track: track.id, to: c.end() }, @@ -285,6 +309,11 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l Tool::Zoom => Some(Gesture::ZoomBox { start: origin.x }), }; } +} + +/// While a clip-gain gesture is dragged, the fader follows the pointer. +fn drag_clip_gain(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::Response) { + let (track, s, mods, p) = (c.inp.track, c.inp.s, c.mods, c.p); if let Some(Gesture::ClipGain { clip, track: t, pos, anchor, fine, fader_bottom }) = &mut app.gesture && *t == track.id && resp.dragged() @@ -303,6 +332,13 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); clip_gain_popup(ui.ctx(), *fader_bottom, *pos); } +} + +/// Click handling for the lane: breakpoints, clip selection, spot dialogs, zoom and pencil points. +fn lane_click(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::Response) { + let (track, lane, s, auto_view) = (c.inp.track, c.inp.lane, c.inp.s, &c.inp.auto_view); + let (point_hit, curve_handle, hit) = (&c.hits.point_hit, c.hits.curve_handle, &c.hits.hit); + let (mods, p, at, eff, selector_press) = (c.mods, c.p, c.at, c.eff, c.selector_press); if resp.clicked() && let Some((param, at)) = &point_hit { @@ -319,14 +355,14 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l ids.push(c.id.0); let _ = app.run("edit.select", json!({"clips": ids})); if s.edit.edit_mode == EditMode::Spot { - app.dialogs.open = Spot::clips(&s, vec![c.id], None, 0).map(Dialog::Spot); + app.dialogs.open = Spot::clips(s, vec![c.id], None, 0).map(Dialog::Spot); } } } Tool::Trim if s.edit.edit_mode == EditMode::Spot && hit.is_some() => { if let Some(c) = &hit { let start = at - c.start < c.end() - at; - app.dialogs.open = Spot::trim(&s, c.id, start, if start { c.start } else { c.end() }).map(Dialog::Spot); + app.dialogs.open = Spot::trim(s, c.id, start, if start { c.start } else { c.end() }).map(Dialog::Spot); } } Tool::Zoom => { @@ -352,11 +388,11 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l Some(c) => { let _ = app.run("edit.select", json!({"clips": [c.id.0]})); } - None => new_midi_clip(app, &s, track.id, at, at), + None => new_midi_clip(app, s, track.id, at, at), } } } - _ if !selector_press => place_insertion(app, ui, &s, track.id, at, mods.shift), + _ if !selector_press => place_insertion(app, ui, s, track.id, at, mods.shift), _ => {} } } @@ -373,6 +409,58 @@ pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, l } } +/// Handle one track lane: clip context menus, drag-and-drop sources, sampler drops, and the active tool's selection, +/// trim, fade, automation and clip editing. +pub(super) fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, lane: Rect, tl: Rect) { + let resp = lane_menu_and_drops(app, ui, track, lane, tl); + let s = app.engine.session_arc(); + let tool = s.edit.tool; + let mods = ui.input(|i| i.modifiers); + let Some(p) = resp.interact_pointer_pos().or_else(|| resp.hover_pos()) else { return }; + let at = sample_at(&s, tl, p.x).max(0); + let origin = if resp.drag_started() { ui.input(|i| i.pointer.press_origin()).unwrap_or(p) } else { p }; + let at_origin = sample_at(&s, tl, origin.x).max(0); + let auto_view = AutoParam::parse(&track.view); + let inp = LaneInput { track, lane, tl, s: &s, tool, origin, at_origin, auto_view }; + let hits = hit_test(&inp); + let eff = effective_tool(&inp, &hits); + if resp.hovered() { + let icon = match eff { + Tool::Trim => egui::CursorIcon::ResizeHorizontal, + Tool::Grabber => egui::CursorIcon::Grab, + Tool::Selector => egui::CursorIcon::Text, + Tool::Zoom => egui::CursorIcon::ZoomIn, + Tool::Pencil => egui::CursorIcon::Crosshair, + _ => egui::CursorIcon::Default, + }; + ui.ctx().set_cursor_icon(icon); + } + let fade_corner = fade_corner_at(&inp, &hits); + let curve_handle = hits.curve_handle; + if fade_corner.is_some() && resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeNwSe); + } + if curve_handle.is_some() && resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); + } + let gain_icon_at = |q: Pos2| { + let c = clip_at(track, sample_at(&s, tl, q.x).max(0)).filter(|_| inp.auto_view.is_none())?; + clip_gain_icon(&s, tl, lane, c).filter(|r| r.contains(q)).map(|_| c.clone()) + }; + if resp.hovered() && gain_icon_at(p).is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); + } + let selector_press = eff == Tool::Selector && fade_corner.is_none() && curve_handle.is_none() && gain_icon_at(origin).is_none(); + if selector_press && resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) { + place_insertion(app, ui, &s, track.id, at, mods.shift); + } + let gain_drag = if resp.drag_started() { gain_icon_at(origin) } else { None }; + let cx = LaneCtx { inp, hits, mods, p, at, eff, fade_corner, selector_press }; + start_gesture(app, ui, &cx, &resp, gain_drag); + drag_clip_gain(app, ui, &cx, &resp); + lane_click(app, ui, &cx, &resp); +} + fn place_insertion(app: &mut SoundApp, ui: &Ui, s: &Session, track: TrackId, at: Samples, extend: bool) { let at = snap(s, at); let sel = s.edit.selection; diff --git a/crates/ui-egui/src/edit_window/layout.rs b/crates/ui-egui/src/edit_window/layout.rs index afc114bb..83452fcc 100644 --- a/crates/ui-egui/src/edit_window/layout.rs +++ b/crates/ui-egui/src/edit_window/layout.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Rect, Samples, Session, Track, pos2}; pub const HEADER_W: f32 = 136.0; diff --git a/crates/ui-egui/src/edit_window/overlay.rs b/crates/ui-egui/src/edit_window/overlay.rs index 494f7bdf..59c9ba06 100644 --- a/crates/ui-egui/src/edit_window/overlay.rs +++ b/crates/ui-egui/src/edit_window/overlay.rs @@ -2,7 +2,7 @@ use super::drag::drag_plan; use super::input::midi_clip_span; use super::layout::x_of; use super::scroll::{FollowFrame, follow_update}; -use super::*; +use super::{Color32, Gesture, Rect, Samples, Shape, SoundApp, Stroke, StrokeKind, Tokens, TrackId, Ui, json, ops, pos2, rgb}; /// The playback cursor is red only while recording; plain playback draws it in its own neutral /// grey, apart from the insertion colour of the edit cursor that stands beside it. diff --git a/crates/ui-egui/src/edit_window/rulers.rs b/crates/ui-egui/src/edit_window/rulers.rs index 250549cc..c665f907 100644 --- a/crates/ui-egui/src/edit_window/rulers.rs +++ b/crates/ui-egui/src/edit_window/rulers.rs @@ -1,6 +1,9 @@ use super::input::snap; use super::layout::{COLUMN_TITLES_H, COLUMNS, Column, HEADER_W, RULER_H, edit_columns, header_width, sample_at, x_of}; -use super::*; +use super::{ + Align2, Color32, GridValue, NoteValue, Range, Rect, Samples, Sense, Session, Shape, SoundApp, Stroke, TimeFormat, Tokens, Ui, bold, + format_position, json, pos2, regular, rgb, vec2, +}; // ---- rulers ---------------------------------------------------------------------------------- @@ -170,7 +173,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect, } else { soundcraft_time::FrameRate::Fps25 }; - timebase_ruler(ui, &painter, &s, tl, row, view, TimeFormat::Timecode, alt, i + 1 == rulers.len()); + timebase_ruler(&painter, &s, &RulerRow { tl, row, view, bottom: i + 1 == rulers.len() }, TimeFormat::Timecode, alt); } "markers" | "markers2" | "markers3" | "markers4" | "markers5" | "chords" => { let lane: u8 = match id.as_str() { @@ -225,7 +228,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect, } _ => { if let Some(f) = fmt { - timebase_ruler(ui, &painter, &s, tl, row, view, f, s.frame_rate, i + 1 == rulers.len()); + timebase_ruler(&painter, &s, &RulerRow { tl, row, view, bottom: i + 1 == rulers.len() }, f, s.frame_rate); // Clicking a timebase ruler locates. let resp = ui.interact(row, ui.scope_id().with(("ruler", id.as_str())), Sense::click_and_drag()); if (resp.clicked() || resp.dragged()) @@ -247,17 +250,17 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect, ui.painter().line_segment([pos2(area.min.x, area.max.y - 1.0), pos2(area.max.x, area.max.y - 1.0)], Stroke::new(1.0, t.border)); } -fn timebase_ruler( - _ui: &Ui, - painter: &egui::Painter, - s: &Session, +/// Where a timebase ruler sits: the timeline, its row and the visible range, and whether it is the bottom ruler. +#[derive(Clone, Copy)] +struct RulerRow { tl: Rect, row: Rect, view: Range, - f: TimeFormat, - rate: soundcraft_time::FrameRate, bottom: bool, -) { +} + +fn timebase_ruler(painter: &egui::Painter, s: &Session, place: &RulerRow, f: TimeFormat, rate: soundcraft_time::FrameRate) { + let RulerRow { tl, row, view, bottom } = *place; let t = Tokens::current(); let sr = s.sample_rate; let spp = s.edit.zoom.samples_per_px; diff --git a/crates/ui-egui/src/edit_window/scroll.rs b/crates/ui-egui/src/edit_window/scroll.rs index c54b34b7..0b78e262 100644 --- a/crates/ui-egui/src/edit_window/scroll.rs +++ b/crates/ui-egui/src/edit_window/scroll.rs @@ -1,7 +1,7 @@ use super::layout::track_height; use super::tracks::in_edit_window; use super::universe::content_end; -use super::*; +use super::{Rect, Samples, Sense, SoundApp, Tokens, TrackId, Ui, json, pos2, vec2}; /// Scroll Into View: track `id` to the top, as far as the scroll bar reaches. A track the Edit /// window doesn't show (hidden, or in a closed folder) leaves the view where it is. diff --git a/crates/ui-egui/src/edit_window/tests.rs b/crates/ui-egui/src/edit_window/tests.rs index 753df7b1..515e0b47 100644 --- a/crates/ui-egui/src/edit_window/tests.rs +++ b/crates/ui-egui/src/edit_window/tests.rs @@ -6,7 +6,7 @@ use egui_kittest::{Harness, kittest::Queryable}; /// they edit, not the short value text ("Read", "Waveform") painted inside them. #[test] fn track_header_selectors_have_accessible_names() { - let mut h = Harness::builder().with_context_setup(crate::fonts::install).build_ui(|ui| { + let mut h = Harness::builder().with_context_setup(|ctx| crate::fonts::install(ctx, true)).build_ui(|ui| { let view = Rect::from_min_size(Pos2::ZERO, vec2(60.0, 17.0)); super::header_selector(ui, view, egui::Id::unique("test-view"), "Waveform", Color32::WHITE, true, "Track view"); let mode = Rect::from_min_size(pos2(0.0, 20.0), vec2(60.0, 17.0)); @@ -591,128 +591,129 @@ fn waveform_geometry(h: &Harness, clip_rect: Rect) -> Vec> { .collect() } +/// Replace the clip's mono source with a stereo one whose right channel is half the left, and make the track stereo. +fn make_stereo(h: &mut Harness<'static, SoundApp>, tid: soundcraft_model::TrackId, source: soundcraft_model::SourceId) { + let audio = h.state().engine.session().pool.get(source).unwrap().clone(); + let left = audio.buffer.channels[0].clone(); + let right = left.iter().map(|sample| sample * 0.5).collect(); + let audio = + soundcraft_model::SourceAudio::new(soundcraft_audio_io::AudioBuffer { sample_rate: audio.buffer.sample_rate, channels: vec![left, right] }); + let s = h.state_mut().engine.session_mut(); + s.pool.insert(source, std::sync::Arc::new(audio)); + s.track_mut(tid).unwrap().format = soundcraft_model::ChannelFormat::Stereo; +} + +/// Where a fade drag presses and where it releases: the curve midpoint (bend) or the fade's end (length). +fn fade_drag_points( + session: &soundcraft_model::Session, + tl: Rect, + lane: Rect, + clip: soundcraft_model::ClipId, + fade_in: bool, + bend: bool, +) -> (Pos2, Pos2) { + let c = session.find_clip(clip).unwrap().1; + let (xs, xe) = (x_of(session, tl, c.start), x_of(session, tl, c.end())); + if bend { + let midpoint = fade_midpoint(session, tl, lane, c, fade_in).unwrap(); + (midpoint, midpoint - vec2(0.0, 16.0)) + } else { + (pos2(if fade_in { xs + 6.0 } else { xe - 6.0 }, lane.min.y + 4.0), pos2(xs + (xe - xs) * if fade_in { 0.7 } else { 0.3 }, lane.min.y + 4.0)) + } +} + +fn fade_waveform_case(channels: usize, fade_in: bool, bend: bool, mode: &str) { + let mut h = smart_demo(); + let tl = timeline(&h); + let (clip, lane) = clip_on_screen(&h, |xs, xe| xs > tl.min.x + 30.0 && xe < tl.max.x - 100.0 && xe - xs > 100.0); + let (tid, _) = h.state().engine.session().find_clip(clip.id).unwrap(); + let neighbour = h.state().engine.session().track(tid).unwrap().clips().iter().find(|c| c.id != clip.id && c.start >= clip.end()).unwrap().clone(); + let source = clip.source().unwrap(); + if channels == 2 { + make_stereo(&mut h, tid, source); + } + if mode == "power" { + h.state_mut().engine.execute("view.waveform_power", &json!({})).unwrap(); + } + h.state_mut().engine.execute("view.waveform_rectified", &json!({"value": mode == "rectified"})).unwrap(); + h.state_mut().engine.execute("view.waveform_outlines", &json!({"value": mode == "outlines"})).unwrap(); + h.state_mut().engine.execute("view.waveform_zoom", &json!({"value": 1.4})).unwrap(); + let c = h.state_mut().engine.session_mut().find_clip_mut(clip.id).unwrap(); + c.gain_db = -3.0; + c.gain_env = vec![(0, -3.0), (c.length, 3.0)]; + let target = soundcraft_model::Fade { + len: if bend { c.length * 2 / 3 } else { c.length / 4 }, + shape: soundcraft_model::FadeShape::SCurve, + curvature: 0.0, + }; + let other = soundcraft_model::Fade { len: c.length / 8, shape: soundcraft_model::FadeShape::Linear, curvature: 0.2 }; + (c.fade_in, c.fade_out) = if fade_in { (target, other) } else { (other, target) }; + h.step(); + let before = h.state().engine.session().clone(); + let undo_len = h.state().engine.undo_history().len(); + let audio = before.pool.get(source).unwrap().clone(); + let (xs, xe) = (x_of(&before, tl, clip.start), x_of(&before, tl, clip.end())); + let clip_rect = Rect::from_min_max(pos2(xs, lane.min.y), pos2(xe, lane.max.y)).intersect(tl); + let neighbour_rect = + Rect::from_min_max(pos2(x_of(&before, tl, neighbour.start), lane.min.y), pos2(x_of(&before, tl, neighbour.end()), lane.max.y)).intersect(tl); + let original = waveform_geometry(&h, clip_rect); + let neighbour_wave = waveform_geometry(&h, neighbour_rect); + assert_eq!(original.len(), channels); + let side = if fade_in { "in" } else { "out" }; + let operation = if bend { "bend" } else { "length" }; + let screenshot = channels == 1 && mode == "peak"; + if screenshot { + fade_shot(&mut h, &format!("waveform-{side}-{operation}-before")); + } + let (press, to) = fade_drag_points(&before, tl, lane, clip.id, fade_in, bend); + h.hover_at(press); + h.drag_at(press); + h.hover_at(to); + h.step(); + h.step(); + assert!(if bend { + matches!(h.state().gesture, Some(Gesture::FadeCurve { .. })) + } else { + matches!(h.state().gesture, Some(Gesture::Fade { .. })) + }); + let preview = waveform_geometry(&h, clip_rect); + assert_eq!(preview.len(), channels); + for channel in 0..channels { + assert_ne!( + preview[channel], original[channel], + "the waveform must respond while the button is held: {side}, {operation}, {mode}, channel={channel}" + ); + } + assert_eq!(waveform_geometry(&h, neighbour_rect), neighbour_wave); + assert_eq!(h.state().engine.session(), &before); + assert_eq!(h.state().engine.undo_history().len(), undo_len); + assert!(std::sync::Arc::ptr_eq(h.state().engine.session().pool.get(source).unwrap(), &audio), "preview must retain cached media and peaks"); + if screenshot { + fade_shot(&mut h, &format!("waveform-{side}-{operation}-preview")); + } + h.drop_at(to); + h.step(); + assert!(h.state().gesture.is_none()); + assert_eq!(waveform_geometry(&h, clip_rect), preview, "release must not cause a waveform jump"); + assert_eq!(waveform_geometry(&h, neighbour_rect), neighbour_wave); + assert_eq!(h.state().engine.undo_history().len(), undo_len + 1); + assert!(std::sync::Arc::ptr_eq(h.state().engine.session().pool.get(source).unwrap(), &audio)); + if screenshot { + fade_shot(&mut h, &format!("waveform-{side}-{operation}-released")); + } + assert!(h.state_mut().engine.undo()); + assert_eq!(h.state().engine.session(), &before); + h.step(); + assert_eq!(waveform_geometry(&h, clip_rect), original); +} + #[test] fn waveforms_follow_fade_drags_before_release_and_match_the_committed_waveform() { for channels in [1, 2] { for fade_in in [true, false] { for bend in [false, true] { for mode in ["peak", "power", "rectified", "outlines"] { - let mut h = smart_demo(); - let tl = timeline(&h); - let (clip, lane) = clip_on_screen(&h, |xs, xe| xs > tl.min.x + 30.0 && xe < tl.max.x - 100.0 && xe - xs > 100.0); - let (tid, _) = h.state().engine.session().find_clip(clip.id).unwrap(); - let neighbour = h - .state() - .engine - .session() - .track(tid) - .unwrap() - .clips() - .iter() - .find(|c| c.id != clip.id && c.start >= clip.end()) - .unwrap() - .clone(); - let source = clip.source().unwrap(); - if channels == 2 { - let audio = h.state().engine.session().pool.get(source).unwrap().clone(); - let left = audio.buffer.channels[0].clone(); - let right = left.iter().map(|sample| sample * 0.5).collect(); - let audio = soundcraft_model::SourceAudio::new(soundcraft_audio_io::AudioBuffer { - sample_rate: audio.buffer.sample_rate, - channels: vec![left, right], - }); - let s = h.state_mut().engine.session_mut(); - s.pool.insert(source, std::sync::Arc::new(audio)); - s.track_mut(tid).unwrap().format = soundcraft_model::ChannelFormat::Stereo; - } - if mode == "power" { - h.state_mut().engine.execute("view.waveform_power", &json!({})).unwrap(); - } - h.state_mut().engine.execute("view.waveform_rectified", &json!({"value": mode == "rectified"})).unwrap(); - h.state_mut().engine.execute("view.waveform_outlines", &json!({"value": mode == "outlines"})).unwrap(); - h.state_mut().engine.execute("view.waveform_zoom", &json!({"value": 1.4})).unwrap(); - let c = h.state_mut().engine.session_mut().find_clip_mut(clip.id).unwrap(); - c.gain_db = -3.0; - c.gain_env = vec![(0, -3.0), (c.length, 3.0)]; - let target = soundcraft_model::Fade { - len: if bend { c.length * 2 / 3 } else { c.length / 4 }, - shape: soundcraft_model::FadeShape::SCurve, - curvature: 0.0, - }; - let other = soundcraft_model::Fade { len: c.length / 8, shape: soundcraft_model::FadeShape::Linear, curvature: 0.2 }; - (c.fade_in, c.fade_out) = if fade_in { (target, other) } else { (other, target) }; - h.step(); - let before = h.state().engine.session().clone(); - let undo_len = h.state().engine.undo_history().len(); - let audio = before.pool.get(source).unwrap().clone(); - let (xs, xe) = (x_of(&before, tl, clip.start), x_of(&before, tl, clip.end())); - let clip_rect = Rect::from_min_max(pos2(xs, lane.min.y), pos2(xe, lane.max.y)).intersect(tl); - let neighbour_rect = Rect::from_min_max( - pos2(x_of(&before, tl, neighbour.start), lane.min.y), - pos2(x_of(&before, tl, neighbour.end()), lane.max.y), - ) - .intersect(tl); - let original = waveform_geometry(&h, clip_rect); - let neighbour_wave = waveform_geometry(&h, neighbour_rect); - assert_eq!(original.len(), channels); - let side = if fade_in { "in" } else { "out" }; - let operation = if bend { "bend" } else { "length" }; - let screenshot = channels == 1 && mode == "peak"; - if screenshot { - fade_shot(&mut h, &format!("waveform-{side}-{operation}-before")); - } - let (press, to) = if bend { - let c = before.find_clip(clip.id).unwrap().1; - let midpoint = fade_midpoint(&before, tl, lane, c, fade_in).unwrap(); - (midpoint, midpoint - vec2(0.0, 16.0)) - } else { - ( - pos2(if fade_in { xs + 6.0 } else { xe - 6.0 }, lane.min.y + 4.0), - pos2(xs + (xe - xs) * if fade_in { 0.7 } else { 0.3 }, lane.min.y + 4.0), - ) - }; - h.hover_at(press); - h.drag_at(press); - h.hover_at(to); - h.step(); - h.step(); - assert!(if bend { - matches!(h.state().gesture, Some(Gesture::FadeCurve { .. })) - } else { - matches!(h.state().gesture, Some(Gesture::Fade { .. })) - }); - let preview = waveform_geometry(&h, clip_rect); - assert_eq!(preview.len(), channels); - for channel in 0..channels { - assert_ne!( - preview[channel], original[channel], - "the waveform must respond while the button is held: {side}, {operation}, {mode}, channel={channel}" - ); - } - assert_eq!(waveform_geometry(&h, neighbour_rect), neighbour_wave); - assert_eq!(h.state().engine.session(), &before); - assert_eq!(h.state().engine.undo_history().len(), undo_len); - assert!( - std::sync::Arc::ptr_eq(h.state().engine.session().pool.get(source).unwrap(), &audio), - "preview must retain cached media and peaks" - ); - if screenshot { - fade_shot(&mut h, &format!("waveform-{side}-{operation}-preview")); - } - h.drop_at(to); - h.step(); - assert!(h.state().gesture.is_none()); - assert_eq!(waveform_geometry(&h, clip_rect), preview, "release must not cause a waveform jump"); - assert_eq!(waveform_geometry(&h, neighbour_rect), neighbour_wave); - assert_eq!(h.state().engine.undo_history().len(), undo_len + 1); - assert!(std::sync::Arc::ptr_eq(h.state().engine.session().pool.get(source).unwrap(), &audio)); - if screenshot { - fade_shot(&mut h, &format!("waveform-{side}-{operation}-released")); - } - assert!(h.state_mut().engine.undo()); - assert_eq!(h.state().engine.session(), &before); - h.step(); - assert_eq!(waveform_geometry(&h, clip_rect), original); + fade_waveform_case(channels, fade_in, bend, mode); } } } @@ -998,85 +999,100 @@ fn fade_midpoint_handles_remain_visible_and_can_be_grabbed_again() { } } +/// `session` with the clip's fade-in (or fade-out) curvature set. +fn with_curvature(session: &soundcraft_model::Session, clip: soundcraft_model::ClipId, fade_in: bool, curvature: f32) -> soundcraft_model::Session { + let mut expected = session.clone(); + let c = expected.find_clip_mut(clip).unwrap(); + if fade_in { + c.fade_in.curvature = curvature; + } else { + c.fade_out.curvature = curvature; + } + expected +} + +/// The screenshot name for a fade bend drag. +fn bend_shot_name(fade_in: bool, dy: f32, stage: &str) -> String { + let side = if fade_in { "in" } else { "out" }; + let direction = if dy < 0.0 { "up" } else { "down" }; + format!("fade-{side}-bend-{direction}-{stage}") +} + +fn fade_midpoint_bend_case(fade_in: bool, show_name: bool, dy: f32) { + let mut h = smart_demo(); + h.state_mut().engine.execute("view.clip_name", &json!({"value": show_name})).unwrap(); + h.step(); + let tl = timeline(&h); + let (clip, lane) = clip_on_screen(&h, |xs, xe| xs > tl.min.x + 30.0 && xe < tl.max.x - 100.0 && xe - xs > 100.0); + let c = h.state_mut().engine.session_mut().find_clip_mut(clip.id).unwrap(); + let target = soundcraft_model::Fade { len: c.length * 2 / 3, shape: soundcraft_model::FadeShape::SCurve, curvature: 0.0 }; + let other = soundcraft_model::Fade { len: c.length / 8, shape: soundcraft_model::FadeShape::Linear, curvature: -0.2 }; + (c.fade_in, c.fade_out) = if fade_in { (target, other) } else { (other, target) }; + h.step(); + let before = h.state().engine.session().clone(); + let clip_rect = Rect::from_min_max(pos2(x_of(&before, tl, clip.start), lane.min.y), pos2(x_of(&before, tl, clip.end()), lane.max.y)); + let original = fade_curves(&h, clip_rect); + let (edited, opposite) = if fade_in { (0, 1) } else { (1, 0) }; + let middle = original[edited].0.points.len() / 2; + let midpoint = original[edited].0.points[middle]; + let undo_len = h.state().engine.undo_history().len(); + h.hover_at(midpoint); + h.step(); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeVertical); + click(&mut h, midpoint); + assert_eq!(h.state().engine.session(), &before, "clicking the curve control should not change the selection"); + h.drag_at(midpoint); + let to = midpoint + vec2(0.0, dy); + h.hover_at(to); + h.step(); + h.step(); // Paint the frame requested when the drag gesture starts. + let curvature = match h.state().gesture { + Some(Gesture::FadeCurve { clip: id, fade_in: side, curvature, .. }) if id == clip.id && side == fade_in => curvature, + _ => panic!("the midpoint must start a curve gesture"), + }; + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeVertical); + assert!(if dy < 0.0 { curvature > 0.0 } else { curvature < 0.0 }); + let preview = fade_curves(&h, clip_rect); + assert_eq!(preview.len(), 2); + assert_eq!(preview[opposite], original[opposite]); + assert_eq!(preview[edited].0.points.first(), original[edited].0.points.first()); + assert_eq!(preview[edited].0.points.last(), original[edited].0.points.last()); + assert_eq!(preview[edited].0.points[middle].x, midpoint.x); + assert!( + (preview[edited].0.points[middle].y - (midpoint.y + dy)).abs() < 0.001, + "side={fade_in}, names={show_name}, dy={dy}, midpoint={midpoint:?}, drawn={:?}, gesture={:?}", + preview[edited].0.points[middle], + h.state().gesture + ); + assert_eq!(h.state().engine.session(), &before); + if show_name { + fade_shot(&mut h, &bend_shot_name(fade_in, dy, "preview")); + } + h.drop_at(to); + h.step(); + let expected = with_curvature(&before, clip.id, fade_in, curvature); + assert_eq!(h.state().engine.session(), &expected); + assert_eq!(fade_curves(&h, clip_rect), preview, "the released envelope must match the preview"); + let rel = if fade_in { target.len / 2 } else { clip.length - target.len / 2 }; + let previous_gain = before.find_clip(clip.id).unwrap().1.gain_at(rel); + let new_gain = expected.find_clip(clip.id).unwrap().1.gain_at(rel); + assert!(if dy < 0.0 { new_gain > previous_gain } else { new_gain < previous_gain }); + assert_eq!(h.state().engine.undo_history().len(), undo_len + 1); + if show_name { + fade_shot(&mut h, &bend_shot_name(fade_in, dy, "released")); + } + assert!(h.state_mut().engine.undo()); + assert_eq!(h.state().engine.session(), &before); + assert!(h.state_mut().engine.redo()); + assert_eq!(h.state().engine.session(), &expected); +} + #[test] fn fade_midpoints_drag_vertically_without_moving_the_endpoints() { for fade_in in [true, false] { for show_name in [true, false] { for dy in [-16.0, 16.0] { - let mut h = smart_demo(); - h.state_mut().engine.execute("view.clip_name", &json!({"value": show_name})).unwrap(); - h.step(); - let tl = timeline(&h); - let (clip, lane) = clip_on_screen(&h, |xs, xe| xs > tl.min.x + 30.0 && xe < tl.max.x - 100.0 && xe - xs > 100.0); - let c = h.state_mut().engine.session_mut().find_clip_mut(clip.id).unwrap(); - let target = soundcraft_model::Fade { len: c.length * 2 / 3, shape: soundcraft_model::FadeShape::SCurve, curvature: 0.0 }; - let other = soundcraft_model::Fade { len: c.length / 8, shape: soundcraft_model::FadeShape::Linear, curvature: -0.2 }; - (c.fade_in, c.fade_out) = if fade_in { (target, other) } else { (other, target) }; - h.step(); - let before = h.state().engine.session().clone(); - let clip_rect = Rect::from_min_max(pos2(x_of(&before, tl, clip.start), lane.min.y), pos2(x_of(&before, tl, clip.end()), lane.max.y)); - let original = fade_curves(&h, clip_rect); - let (edited, opposite) = if fade_in { (0, 1) } else { (1, 0) }; - let middle = original[edited].0.points.len() / 2; - let midpoint = original[edited].0.points[middle]; - let undo_len = h.state().engine.undo_history().len(); - h.hover_at(midpoint); - h.step(); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeVertical); - click(&mut h, midpoint); - assert_eq!(h.state().engine.session(), &before, "clicking the curve control should not change the selection"); - h.drag_at(midpoint); - let to = midpoint + vec2(0.0, dy); - h.hover_at(to); - h.step(); - h.step(); // Paint the frame requested when the drag gesture starts. - let curvature = match h.state().gesture { - Some(Gesture::FadeCurve { clip: id, fade_in: side, curvature, .. }) if id == clip.id && side == fade_in => curvature, - _ => panic!("the midpoint must start a curve gesture"), - }; - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeVertical); - assert!(if dy < 0.0 { curvature > 0.0 } else { curvature < 0.0 }); - let preview = fade_curves(&h, clip_rect); - assert_eq!(preview.len(), 2); - assert_eq!(preview[opposite], original[opposite]); - assert_eq!(preview[edited].0.points.first(), original[edited].0.points.first()); - assert_eq!(preview[edited].0.points.last(), original[edited].0.points.last()); - assert_eq!(preview[edited].0.points[middle].x, midpoint.x); - assert!( - (preview[edited].0.points[middle].y - (midpoint.y + dy)).abs() < 0.001, - "side={fade_in}, names={show_name}, dy={dy}, midpoint={midpoint:?}, drawn={:?}, gesture={:?}", - preview[edited].0.points[middle], - h.state().gesture - ); - assert_eq!(h.state().engine.session(), &before); - let side = if fade_in { "in" } else { "out" }; - let direction = if dy < 0.0 { "up" } else { "down" }; - if show_name { - fade_shot(&mut h, &format!("fade-{side}-bend-{direction}-preview")); - } - h.drop_at(to); - h.step(); - let mut expected = before.clone(); - let c = expected.find_clip_mut(clip.id).unwrap(); - if fade_in { - c.fade_in.curvature = curvature; - } else { - c.fade_out.curvature = curvature; - } - assert_eq!(h.state().engine.session(), &expected); - assert_eq!(fade_curves(&h, clip_rect), preview, "the released envelope must match the preview"); - let rel = if fade_in { target.len / 2 } else { clip.length - target.len / 2 }; - let previous_gain = before.find_clip(clip.id).unwrap().1.gain_at(rel); - let new_gain = expected.find_clip(clip.id).unwrap().1.gain_at(rel); - assert!(if dy < 0.0 { new_gain > previous_gain } else { new_gain < previous_gain }); - assert_eq!(h.state().engine.undo_history().len(), undo_len + 1); - if show_name { - fade_shot(&mut h, &format!("fade-{side}-bend-{direction}-released")); - } - assert!(h.state_mut().engine.undo()); - assert_eq!(h.state().engine.session(), &before); - assert!(h.state_mut().engine.redo()); - assert_eq!(h.state().engine.session(), &expected); + fade_midpoint_bend_case(fade_in, show_name, dy); } } } diff --git a/crates/ui-egui/src/edit_window/tracks.rs b/crates/ui-egui/src/edit_window/tracks.rs index 8eb6c593..8da99821 100644 --- a/crates/ui-egui/src/edit_window/tracks.rs +++ b/crates/ui-egui/src/edit_window/tracks.rs @@ -1,9 +1,12 @@ use super::automation::draw_automation; -use super::clips::{draw_clip, draw_live_take, draw_strip_silence, grid_lines}; +use super::clips::{ClipLane, draw_clip, draw_live_take, draw_strip_silence, grid_lines}; use super::header::{header_column, track_header}; use super::input::lane_interaction; use super::layout::{Column, HEADER_W, LANE_H, STRIP_W, lane_rect, sample_at, x_of}; -use super::*; +use super::{ + Align2, AutoParam, Range, Rect, Sense, Session, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, json, ops, pos2, regular, + rgb, vec2, +}; pub(super) fn in_edit_window(s: &Session, t: &Track) -> bool { ops::shown(s, t) @@ -90,7 +93,7 @@ pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect, if !clip.range().overlaps(&view) { continue; } - draw_clip(app, &painter, &s, track, sorted, clip, tl, lane, auto_view.is_some()); + draw_clip(&ClipLane { app, painter: &painter, s: &s, track, sorted, tl, lane }, clip, auto_view.is_some()); } draw_live_take(app, &painter, &s, track, tl, lane); crate::video_track::draw_lane(app, &painter, &s, track, tl, lane); @@ -140,7 +143,7 @@ fn playlist_lanes(app: &mut SoundApp, ui: &mut Ui, track: &Track, row: Rect, mai let sorted = track.clips().is_sorted_by_key(|c| c.start); let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x)); for c in pl.clips.iter().filter(|c| c.range().overlaps(&view)) { - draw_clip(app, &painter, &s, track, sorted, c, tl, lane, false); + draw_clip(&ClipLane { app, painter: &painter, s: &s, track, sorted, tl, lane }, c, false); } let resp = ui.interact(lane, ui.scope_id().with(("pl_lane", track.id.0, i)), Sense::click()); if resp.clicked() diff --git a/crates/ui-egui/src/edit_window/universe.rs b/crates/ui-egui/src/edit_window/universe.rs index f8706efb..302a58c9 100644 --- a/crates/ui-egui/src/edit_window/universe.rs +++ b/crates/ui-egui/src/edit_window/universe.rs @@ -1,4 +1,5 @@ -use super::*; +use super::overlay::playhead_colour; +use super::{Color32, Rect, Samples, Sense, Session, SoundApp, Stroke, StrokeKind, Tokens, Track, Ui, json, pos2, rgb, vec2}; /// The Universe's clip blocks for one document revision and area: each track's clips merged into /// runs of one colour. A drum edit holds tens of thousands of clips a pixel or less wide here; diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 3f9ce63a..514c10a1 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -80,8 +80,8 @@ fn load_from_fontconfig(pattern: &str, lang: Option<&str>) -> Option { } #[cfg(not(target_arch = "wasm32"))] -fn load(cands: &[(&str, u32)], pattern: &str, lang: Option<&str>) -> Option { - if std::env::var_os("SOUNDCRAFT_NO_SYSTEM_FONTS").is_some() { +fn load(cands: &[(&str, u32)], pattern: &str, lang: Option<&str>, system_fonts: bool) -> Option { + if !system_fonts { return None; } #[cfg(any(target_os = "linux", target_os = "freebsd"))] @@ -104,28 +104,29 @@ fn load(cands: &[(&str, u32)], pattern: &str, lang: Option<&str>) -> Option) -> Option { +fn load(_: &[(&str, u32)], _: &str, _: Option<&str>, _: bool) -> Option { None } -pub fn definitions() -> FontDefinitions { +/// The font set: the bundled faces, plus the system ones when `system_fonts` is true. +pub fn definitions(system_fonts: bool) -> FontDefinitions { let mut fonts = FontDefinitions::default(); let base: Vec = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); let mut bold_family = base.clone(); - if let Some(reg) = load(REGULAR, "sans-serif", None) { + if let Some(reg) = load(REGULAR, "sans-serif", None, system_fonts) { fonts.font_data.insert("system-regular".into(), Arc::new(reg)); if let Some(f) = fonts.families.get_mut(&FontFamily::Proportional) { f.insert(0, "system-regular".into()); } } - if let Some(b) = load(BOLD, "sans-serif:style=Bold", None) { + if let Some(b) = load(BOLD, "sans-serif:style=Bold", None, system_fonts) { fonts.font_data.insert("system-bold".into(), Arc::new(b)); bold_family.insert(0, "system-bold".into()); } else if fonts.font_data.contains_key("system-regular") { bold_family.insert(0, "system-regular".into()); } fonts.families.insert(FontFamily::Name("bold".into()), bold_family); - if let Some(h) = load(HANGUL, "sans-serif:lang=ko", Some("ko")) { + if let Some(h) = load(HANGUL, "sans-serif:lang=ko", Some("ko"), system_fonts) { fonts.font_data.insert("system-hangul".into(), Arc::new(h)); for family in fonts.families.values_mut() { family.push("system-hangul".into()); @@ -134,8 +135,8 @@ pub fn definitions() -> FontDefinitions { fonts } -pub fn install(ctx: &egui::Context) { - ctx.set_fonts(definitions()); +pub fn install(ctx: &egui::Context, system_fonts: bool) { + ctx.set_fonts(definitions(system_fonts)); } #[cfg(test)] @@ -177,7 +178,7 @@ mod tests { /// Korean names draw in every family, not as boxes; skipped when the system has no Korean font. #[test] fn every_family_draws_hangul_with_a_system_korean_font() { - let defs = definitions(); + let defs = definitions(true); if !defs.font_data.contains_key("system-hangul") { eprintln!("skipping: no Korean system font"); return; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 368c10bf..a84be7e4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -369,6 +369,8 @@ pub struct SoundApp { last_rev: u64, fonts_ready: bool, fonts_installed: bool, + /// Whether the system fonts are loaded next to the bundled ones; set before the first frame. + system_fonts: bool, /// The palette last applied to the context (light?), so visuals are set only on a change. theme_applied: Option, /// Last panel host context, used to cancel renderer-owned gestures on explicit replacement. diff --git a/crates/ui-egui/src/mix_window.rs b/crates/ui-egui/src/mix_window.rs index 5bf55078..f089499b 100644 --- a/crates/ui-egui/src/mix_window.rs +++ b/crates/ui-egui/src/mix_window.rs @@ -151,6 +151,30 @@ fn section_label(ui: &Ui, r: Rect, text: &str, narrow: bool) { /// Draw one mixer channel strip: preamp, instrument, object, insert and send sections, EQ curve, routing, fader and /// meters, with its interactions. +/// The height of the strip's footer: volume readout and name plate. +const STRIP_FOOT_H: f32 = 64.0; + +/// One mixer strip's geometry and settings, shared by its sections. +struct StripCtx<'a> { + track: &'a Track, + id: TrackId, + r: Rect, + w: f32, + x0: f32, + inner_w: f32, + narrow: bool, + selected: bool, + views: Vec, + all: bool, +} + +impl StripCtx<'_> { + /// Whether the mixer shows the section named `view`. + fn shows(&self, view: &str) -> bool { + self.all || self.views.iter().any(|x| x == view) + } +} + fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapshot>, scroll_here: bool) { let t = Tokens::current(); let session = app.engine.session_arc(); @@ -173,12 +197,30 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh let inner_w = w - 8.0; let x0 = r.min.x + 4.0; let views = app.ui.mix_views.clone(); - let has = |v: &str| views.iter().any(|x| x == v); - let all = has("all"); + let all = views.iter().any(|x| x == "all"); + let cx = StripCtx { track, id, r, w, x0, inner_w, narrow, selected, views, all }; // Preamp, instrument and object rows keep their height on every strip so sections line up; // their controls only appear on tracks with an input. + y = preamp_section(app, ui, &cx, y); + y = instrument_section(app, ui, &cx, y); + y = object_section(app, ui, &cx, y); + y = slot_sections(app, ui, &cx, y); + y = eq_section(ui, &cx, y); + y = comments_section(app, ui, &cx, y); + y = io_section(app, ui, &cx, y); + y = group_selector(app, ui, &cx, y); + y = pan_section(app, ui, &cx, y); + y = toggle_rows(app, ui, &cx, y); + fader_and_meter(app, ui, &cx, y, snap); + name_and_readout(app, ui, &cx); +} + +/// Input gain stage ahead of the inserts (the track's trim). +fn preamp_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, narrow, x0, inner_w, .. } = *cx; + let t = Tokens::current(); let has_input = matches!(track.kind, TrackKind::Audio | TrackKind::Instrument | TrackKind::Midi); - if all || has("mic_preamps") { + if cx.shows("mic_preamps") { // Input gain stage ahead of the inserts (the track's trim). let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 34.0)); inset(ui.painter(), sec, t.strip_section); @@ -199,7 +241,14 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y = sec.max.y + 4.0; } - if all || has("instruments") { + y +} + +/// The instrument slot. +fn instrument_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, narrow, x0, inner_w, .. } = *cx; + let t = Tokens::current(); + if cx.shows("instruments") { let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 34.0)); inset(ui.painter(), sec, t.strip_section); section_label(ui, sec, "INSTRUMENT", narrow); @@ -215,7 +264,14 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y = sec.max.y + 4.0; } - if all || has("object") { + y +} + +/// The object/bed switch. +fn object_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, x0, inner_w, .. } = *cx; + let has_input = matches!(track.kind, TrackKind::Audio | TrackKind::Instrument | TrackKind::Midi); + if cx.shows("object") { let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 20.0)); if has_input { let on = app.engine.session().edit.flag(&format!("object.{}", id.0)); @@ -227,13 +283,20 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y = sec.max.y + 4.0; } + y +} + +/// The insert and send sections. +fn slot_sections(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, narrow, x0, inner_w, .. } = *cx; + let t = Tokens::current(); for (key, title, off, is_send) in [ ("inserts_ae", "INSERTS A-E", 0usize, false), ("inserts_fj", "INSERTS F-J", 5, false), ("sends_ae", "SENDS A-E", 0, true), ("sends_fj", "SENDS F-J", 5, true), ] { - if !(all || has(key)) { + if !cx.shows(key) { continue; } let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 16.0 + 5.0 * 17.0)); @@ -249,7 +312,14 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y = sec.max.y + 4.0; } - if all || has("eq_curve") { + y +} + +/// The EQ curve. +fn eq_section(ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, x0, inner_w, .. } = *cx; + let t = Tokens::current(); + if cx.shows("eq_curve") { let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 40.0)); ui.painter().rect_filled(sec, 2.0, Color32::from_rgb(14, 18, 22)); let eq = track.mixer.inserts.iter().flatten().find(|i| i.plugin == "eq_7band" || i.plugin == "eq_1band"); @@ -278,7 +348,13 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y = sec.max.y + 4.0; } - if all || has("comments") { + y +} + +/// The comments field. +fn comments_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, narrow, x0, inner_w, .. } = *cx; + if cx.shows("comments") { let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 44.0)); let mut c = track.comments.clone(); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(sec)); @@ -292,7 +368,14 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y = sec.max.y + 4.0; } - if all || has("io") { + y +} + +/// Input, output and automation mode selectors. +fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, narrow, x0, inner_w, .. } = *cx; + let t = Tokens::current(); + if cx.shows("io") { let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 16.0 + 2.0 * 18.0 + 30.0)); inset(ui.painter(), sec, t.strip_section); section_label(ui, sec, "I / O", narrow); @@ -357,6 +440,13 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh }); y = sec.max.y + 4.0; } + y +} + +/// The group selector. +fn group_selector(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, narrow, x0, inner_w, .. } = *cx; + let t = Tokens::current(); // Group selector. let no_group = if narrow { "nogrp" } else { "no group" }; let gname = app.engine.session().groups.iter().find(|g| g.members.contains(&id)).map_or(no_group.to_string(), |g| g.name.clone()); @@ -371,6 +461,13 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh SelectorLabels { name: &format!("Group for {}", track.name), value: &gname, tooltip: "Group" }, ); y += 22.0; + y +} + +/// Pan: a surround panner when the output is multichannel, else the stereo knobs. +fn pan_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, x0, inner_w, .. } = *cx; + let t = Tokens::current(); // Pan: a surround panner when the output is multichannel, else the stereo knobs. let out_fmt = output_format(app, track); let surround_out = @@ -429,6 +526,13 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } y += 54.0; } + y +} + +/// Rec / Input / Solo / Mute. +fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 { + let StripCtx { track, id, x0, inner_w, .. } = *cx; + let t = Tokens::current(); // Rec / Input / Solo / Mute. let bw = (inner_w - 6.0) / 2.0; let mut row = ui.new_child( @@ -461,9 +565,15 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh } } y += 26.0; + y +} + +/// The fader and its meter. +fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32, snap: Option<&MeterSnapshot>) { + let StripCtx { track, id, narrow, x0, inner_w, r, .. } = *cx; + let t = Tokens::current(); // Fader + meter. - let bottom_h = 64.0; - let fh = (r.max.y - bottom_h - y).max(120.0); + let fh = (r.max.y - STRIP_FOOT_H - y).max(120.0); let wide_meter = (if track.kind == TrackKind::Master { app.engine.session().main_format() } else { track.format }).channels() > 2; let fr = Rect::from_min_size(pos2(x0, y), vec2(inner_w * if wide_meter { 0.45 } else { 0.6 }, fh)); if let Some(db) = fader(ui, fr, track.mixer.volume_db, ui.scope_id().with(("fader", id.0)), &format!("{} level", track.name)) { @@ -495,8 +605,14 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh if md.gr > 0.1 { ui.painter().text(pos2(mr.center().x, mr.min.y - 3.0), Align2::CENTER_BOTTOM, format!("-{:.0}", md.gr), regular(8.0), t.meter_yellow); } +} + +/// Volume readout, kind label and name plate. +fn name_and_readout(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>) { + let StripCtx { track, id, x0, inner_w, r, w, selected, .. } = *cx; + let t = Tokens::current(); // Volume readout and name. - let vr = Rect::from_min_size(pos2(x0 + 4.0, r.max.y - bottom_h + 4.0), vec2(inner_w - 8.0, 15.0)); + let vr = Rect::from_min_size(pos2(x0 + 4.0, r.max.y - STRIP_FOOT_H + 4.0), vec2(inner_w - 8.0, 15.0)); inset(ui.painter(), vr, t.counter_bg); let (_, entered) = editable_readout( ui, diff --git a/crates/ui-egui/src/mix_window/plugin_menu.rs b/crates/ui-egui/src/mix_window/plugin_menu.rs index 0680f6eb..ea077887 100644 --- a/crates/ui-egui/src/mix_window/plugin_menu.rs +++ b/crates/ui-egui/src/mix_window/plugin_menu.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Color32, Rect, SoundApp, TrackId, Ui, json, pos2, vec2}; /// An insert's menu: a search field that takes typing at once, then (until something is typed) /// Bypass and removal and the plugins by category and format. @@ -197,7 +197,24 @@ impl MenuSearch { /// `n` matches in a scrolling list, each drawn by `row` (told whether it is highlighted); /// returns the one clicked, or the highlighted one on Enter. - pub(super) fn rows(&self, ui: &mut Ui, n: usize, max_height: f32, mut row: impl FnMut(&mut Ui, usize, bool) -> bool) -> Option { + pub(super) fn rows(&self, ui: &mut Ui, n: usize, max_height: f32, row: impl FnMut(&mut Ui, usize, bool) -> bool) -> Option { + let row_h = ui.spacing().interact_size.y; + egui::ScrollArea::vertical() + .id_salt(self.id.with("rows")) + .max_height(max_height) + .show_rows(ui, row_h, n, |ui, range| self.list_rows(ui, range, n, row)) + .inner + } + + /// The rows of `range` out of `n` matches, drawn into a list that scrolls and virtualises + /// itself (a shared dropdown menu's list); `rows` is the same list in a scroll area of its own. + pub(super) fn list_rows( + &self, + ui: &mut Ui, + range: std::ops::Range, + n: usize, + mut row: impl FnMut(&mut Ui, usize, bool) -> bool, + ) -> Option { let [up, down, enter] = self.keys; let typing = self.typing(); let highlight = match (up, down) { @@ -210,17 +227,15 @@ impl MenuSearch { let mut picked = (typing && enter && n > 0).then_some(highlight); let row_h = ui.spacing().interact_size.y; let step = row_h + ui.spacing().item_spacing.y; - egui::ScrollArea::vertical().id_salt(self.id.with("rows")).max_height(max_height).show_rows(ui, row_h, n, |ui, range| { - if typing && (up || down) { - let top = ui.max_rect().top() + (highlight as f32 - range.start as f32) * step; - ui.scroll_to_rect(Rect::from_min_size(pos2(ui.max_rect().left(), top), vec2(1.0, row_h)), None); + if typing && (up || down) { + let top = ui.max_rect().top() + (highlight as f32 - range.start as f32) * step; + ui.scroll_to_rect(Rect::from_min_size(pos2(ui.max_rect().left(), top), vec2(1.0, row_h)), None); + } + for i in range { + if row(ui, i, typing && i == highlight) { + picked = Some(i); } - for i in range { - if row(ui, i, typing && i == highlight) { - picked = Some(i); - } - } - }); + } picked } } diff --git a/crates/ui-egui/src/mix_window/routing.rs b/crates/ui-egui/src/mix_window/routing.rs index 63e21f5b..176a8cba 100644 --- a/crates/ui-egui/src/mix_window/routing.rs +++ b/crates/ui-egui/src/mix_window/routing.rs @@ -1,5 +1,5 @@ use super::plugin_menu::{MenuSearch, menu_row}; -use super::*; +use super::{Route, SoundApp, Track, TrackId, Ui, json}; pub(crate) fn route_name(app: &SoundApp, r: &Route) -> String { match r { diff --git a/crates/ui-egui/src/mix_window/sends.rs b/crates/ui-egui/src/mix_window/sends.rs index b5da2eff..e0c3da4a 100644 --- a/crates/ui-egui/src/mix_window/sends.rs +++ b/crates/ui-egui/src/mix_window/sends.rs @@ -1,7 +1,11 @@ use super::plugin_menu::{MenuSearch, menu_row}; use super::routing::route_name; use super::slots::{COMPACT_SLOT, Mark, empty_slot, level_icon, used_slot}; -use super::*; +use super::{ + Align2, Rect, Route, Sense, SoundApp, Stroke, StrokeKind, Tokens, Track, TrackId, TrackKind, Ui, db_text, fader, json, pan_knob, pan_text, pos2, + regular, text_toggle, vec2, +}; +use craft_ui::combo::Menu; /// Draw one send slot: the route area picks a destination, while the level area opens or edits the send level. pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: usize, r: Rect) { @@ -53,30 +57,8 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us } None => empty_slot(ui.painter(), r, ui.rect_contains_pointer(r), mark), } - if let Some(send) = &snd { - egui::Popup::menu(&route_resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(250.0); - ui.horizontal(|ui| { - ui.strong(format!("Send {}", (b'A' + slot as u8) as char)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(egui::RichText::new(route_name(app, &send.target)).color(Tokens::current().counter_text)); - }); - }); - ui.label(egui::RichText::new("DESTINATION").size(8.0).color(Tokens::current().text_dim)); - send_route_menu(app, ui, id, slot, Some(&send.target)); - ui.separator(); - if ui.button("Remove send").clicked() { - let _ = app.run("mix.send_remove", json!({"track": id.0, "slot": slot})); - ui.close(); - } - }); - } else { - egui::Popup::menu(&route_resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(250.0); - ui.strong(format!("Send {} · Choose destination", (b'A' + slot as u8) as char)); - send_route_menu(app, ui, id, slot, None); - }); - } + let current = snd.as_ref().map(|send| (send.target.clone(), route_name(app, &send.target))); + send_route_menu(app, ui, &route_resp, id, slot, current); } /// The Send window, as in Pro Tools: one send's fader, level, pan, Mute and Pre-fader. Clicking a @@ -341,30 +323,143 @@ fn send_level_scale(ui: &mut Ui, db: f32) { ui.painter().line_segment([pos2(x, r.min.y), pos2(x, line_y + 3.0)], Stroke::new(2.0, t.counter_text)); } -/// Searchable bus destination list with a New Bus action for a send. -fn send_route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, current: Option<&Route>) { +/// What the send menu's footer was used for. +enum SendFooter { + NewBus, + RemoveSend, +} + +/// The send's destination menu: a title and the bus search on top, the matching buses in a list +/// that scrolls, "new bus..." (and "Remove send" for an existing send) fixed under it. +/// `current` is the send's destination and its name, if the slot has a send. +fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: TrackId, slot: usize, current: Option<(Route, String)>) { let busses = app.engine.session().busses.clone(); - let search = MenuSearch::show(ui, egui::Id::unique(("send-bus-search", id.0, slot)), "Search buses…"); - let visible: Vec<_> = busses.iter().filter(|bus| search.matches(&bus.name)).collect(); - let picked = search.rows(ui, visible.len(), 260.0, |ui, i, highlighted| { - let current = matches!(current, Some(Route::Bus(bus_id)) if *bus_id == visible[i].id); - menu_row(ui, highlighted || (current && !search.typing()), &visible[i].name) - }); - if let Some(i) = picked { - let _ = app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": visible[i].name})); - ui.close(); + let which = (b'A' + slot as u8) as char; + let has_send = current.is_some(); + let header = |ui: &mut Ui| { + ui.set_min_width(250.0); + match ¤t { + Some((_, name)) => { + ui.horizontal(|ui| { + ui.strong(format!("Send {which}")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(egui::RichText::new(name).color(Tokens::current().counter_text)); + }); + }); + ui.label(egui::RichText::new("DESTINATION").size(8.0).color(Tokens::current().text_dim)); + } + None => { + ui.strong(format!("Send {which} · Choose destination")); + } + } + let search = MenuSearch::show(ui, egui::Id::unique(("send-bus-search", id.0, slot)), "Search buses…"); + let visible: Vec<_> = busses.iter().filter(|bus| search.matches(&bus.name)).collect(); + (search, visible) + }; + let target = current.as_ref().map(|(route, _)| route); + let row_h = ui.spacing().interact_size.y; + let shown = Menu::new(ui, field).height(260.0).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show_rows_with_header_footer( + header, + row_h, + |(_, visible)| visible.len(), + |ui, range, (search, visible)| { + let n = visible.len(); + let picked = search.list_rows(ui, range, n, |ui, i, highlighted| { + let is_current = matches!(target, Some(Route::Bus(bus_id)) if *bus_id == visible[i].id); + menu_row(ui, highlighted || (is_current && !search.typing()), &visible[i].name) + }); + picked.map(|i| { + ui.close(); + visible[i].name.clone() + }) + }, + |ui| { + if ui.button("new bus...").clicked() { + ui.close(); + return Some(SendFooter::NewBus); + } + if has_send && ui.button("Remove send").clicked() { + ui.close(); + return Some(SendFooter::RemoveSend); + } + None + }, + ); + let Some((picked, footer)) = shown else { return }; + if let Some(bus) = picked { + let _ = app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": bus})); } - ui.separator(); - if ui.button("new bus...").clicked() { - let mut n = busses.len() + 1; - while busses.iter().any(|bus| bus.name.eq_ignore_ascii_case(&format!("Bus {n}"))) - || app.engine.session().track_by_name(&format!("Bus {n}")).is_some() - { - n += 1; + match footer { + Some(SendFooter::NewBus) => { + let mut n = busses.len() + 1; + while busses.iter().any(|bus| bus.name.eq_ignore_ascii_case(&format!("Bus {n}"))) + || app.engine.session().track_by_name(&format!("Bus {n}")).is_some() + { + n += 1; + } + if app.run("mix.new_bus", json!({"name": format!("Bus {n}")})).is_ok() { + let _ = app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": format!("Bus {n}")})); + } } - if app.run("mix.new_bus", json!({"name": format!("Bus {n}")})).is_ok() { - let _ = app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": format!("Bus {n}")})); + Some(SendFooter::RemoveSend) => { + let _ = app.run("mix.send_remove", json!({"track": id.0, "slot": slot})); } - ui.close(); + None => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Services; + use egui_kittest::{Harness, kittest::Queryable}; + + /// Filtering the destination list to nothing shrinks the menu; clearing the filter grows it + /// back, with the search field in the same place and the footer under the list. + #[test] + fn the_send_destination_menu_grows_back_when_the_search_is_cleared() { + let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default()); + for n in 0..30 { + app.run("mix.new_bus", json!({"name": format!("Aux {n}")})).unwrap(); + } + let kick = app.engine.session().track_by_name("Kick").unwrap().id; + app.run("mix.send", json!({"track": kick.0, "slot": 0, "bus": "Aux 0"})).unwrap(); + let _palette = crate::theme::lock_test_palette(); + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(600.0, 800.0)).build_ui_state( + move |ui, (app, kick): &mut (SoundApp, TrackId)| { + if !ready { + crate::fonts::install(ui.ctx(), true); + crate::theme::apply(ui.ctx(), false); + ready = true; + return; + } + let track = app.engine.session().track(*kick).cloned().unwrap(); + let r = Rect::from_min_size(ui.max_rect().min + vec2(20.0, 20.0), vec2(120.0, 24.0)); + send_slot(app, ui, &track, 0, r); + }, + (app, kick), + ); + h.run(); + h.get_by_label("Send A for Kick").click(); + h.run(); + let field = |h: &Harness<'_, (SoundApp, TrackId)>| h.get_by_role(egui::accesskit::Role::TextInput).rect(); + let footer = |h: &Harness<'_, (SoundApp, TrackId)>| h.get_by_label("Remove send").rect(); + let (search, full) = (field(&h), footer(&h)); + assert!(h.query_by_label("new bus...").is_some(), "the footer lists new bus..."); + assert!(full.top() > search.bottom() + 150.0, "the list sits between the search and the footer: {search:?} {full:?}"); + + h.get_by_role(egui::accesskit::Role::TextInput).type_text("zzzz"); + h.run(); + let none = footer(&h); + assert!(none.top() < full.top() - 100.0, "no matches shrink the menu: {none:?} vs {full:?}"); + assert_eq!(field(&h), search, "the search field stays put"); + + for _ in 0..4 { + h.key_press(egui::Key::Backspace); + h.run(); + } + assert_eq!(field(&h), search, "the search field stays put"); + assert!((footer(&h).top() - full.top()).abs() < 1.0, "cleared, the footer is back under the full list: {:?} vs {full:?}", footer(&h)); } } diff --git a/crates/ui-egui/src/mix_window/slots.rs b/crates/ui-egui/src/mix_window/slots.rs index 0c7e45cd..866b60eb 100644 --- a/crates/ui-egui/src/mix_window/slots.rs +++ b/crates/ui-egui/src/mix_window/slots.rs @@ -1,5 +1,5 @@ use super::plugin_menu::{instrument_menu, plugin_info, plugin_menu}; -use super::*; +use super::{Align2, Color32, Rect, Sense, SoundApp, Stroke, Tokens, Track, Ui, bold, groove, json, pos2, raised_key, shade, vec2}; /// An instrument track's INSTRUMENT row: click opens a hosted instrument's plugin window, /// right-click (or click, when none is set) picks another instrument. A built-in's parameters diff --git a/crates/ui-egui/src/panels/about.rs b/crates/ui-egui/src/panels/about.rs index 36074c25..504bf9f7 100644 --- a/crates/ui-egui/src/panels/about.rs +++ b/crates/ui-egui/src/panels/about.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, bold, mono, vec2}; /// About window tabs for version information, contributors and models. pub(super) fn about(app: &mut SoundApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/panels/clips.rs b/crates/ui-egui/src/panels/clips.rs index 4c127b97..cbdd28d5 100644 --- a/crates/ui-egui/src/panels/clips.rs +++ b/crates/ui-egui/src/panels/clips.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Align2, ClipId, Rect, Sense, SoundApp, SourceId, Tokens, Ui, bold, json, panel_header, pos2, regular, rgb, vec2, with_pending_offset}; /// One row of the clip list: a whole file, or a clip on a track (positions in the session). #[derive(Clone, Copy)] diff --git a/crates/ui-egui/src/panels/extra_windows.rs b/crates/ui-egui/src/panels/extra_windows.rs index e4a1001e..d257e96f 100644 --- a/crates/ui-egui/src/panels/extra_windows.rs +++ b/crates/ui-egui/src/panels/extra_windows.rs @@ -165,7 +165,7 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) { ); crate::widgets::checkbox(ui, &mut app.extra.reduce_motion, "Reduce motion"); let mut chosen = None; - egui::ComboBox::from_label("Theme").selected_text(app.ui.theme.label()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_label("Theme").selected_text(app.ui.theme.label()).show_ui(ui, |ui| { for mode in crate::theme::ThemeMode::ALL { if ui.selectable_label(app.ui.theme == mode, mode.label()).clicked() { chosen = Some(mode); diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index da145ca9..3d284f75 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, Tokens, Ui, json}; pub(crate) fn undo_history(app: &mut SoundApp, ui: &mut Ui) { let hist = app.engine.undo_history(); diff --git a/crates/ui-egui/src/panels/memory.rs b/crates/ui-egui/src/panels/memory.rs index 313713aa..d849e382 100644 --- a/crates/ui-egui/src/panels/memory.rs +++ b/crates/ui-egui/src/panels/memory.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{SoundApp, Ui, json, mono}; /// One recallable memory-location row: number button, editable name, time, length, kind and delete. fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc: &str, len: &str, kind: &str) { diff --git a/crates/ui-egui/src/panels/midi_editor.rs b/crates/ui-egui/src/panels/midi_editor.rs index 2515dbbb..2e48be01 100644 --- a/crates/ui-egui/src/panels/midi_editor.rs +++ b/crates/ui-egui/src/panels/midi_editor.rs @@ -69,6 +69,50 @@ fn is_black(p: i32) -> bool { } /// Draw the MIDI editor for the target clip, with an empty-state prompt that adds a clip on the selected MIDI track. +/// The piano roll's geometry: where it is drawn and how ticks and pitches map onto it. +#[derive(Clone, Copy)] +struct Roll<'a> { + sequence: &'a soundcraft_midi::Sequence, + roll: Rect, + keys: Rect, + vel: Rect, + px_per_tick: f32, + len_ticks: i64, + scroll: f32, + grid_ticks: i64, + rows: i32, +} + +impl Roll<'_> { + fn x_of(&self, tick: i64) -> f32 { + self.roll.min.x + tick as f32 * self.px_per_tick + } + + fn y_of(&self, pitch: i32) -> f32 { + self.roll.min.y + (127 - pitch) as f32 * ROW_H - self.scroll + } + + fn pitch_at(&self, y: f32) -> i32 { + 127 - ((y - self.roll.min.y + self.scroll) / ROW_H).floor() as i32 + } + + /// The note under `pos` and whether `pos` is on its resize edge. + fn hit(&self, pos: egui::Pos2) -> Option<(usize, bool)> { + self.sequence.notes.iter().enumerate().rev().find_map(|(i, n)| { + let r = Rect::from_min_max( + pos2(self.x_of(n.start), self.y_of(i32::from(n.pitch))), + pos2(self.x_of(n.start + n.length).max(self.x_of(n.start) + 3.0), self.y_of(i32::from(n.pitch)) + ROW_H), + ); + r.contains(pos).then_some((i, pos.x > r.max.x - 5.0)) + }) + } + + /// `tk` ticks, rounded to the grid. + fn snap(&self, tk: f32) -> i64 { + ((tk / self.grid_ticks as f32).round() as i64) * self.grid_ticks + } +} + pub fn show(app: &mut SoundApp, ui: &mut Ui) { // Painter-only contents do not advance the layout. Claim the resized // space, including the empty state, so the dock keeps its chosen height. @@ -80,24 +124,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { ui.painter().rect_filled(header, 0.0, t.panel_bg2); ui.painter().text(pos2(header.min.x + 8.0, header.center().y), Align2::LEFT_CENTER, "MIDI EDITOR", bold(11.5), t.header_text); let Some(cid) = target_clip(app) else { - let track = { - let s = app.engine.session(); - s.tracks.iter().find(|t| t.kind.is_midi() && s.edit.selected_tracks.contains(&t.id)).map(|t| (t.id, t.name.clone())) - }; - let msg = match &track { - Some((_, name)) => format!("Click to add a MIDI clip to {name} at the insertion point."), - None => "Select a MIDI clip (or a MIDI track) to edit its notes.".into(), - }; - ui.painter().text(full.center(), Align2::CENTER_CENTER, msg, regular(13.0), t.text_dim); - let body = Rect::from_min_max(pos2(full.min.x, header.max.y), full.max); - if let Some((id, _)) = track - && ui.interact(body, ui.scope_id().with("new_clip"), Sense::click()).clicked() - { - let sel = app.engine.session().edit.selection; - if let Ok(v) = app.run("midi.new_clip", json!({"track": id.0, "start": sel.start, "end": sel.end})) { - let _ = app.run("edit.select", json!({"clips": [v["clip"]]})); - } - } + empty_state(app, ui, full, header); return; }; let Some((track, clip)) = app.engine.session().find_clip(cid).map(|(t, c)| (t, c.clone())) else { return }; @@ -115,40 +142,8 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { regular(11.0), t.text_dim, ); - let grid_ticks = match app.engine.session().edit.grid { - soundcraft_time::GridValue::Note { value, dotted, triplet } => { - let mut g = value.ticks(); - if dotted { - g = g * 3 / 2; - } - if triplet { - g = g * 2 / 3; - } - g.max(1) - } - _ => TICKS_PER_QUARTER / 4, - }; - // Header toolbar: whole-clip MIDI operations. - let bar = Rect::from_min_max(pos2(header.max.x - 330.0, header.min.y + 1.0), pos2(header.max.x - 6.0, header.max.y - 1.0)); - let mut tb = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); - tb.spacing_mut().item_spacing.x = 4.0; - let mut op: Option<(&str, serde_json::Value)> = None; - if tb.small_button("Legato").clicked() { - op = Some(("event.change_duration", json!({"legato": 0}))); - } - if tb.small_button("Vel −10").clicked() { - op = Some(("event.change_velocity", json!({"add": -10}))); - } - if tb.small_button("Vel +10").clicked() { - op = Some(("event.change_velocity", json!({"add": 10}))); - } - if tb.small_button("Quantize").on_hover_text("Quantize to the grid").clicked() { - op = Some(("event.quantize", json!({"grid": grid_ticks, "strength": 100}))); - } - if let Some((id, mut p)) = op { - p["clips"] = json!([cid.0]); - let _ = app.run(id, p); - } + let grid_ticks = grid_ticks_of(app); + midi_toolbar(app, ui, header, cid, grid_ticks); let s = app.engine.session_arc(); let sr = s.sample_rate; let base_tick = s.tempo.samples_to_ticks(clip.start, sr); @@ -170,15 +165,90 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { app.midi.scroll = app.midi.scroll.clamp(0.0, (128.0 * ROW_H - roll.height()).max(0.0)); let scroll = app.midi.scroll; let px_per_tick = roll.width() / len_ticks as f32; - let x_of = |tick: i64| roll.min.x + tick as f32 * px_per_tick; - let y_of = |pitch: i32| roll.min.y + (127 - pitch) as f32 * ROW_H - scroll; - let pitch_at = |y: f32| 127 - ((y - roll.min.y + scroll) / ROW_H).floor() as i32; + let g = Roll { sequence, roll, keys, vel, px_per_tick, len_ticks, scroll, grid_ticks, rows }; let painter = ui.painter().with_clip_rect(roll.union(keys)); + draw_roll_background(&painter, &g); + // Notes. + let base = egui::Color32::from_rgb(track_color[0], track_color[1], track_color[2]); + draw_notes(app, &painter, &g, base); + note_pointer(app, ui, &g, cid, s.edit.tool == Tool::Pencil); + note_keys(app, ui, &g, cid); + velocity_lane(app, ui, &g, cid, base, full.min.x + 6.0); +} + +/// The empty state: a prompt that adds a clip on the selected MIDI track when clicked. +fn empty_state(app: &mut SoundApp, ui: &mut Ui, full: Rect, header: Rect) { + let t = Tokens::current(); + let track = { + let s = app.engine.session(); + s.tracks.iter().find(|t| t.kind.is_midi() && s.edit.selected_tracks.contains(&t.id)).map(|t| (t.id, t.name.clone())) + }; + let msg = match &track { + Some((_, name)) => format!("Click to add a MIDI clip to {name} at the insertion point."), + None => "Select a MIDI clip (or a MIDI track) to edit its notes.".into(), + }; + ui.painter().text(full.center(), Align2::CENTER_CENTER, msg, regular(13.0), t.text_dim); + let body = Rect::from_min_max(pos2(full.min.x, header.max.y), full.max); + if let Some((id, _)) = track + && ui.interact(body, ui.scope_id().with("new_clip"), Sense::click()).clicked() + { + let sel = app.engine.session().edit.selection; + if let Ok(v) = app.run("midi.new_clip", json!({"track": id.0, "start": sel.start, "end": sel.end})) { + let _ = app.run("edit.select", json!({"clips": [v["clip"]]})); + } + } +} + +/// The grid step in ticks, from the Edit window's grid value. +fn grid_ticks_of(app: &SoundApp) -> i64 { + match app.engine.session().edit.grid { + soundcraft_time::GridValue::Note { value, dotted, triplet } => { + let mut g = value.ticks(); + if dotted { + g = g * 3 / 2; + } + if triplet { + g = g * 2 / 3; + } + g.max(1) + } + _ => TICKS_PER_QUARTER / 4, + } +} + +/// The header toolbar: whole-clip MIDI operations. +fn midi_toolbar(app: &mut SoundApp, ui: &mut Ui, header: Rect, cid: ClipId, grid_ticks: i64) { + // Header toolbar: whole-clip MIDI operations. + let bar = Rect::from_min_max(pos2(header.max.x - 330.0, header.min.y + 1.0), pos2(header.max.x - 6.0, header.max.y - 1.0)); + let mut tb = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); + tb.spacing_mut().item_spacing.x = 4.0; + let mut op: Option<(&str, serde_json::Value)> = None; + if tb.small_button("Legato").clicked() { + op = Some(("event.change_duration", json!({"legato": 0}))); + } + if tb.small_button("Vel −10").clicked() { + op = Some(("event.change_velocity", json!({"add": -10}))); + } + if tb.small_button("Vel +10").clicked() { + op = Some(("event.change_velocity", json!({"add": 10}))); + } + if tb.small_button("Quantize").on_hover_text("Quantize to the grid").clicked() { + op = Some(("event.quantize", json!({"grid": grid_ticks, "strength": 100}))); + } + if let Some((id, mut p)) = op { + p["clips"] = json!([cid.0]); + let _ = app.run(id, p); + } +} + +/// Background rows, piano keys and the grid. +fn draw_roll_background(painter: &egui::Painter, g: &Roll<'_>) { + let Roll { roll, keys, px_per_tick, len_ticks, grid_ticks, rows, .. } = *g; // Background rows and keys. - let top = pitch_at(roll.min.y); + let top = g.pitch_at(roll.min.y); for r in 0..=rows + 1 { let pitch = top - r; - let y = y_of(pitch); + let y = g.y_of(pitch); let row = Rect::from_min_size(pos2(roll.min.x, y), vec2(roll.width(), ROW_H)); painter.rect_filled(row, 0.0, if is_black(pitch) { Color32::from_rgb(30, 30, 32) } else { Color32::from_rgb(40, 40, 42) }); let key = Rect::from_min_size(pos2(keys.min.x, y), vec2(KEY_W - 2.0, ROW_H - 1.0)); @@ -198,7 +268,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { let mut tick = 0; while tick <= len_ticks { let bar = tick % (TICKS_PER_QUARTER * 4) == 0; - let x = x_of(tick); + let x = g.x_of(tick); if grid_ticks as f32 * px_per_tick > 4.0 || bar { painter.line_segment( [pos2(x, roll.min.y), pos2(x, roll.max.y)], @@ -207,8 +277,12 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { } tick += grid_ticks; } +} + +/// The notes, with a drag in progress applied. +fn draw_notes(app: &SoundApp, painter: &egui::Painter, g: &Roll<'_>, base: Color32) { + let Roll { sequence, grid_ticks, .. } = *g; // Notes. - let base = egui::Color32::from_rgb(track_color[0], track_color[1], track_color[2]); let drag = app.midi.drag.clone(); for (i, n) in sequence.notes.iter().enumerate() { let (mut st, mut ln, mut p) = (n.start, n.length, i32::from(n.pitch)); @@ -224,7 +298,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { p = (p + d.dy_semi as i32).clamp(0, 127); } } - let r = Rect::from_min_max(pos2(x_of(st), y_of(p) + 1.0), pos2(x_of(st + ln).max(x_of(st) + 3.0), y_of(p) + ROW_H - 1.0)); + let r = Rect::from_min_max(pos2(g.x_of(st), g.y_of(p) + 1.0), pos2(g.x_of(st + ln).max(g.x_of(st) + 3.0), g.y_of(p) + ROW_H - 1.0)); let sel = app.midi.selected.contains(&i); let k = 0.45 + 0.55 * f32::from(n.velocity) / 127.0; let fill = if sel { @@ -234,22 +308,17 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { }; painter.rect(r, 2.0, fill, Stroke::new(1.0, Color32::BLACK), StrokeKind::Inside); } +} + +/// Pointer interaction on the roll: note and band selection, drags and clicks. +fn note_pointer(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId, pencil: bool) { + let Roll { sequence, roll, px_per_tick, grid_ticks, .. } = *g; // Interaction. let resp = ui.interact(roll, ui.scope_id().with(("roll", cid.0)), Sense::click_and_drag()); - let hit = |pos: egui::Pos2| -> Option<(usize, bool)> { - sequence.notes.iter().enumerate().rev().find_map(|(i, n)| { - let r = Rect::from_min_max( - pos2(x_of(n.start), y_of(i32::from(n.pitch))), - pos2(x_of(n.start + n.length).max(x_of(n.start) + 3.0), y_of(i32::from(n.pitch)) + ROW_H), - ); - r.contains(pos).then_some((i, pos.x > r.max.x - 5.0)) - }) - }; - let snap = |tk: f32| -> i64 { ((tk / grid_ticks as f32).round() as i64) * grid_ticks }; if resp.drag_started() && let Some(p) = resp.interact_pointer_pos() { - if let Some((i, edge)) = hit(p) { + if let Some((i, edge)) = g.hit(p) { if !app.midi.selected.contains(&i) { app.midi.selected = vec![i]; } @@ -275,8 +344,8 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { .enumerate() .filter(|(_, n)| { let r = Rect::from_min_max( - pos2(x_of(n.start), y_of(i32::from(n.pitch))), - pos2(x_of(n.start + n.length), y_of(i32::from(n.pitch)) + ROW_H), + pos2(g.x_of(n.start), g.y_of(i32::from(n.pitch))), + pos2(g.x_of(n.start + n.length), g.y_of(i32::from(n.pitch)) + ROW_H), ); r.intersects(band) }) @@ -288,7 +357,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { if resp.dragged() && let (Some(d), Some(p)) = (&mut app.midi.drag, resp.interact_pointer_pos()) { - d.dx_ticks = snap((p.x - d.start.x) / px_per_tick); + d.dx_ticks = g.snap((p.x - d.start.x) / px_per_tick); d.dy_semi = -((p.y - d.start.y) / ROW_H).round() as i64; } if resp.drag_stopped() @@ -306,7 +375,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { if resp.clicked() && let Some(p) = resp.interact_pointer_pos() { - match hit(p) { + match g.hit(p) { Some((i, _)) => { if ui.input(|x| x.modifiers.shift) { if !app.midi.selected.contains(&i) { @@ -317,8 +386,8 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { } // Audition on the instrument would go here (needs a live MIDI input path). } - None if s.edit.tool == Tool::Pencil => { - let pitch = pitch_at(p.y).clamp(0, 127); + None if pencil => { + let pitch = g.pitch_at(p.y).clamp(0, 127); let start = (((p.x - roll.min.x) / px_per_tick) as i64 / grid_ticks) * grid_ticks; let _ = app.run( "midi.note_add", @@ -329,6 +398,11 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { None => app.midi.selected.clear(), } } +} + +/// Keyboard: select all, move and delete notes. +fn note_keys(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId) { + let Roll { sequence, roll, grid_ticks, .. } = *g; // Keyboard: Cmd+A select all; arrows transpose (Shift = octave) and move by the grid. if ui.rect_contains_pointer(roll) && !ui.ctx().egui_wants_keyboard_input() { let (all, up, down, left, right, shift) = ui.input(|i| { @@ -373,12 +447,18 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { let _ = app.run("midi.note_delete", json!({"clip": cid.0, "indices": app.midi.selected})); app.midi.selected.clear(); } +} + +/// The velocity lane under the roll. +fn velocity_lane(app: &mut SoundApp, ui: &mut Ui, g: &Roll<'_>, cid: ClipId, base: Color32, label_x: f32) { + let Roll { sequence, vel, .. } = *g; + let t = Tokens::current(); // Velocity lane. ui.painter().rect_filled(vel, 0.0, Color32::from_rgb(28, 28, 30)); - ui.painter().text(pos2(full.min.x + 6.0, vel.center().y), Align2::LEFT_CENTER, "Velocity", regular(10.0), t.text_dim); + ui.painter().text(pos2(label_x, vel.center().y), Align2::LEFT_CENTER, "Velocity", regular(10.0), t.text_dim); let vresp = ui.interact(vel, ui.scope_id().with(("vel", cid.0)), Sense::click_and_drag()); for (i, n) in sequence.notes.iter().enumerate() { - let x = x_of(n.start); + let x = g.x_of(n.start); let h = (vel.height() - 4.0) * f32::from(n.velocity) / 127.0; let col = if app.midi.selected.contains(&i) { Color32::WHITE } else { base }; ui.painter().line_segment([pos2(x + 1.0, vel.max.y - 2.0), pos2(x + 1.0, vel.max.y - 2.0 - h)], Stroke::new(3.0, col)); @@ -386,8 +466,8 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { } if (vresp.clicked() || vresp.dragged()) && let Some(p) = vresp.interact_pointer_pos() - && let Some((i, n)) = sequence.notes.iter().enumerate().min_by_key(|(_, n)| ((x_of(n.start) - p.x).abs() * 10.0) as i64) - && (x_of(n.start) - p.x).abs() < 8.0 + && let Some((i, n)) = sequence.notes.iter().enumerate().min_by_key(|(_, n)| ((g.x_of(n.start) - p.x).abs() * 10.0) as i64) + && (g.x_of(n.start) - p.x).abs() < 8.0 { let v = (((vel.max.y - 2.0 - p.y) / (vel.height() - 4.0)) * 127.0).round().clamp(1.0, 127.0) as i64; let _ = app.engine.execute_merged("midi.note_edit", &json!({"clip": cid.0, "index": i, "velocity": v}), &format!("vel:{}", cid.0)); diff --git a/crates/ui-egui/src/panels/plugins.rs b/crates/ui-egui/src/panels/plugins.rs index 326e4a51..29125432 100644 --- a/crates/ui-egui/src/panels/plugins.rs +++ b/crates/ui-egui/src/panels/plugins.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Color32, Sense, SoundApp, Stroke, Tokens, Ui, json, mono, pos2, vec2}; /// Draw plugin windows for instrument and insert slots that still exist, removing closed ones from the list. pub(super) fn plugin_windows(app: &mut SoundApp, ctx: &egui::Context) { @@ -70,7 +70,7 @@ pub(super) fn plugin_windows(app: &mut SoundApp, ctx: &egui::Context) { let mut x = v; let resp = if !p.choices.is_empty() { let mut idx = x.round().max(0.0) as usize; - let r = egui::ComboBox::from_id_salt(("pc", tid.0, slot, p.id)) + let r = craft_ui::ComboBox::from_id_salt(("pc", tid.0, slot, p.id)) .selected_text(p.choices.get(idx).copied().unwrap_or("?")) .show_ui(ui, |ui| { for (i, c) in p.choices.iter().enumerate() { diff --git a/crates/ui-egui/src/panels/sampler_window.rs b/crates/ui-egui/src/panels/sampler_window.rs index a16fee9e..cc14c94c 100644 --- a/crates/ui-egui/src/panels/sampler_window.rs +++ b/crates/ui-egui/src/panels/sampler_window.rs @@ -7,22 +7,18 @@ use crate::SoundApp; use crate::theme::{Tokens, mono, regular}; use egui::{Align2, Color32, CursorIcon, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::json; +use soundcraft_audio_io::FileFormat; use soundcraft_model::{Insert, TrackId}; -use std::ffi::OsStr; -use std::path::Path; /// The built-in Sampler's plugin id. pub const SAMPLER: &str = "sampler"; -/// File extensions a sample can come from (what the audio decoder reads). -const AUDIO_EXTS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac", "mp3", "ogg", "oga", "m4a", "aac", "mp4", "caf"]; - /// Markers on the sample strip: the parameter each one sets, and whether it needs a loop. const MARKERS: [(&str, bool); 3] = [("start", false), ("loop_start", true), ("loop_end", true)]; /// Whether a file name looks like audio the sampler can load. -pub fn is_audio_name(name: &str) -> bool { - Path::new(name).extension().and_then(OsStr::to_str).is_some_and(|x| AUDIO_EXTS.contains(&x.to_ascii_lowercase().as_str())) +pub fn is_audio_name(name: impl AsRef) -> bool { + FileFormat::from_path(name).is_some() } /// Sampler parameters that are MIDI notes. @@ -145,9 +141,14 @@ pub fn sample_strip(app: &mut SoundApp, ui: &mut Ui, tid: TrackId, ins: &Insert) let load = if can_pick { load } else { load.on_disabled_hover_text("Drop an audio file on this window") }; if load.clicked() && let Some(pick) = &app.services.pick_open - && let Some(path) = pick("mix.sampler_load", AUDIO_EXTS) + && let Some(path) = pick("mix.sampler_load", &FileFormat::readable_extensions()) { - let _ = app.run("mix.sampler_load", json!({"track": tid.0, "path": path})); + match crate::dialogs::unicode(&path) { + Ok(path) => { + let _ = app.run("mix.sampler_load", json!({"track": tid.0, "path": path})); + } + Err(e) => app.ui.status = e.to_string(), + } } if ins.sample.is_some() && ui.button("Clear").clicked() { let _ = app.run("mix.sampler_clear", json!({"track": tid.0})); diff --git a/crates/ui-egui/src/panels/tracks.rs b/crates/ui-egui/src/panels/tracks.rs index 41b82794..b4fd9bb8 100644 --- a/crates/ui-egui/src/panels/tracks.rs +++ b/crates/ui-egui/src/panels/tracks.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + Align2, Color32, Rect, Sense, SoundApp, Stroke, Tokens, Ui, bold, gutter_scroll, json, panel_header, pos2, regular, rgb, vec2, + with_pending_offset, +}; /// Drag a Tracks list row to reorder the tracks: a line marks the gap it will land in. fn drag_track(app: &mut SoundApp, ui: &Ui, row: Rect, id: u64, dropped: bool) { diff --git a/crates/ui-egui/src/panels/transport.rs b/crates/ui-egui/src/panels/transport.rs index 511ccb51..9451c1d6 100644 --- a/crates/ui-egui/src/panels/transport.rs +++ b/crates/ui-egui/src/panels/transport.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Align2, Rect, Sense, SoundApp, Tokens, json, mono, pos2, vec2}; pub(super) fn transport_window(app: &mut SoundApp, ctx: &egui::Context) { let mut open = app.ui.show_transport; diff --git a/crates/ui-egui/src/panels/windows.rs b/crates/ui-egui/src/panels/windows.rs index 5138a113..a0719ea2 100644 --- a/crates/ui-egui/src/panels/windows.rs +++ b/crates/ui-egui/src/panels/windows.rs @@ -4,7 +4,8 @@ use crate::SoundApp; use crate::theme::{Tokens, mono, rgb}; use egui::{Color32, Sense, vec2}; use serde_json::{Value, json}; -use soundcraft_model::{AutomationMode, ClipContent}; +use soundcraft_audio_io::FileFormat; +use soundcraft_model::{AutomationMode, ClipContent, SESSION_EXTENSION}; use soundcraft_playback::AudioConfig; use soundcraft_playback::devices::{AudioSystem, DeviceInfo}; use std::sync::Arc; @@ -334,38 +335,38 @@ fn workspace(app: &mut SoundApp, ctx: &egui::Context) { ui.label(egui::RichText::new(&dir).small()); }); ui.separator(); - let mut entries: Vec<(String, bool)> = std::fs::read_dir(&dir) + // Names stay paths: a name that is not valid Unicode is shown lossily, and opening it says so. + let mut entries: Vec<(std::path::PathBuf, String, bool)> = std::fs::read_dir(&dir) .map(|rd| { rd.flatten() .filter_map(|e| { + let path = e.path(); let name = e.file_name().to_string_lossy().into_owned(); if name.starts_with('.') { return None; } let is_dir = e.file_type().is_ok_and(|t| t.is_dir()); - let ext = std::path::Path::new(&name).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase(); - (is_dir || ["wav", "aif", "aiff", "flac", "mp3", "ogg", "m4a", "m4b", "caf", "mid", "midi", "scraft"].contains(&ext.as_str())) - .then_some((name, is_dir)) + let ext = path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase(); + (is_dir || FileFormat::from_extension(&ext).is_some() || ["mid", "midi", SESSION_EXTENSION].contains(&ext.as_str())) + .then_some((path, name, is_dir)) }) .collect() }) .unwrap_or_default(); - entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.to_lowercase().cmp(&b.0.to_lowercase()))); + entries.sort_by(|a, b| b.2.cmp(&a.2).then(a.1.to_lowercase().cmp(&b.1.to_lowercase()))); egui::ScrollArea::vertical().show(ui, |ui| { - for (name, is_dir) in entries.into_iter().take(2000) { - let path = std::path::Path::new(&dir).join(&name).to_string_lossy().into_owned(); + for (path, name, is_dir) in entries.into_iter().take(2000) { let label = if is_dir { format!("📁 {name}") } else { format!("🔊 {name}") }; let r = ui.selectable_label(false, label); if r.double_clicked() { if is_dir { - app.ui.workspace_dir = path; - } else if name.ends_with(".scraft") { - let _ = crate::dialogs::run_or_ask(app, "session.open", json!({"path": path})); - } else if name.ends_with(".mid") || name.ends_with(".midi") { - let _ = app.run("file.import_midi", json!({"path": path})); + // The folder is kept as text in the preferences. + match crate::dialogs::unicode(&path) { + Ok(p) => app.ui.workspace_dir = p.to_owned(), + Err(e) => app.ui.status = e.to_string(), + } } else { - let at = app.engine.session().edit.selection.start; - crate::import::start(app, json!({"path": path, "at": at})); + crate::dialogs::open_path(app, &path); } } } @@ -452,7 +453,7 @@ fn chosen_device<'a>(devices: &'a [DeviceInfo], name: Option<&str>) -> Option<&' fn device_combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut Option, devices: &[DeviceInfo]) { let default = devices.iter().find(|d| d.is_default).map_or("none".to_string(), |d| d.name.clone()); let shown = value.clone().unwrap_or_else(|| format!("Default ({default})")); - let combo = egui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| { + let combo = craft_ui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| { ui.selectable_value(value, None, format!("Default ({default})")); for d in devices { ui.selectable_value(value, Some(d.name.clone()), format!("{} ({} ch)", d.name, d.max_channels)); @@ -464,7 +465,7 @@ fn device_combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut Option, options: &[u32], unit: &str) { let shown = value.map_or("Device default".to_string(), |v| format!("{v} {unit}")); - let combo = egui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| { + let combo = craft_ui::ComboBox::from_id_salt(id).width(300.0).selected_text(shown).show_ui(ui, |ui| { ui.selectable_value(value, None, "Device default"); for v in options { ui.selectable_value(value, Some(*v), format!("{v} {unit}")); @@ -490,7 +491,7 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) { let system_label = ui.label("Audio system"); let def = systems.iter().find(|s| s.is_default).map_or("none".to_string(), |s| s.name.clone()); let shown = draft.system.clone().unwrap_or_else(|| format!("Default ({def})")); - let system = egui::ComboBox::from_id_salt("pe-system").width(300.0).selected_text(shown).show_ui(ui, |ui| { + let system = craft_ui::ComboBox::from_id_salt("pe-system").width(300.0).selected_text(shown).show_ui(ui, |ui| { let before = draft.system.clone(); ui.selectable_value(&mut draft.system, None, format!("Default ({def})")); for s in systems.iter() { @@ -654,7 +655,7 @@ pub fn io_setup(app: &mut SoundApp, ctx: &egui::Context) { let main = app.engine.session().main_format(); ui.horizontal(|ui| { let main_label = ui.label("Main output"); - let format = egui::ComboBox::from_id_salt("main_output_format").selected_text(main.label()).show_ui(ui, |ui| { + let format = craft_ui::ComboBox::from_id_salt("main_output_format").selected_text(main.label()).show_ui(ui, |ui| { for f in soundcraft_model::ChannelFormat::ALL.into_iter().filter(|f| (2..=16).contains(&f.channels())) { if ui.selectable_label(f == main, f.label()).clicked() && f != main { let _ = app.run("setup.main_format", json!({"format": f.label()})); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 24b7cadc..e128241f 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -1,7 +1,12 @@ -/// Host services (file dialogs) injected by the app; absent in tests and on the web. +use std::path::{Path, PathBuf}; + +/// Host services (file dialogs) injected by the app; absent in tests and on the web. They return +/// paths as picked: the caller converts one to text where a command takes it ([`crate::dialogs::unicode`]). #[derive(Default)] pub struct Services { - pub pick_open: Option Option>>, - pub pick_save: Option Option>>, - pub pick_folder: Option Option>>, + pub pick_open: Option Option>>, + /// The purpose and the file to start from. + pub pick_save: Option Option>>, + /// The folder to start in. + pub pick_folder: Option Option>>, } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 35319f1c..e2c9a979 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -177,6 +177,14 @@ fn fixed(app: &mut SoundApp, key: Key, m: Modifiers, mac: bool) -> bool { let _ = app.run("edit.tool", json!({"tool": tool})); true } + _ => fixed_more(app, key, m, mac), + } +} + +/// The rest of [`fixed`]'s keys. +fn fixed_more(app: &mut SoundApp, key: Key, m: Modifiers, mac: bool) -> bool { + let plain = !m.command && !m.alt && !m.ctrl && !m.shift; + match key { // `=` is what a bare press of the unlabeled +/- key reports (it has no shift held, so it // can never be `Key::Plus`); `Key::Plus` is kept for a keyboard that does send it (e.g. a // numpad +). `!m.alt` leaves Alt+= to `window.event_list`'s registered shortcut. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index bbbba444..892b5393 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1387,6 +1387,56 @@ fn transport_simulation_advances_by_monotonic_elapsed_time_only() { app.engine.transport.playing = false; app.sim = None; } +/// One host iteration: the raw-input hook, then logic and UI in a single pass. +fn run_host_frame(app: &mut SoundApp, ctx: &egui::Context, mut input: egui::RawInput) { + app.raw_input_hook(ctx, &mut input); + let mut output = ctx.run_ui(input, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + output.textures_delta.clear(); +} + +/// Run one frame that discards its first layout pass; returns how many passes ran. +fn run_host_frame_discarding_first_pass(app: &mut SoundApp, ctx: &egui::Context, input: egui::RawInput) -> usize { + let mut passes = 0; + let mut output = ctx.run_ui(input, |ui| { + app.logic(ui.ctx()); + passes += 1; + if passes == 1 { + ui.ctx().request_discard("plugin gesture must survive a second layout pass"); + } + app.ui(ui); + }); + output.textures_delta.clear(); + passes +} + +/// The editor-poll fixture: each poll counts itself, takes the queued edits and, for the gestures that +/// ended, captures the instrument state `latest` holds. +fn poll_fixture( + reports: &std::rc::Rc>>, + latest: &std::rc::Rc>, + polls: &std::rc::Rc>, + captures: &std::rc::Rc>>, +) -> super::EditorPollFixture { + let (poll_reports, poll_latest, poll_count, poll_captures) = (reports.clone(), latest.clone(), polls.clone(), captures.clone()); + Box::new(move |pending| { + poll_count.set(poll_count.get() + 1); + let edits = std::mem::take(&mut *poll_reports.borrow_mut()); + super::editor_changes( + pending, + edits, + Vec::new(), + |_| false, + |due| { + poll_captures.borrow_mut().extend_from_slice(due); + due.iter().map(|&(track, slot)| (track, slot, vec![poll_latest.get(), 1])).collect() + }, + ) + }) +} + /// Plugin queues are drained once per host iteration, rather than once per discarded pass. /// The fixture replaces only native polling; the real raw hook, logic/UI, scheduler and /// engine state/undo commands run normally. @@ -1400,13 +1450,7 @@ fn editor_gesture_polling_survives_discarded_and_hidden_host_iterations() { let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); let raw = || egui::RawInput { screen_rect: Some(rect), ..Default::default() }; for _ in 0..4 { - let mut input = raw(); - app.raw_input_hook(&ctx, &mut input); - let mut output = ctx.run_ui(input, |ui| { - app.logic(ui.ctx()); - app.ui(ui); - }); - output.textures_delta.clear(); + run_host_frame(&mut app, &ctx, raw()); } let keys = app.engine.session().track_by_name("Keys").unwrap().id; let original = instrument_state(&app, keys); @@ -1421,34 +1465,11 @@ fn editor_gesture_polling_survives_discarded_and_hidden_host_iterations() { let latest = Rc::new(Cell::new(1u8)); let polls = Rc::new(Cell::new(0)); let captures = Rc::new(RefCell::new(Vec::new())); - let (poll_reports, poll_latest, poll_count, poll_captures) = (reports.clone(), latest.clone(), polls.clone(), captures.clone()); - app.editor_poll_fixture = Some(Box::new(move |pending| { - poll_count.set(poll_count.get() + 1); - let edits = std::mem::take(&mut *poll_reports.borrow_mut()); - super::editor_changes( - pending, - edits, - Vec::new(), - |_| false, - |due| { - poll_captures.borrow_mut().extend_from_slice(due); - due.iter().map(|&(track, slot)| (track, slot, vec![poll_latest.get(), 1])).collect() - }, - ) - })); + app.editor_poll_fixture = Some(poll_fixture(&reports, &latest, &polls, &captures)); reports.borrow_mut().push((keys, soundcraft_mix::INSTRUMENT_SLOT, "cutoff".into(), 1.0)); let mut input = raw(); app.raw_input_hook(&ctx, &mut input); - let mut passes = 0; - let mut output = ctx.run_ui(input, |ui| { - app.logic(ui.ctx()); - passes += 1; - if passes == 1 { - ui.ctx().request_discard("plugin gesture must survive a second layout pass"); - } - app.ui(ui); - }); - output.textures_delta.clear(); + let passes = run_host_frame_discarding_first_pass(&mut app, &ctx, input); assert!(passes >= 2, "the regression must actually force a discarded pass"); assert_eq!(polls.get(), 1, "the rerun cannot drain an empty editor queue"); assert!(captures.borrow().is_empty(), "the ongoing gesture has not ended"); @@ -1490,7 +1511,12 @@ fn editor_gesture_polling_survives_discarded_and_hidden_host_iterations() { let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); assert_eq!(polls.get(), 4, "a fresh empty host iteration is still live"); assert_eq!(captures.borrow().len(), 1, "the completed gesture is captured once"); - assert_eq!(app.engine.revision, settled_revision); + assert_history_unchanged(&app, settled_revision, undo, &history, &journal); +} + +/// The engine's revision, undo history and journal are as they were. +fn assert_history_unchanged(app: &SoundApp, revision: u64, undo: usize, history: &[String], journal: &[(String, serde_json::Value)]) { + assert_eq!(app.engine.revision, revision); assert_eq!(app.engine.undo_history().len(), undo); assert_eq!(app.engine.undo_history(), history); assert_eq!(app.engine.journal, journal); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 1a23ef63..e4a2acb1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -754,7 +754,7 @@ mod selector_visual_regressions { let mut harness = egui_kittest::Harness::builder().with_size(vec2(320.0, 120.0)).with_pixels_per_point(scale).wgpu().build_ui_state( move |ui, regions: &mut serde_json::Map| { if !ready { - crate::fonts::install(ui.ctx()); + crate::fonts::install(ui.ctx(), true); crate::theme::apply(ui.ctx(), false); ready = true; return; @@ -807,7 +807,7 @@ mod selector_visual_regressions { for mode in soundcraft_model::AutomationMode::ALL { for scale in [1.0, 1.5, 2.0] { let ctx = egui::Context::default(); - crate::fonts::install(&ctx); + crate::fonts::install(&ctx, true); crate::theme::apply(&ctx, false); let mut app = mixer_app(narrow, mode); let mut output = ctx.run_ui(scaled_input(vec2(320.0, 640.0), scale), |ui| crate::mix_window::show(&mut app, ui)); @@ -856,7 +856,7 @@ mod selector_visual_regressions { egui_kittest::Harness::builder().with_size(vec2(320.0, 640.0)).with_pixels_per_point(scale).wgpu().build_ui_state( move |ui, app: &mut crate::SoundApp| { if !ready { - crate::fonts::install(ui.ctx()); + crate::fonts::install(ui.ctx(), true); crate::theme::apply(ui.ctx(), false); ready = true; return; @@ -902,7 +902,7 @@ mod selector_visual_regressions { for label in ["auto read", "no group", "A very long mixer group name"] { for scale in [1.0, 1.5, 2.0] { let ctx = egui::Context::default(); - crate::fonts::install(&ctx); + crate::fonts::install(&ctx, true); crate::theme::apply(&ctx, false); let mut rect = Rect::NOTHING; let mut output = ctx.run_ui(scaled_input(vec2(320.0, 120.0), scale), |ui| { diff --git a/crates/ui-egui/tests/it/bounce_dialog.rs b/crates/ui-egui/tests/it/bounce_dialog.rs index e3a5499c..a712f4c3 100644 --- a/crates/ui-egui/tests/it/bounce_dialog.rs +++ b/crates/ui-egui/tests/it/bounce_dialog.rs @@ -1,16 +1,18 @@ //! Bounce Mix starts in the session's folder and has a Browse button for the file (#186). use egui::vec2; use egui_kittest::{Harness, kittest::Queryable}; +use soundcraft_audio_io::FileFormat; use soundcraft_ui_egui::{Services, SoundApp, dialogs::Dialog}; use std::cell::RefCell; +use std::path::{Path, PathBuf}; use std::rc::Rc; #[test] fn bounce_starts_in_the_session_folder_and_browse_picks_the_file_and_format() { let asked = Rc::new(RefCell::new(Vec::new())); let log = Rc::clone(&asked); - let pick_save: Box Option> = Box::new(move |purpose, default| { - log.borrow_mut().push((purpose.to_string(), default.to_string())); + let pick_save: Box Option> = Box::new(move |purpose, default| { + log.borrow_mut().push((purpose.to_string(), default.to_path_buf())); Some("/Mixes/Final Mix.FLAC".into()) }); let mut engine = soundcraft_engine::demo::demo_engine(); @@ -27,10 +29,10 @@ fn bounce_starts_in_the_session_folder_and_browse_picks_the_file_and_format() { h.run_steps(3); h.get_by_label("Browse…").click(); h.run_steps(3); - let default = "/Songs/Midnight Groove/Midnight Groove Bounce.wav".to_string(); + let default = PathBuf::from("/Songs/Midnight Groove/Midnight Groove Bounce.wav"); assert_eq!(*asked.borrow(), vec![("file.bounce_mix".to_string(), default)]); match &h.state().dialogs.open { - Some(Dialog::Bounce { path, format, .. }) => assert_eq!((path.as_str(), format.as_str()), ("/Mixes/Final Mix.FLAC", "flac")), + Some(Dialog::Bounce { path, format, .. }) => assert_eq!((path.as_str(), *format), ("/Mixes/Final Mix.FLAC", FileFormat::Flac)), other => panic!("{other:?}"), } } diff --git a/crates/ui-egui/tests/mix_instrument_contrast.rs b/crates/ui-egui/tests/mix_instrument_contrast.rs index bcdc5c28..2bb6cd92 100644 --- a/crates/ui-egui/tests/mix_instrument_contrast.rs +++ b/crates/ui-egui/tests/mix_instrument_contrast.rs @@ -72,6 +72,19 @@ fn contrast(a: Color32, b: Color32) -> f64 { (a.max(b) + 0.05) / (a.min(b) + 0.05) } +/// A primary click at `at`, one frame for the press and one for the release. +fn press_and_release(harness: &mut egui_kittest::Harness<'_, SoundApp>, at: egui::Pos2) { + for pressed in [true, false] { + harness.input_mut().events.push(Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }); + harness.step(); + } +} + /// In real frames, populated and empty instrument and insert slots use the active theme's readable palette across /// light, dark and system modes, and a plugin change leaves the rest of the session and audio pool intact. #[test] @@ -169,15 +182,7 @@ fn populated_mix_instrument_uses_readable_palette_in_real_frames() { // Exercise the same painted control's ordinary click/picker path after palette changes. let at = slot(harness.output(), "SubSynth").rect.center(); - for pressed in [true, false] { - harness.input_mut().events.push(Event::PointerButton { - pos: at, - button: egui::PointerButton::Primary, - pressed, - modifiers: Default::default(), - }); - harness.step(); - } + press_and_release(&mut harness, at); harness.step(); // Let the popup finish its initial sizing pass. harness.get_by_label("Built-in").hover(); harness.step(); diff --git a/crates/video/src/h264/deblock.rs b/crates/video/src/h264/deblock.rs index 12ba8da5..e918476c 100644 --- a/crates/video/src/h264/deblock.rs +++ b/crates/video/src/h264/deblock.rs @@ -279,7 +279,6 @@ fn filter_horizontal(pix: &mut [u8], stride: usize, x: usize, y: } /// Deblock one macroblock (macroblocks must be processed in raster order). -#[allow(clippy::needless_range_loop)] pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) { let q = &pic.mbs[addr]; if q.slice_num == u32::MAX { @@ -303,6 +302,23 @@ pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) { let alpha_off = sq.alpha_offset; let beta_off = sq.beta_offset; let t8 = q.transform_8x8; + let bs = boundary_strengths(pic, q, sq, left, top, t8); + let qp_of = |st: &MbState| if st.kind == MbKind::IPcm { 0 } else { st.qp as i32 }; + let q_qp = qp_of(q); + let q_qpc = q.qpc; + let p_qp = [left.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc)), top.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc))]; + let params = |qpp: i32, qpq: i32, b: [u8; 4]| { + let qpav = (qpp + qpq + 1) >> 1; + let index_a = (qpav + alpha_off).clamp(0, 51) as usize; + let index_b = (qpav + beta_off).clamp(0, 51) as usize; + let tc = |b: u8| if (1..4).contains(&b) { TC0[index_a][b as usize - 1] as i32 } else { 0 }; + EdgeParams { bs: b, tc0: [tc(b[0]), tc(b[1]), tc(b[2]), tc(b[3])], alpha: ALPHA[index_a] as i32, beta: BETA[index_b] as i32 } + }; + filter_luma(pic, (mx, my), &bs, q_qp, p_qp, ¶ms); + filter_chroma(pic, (mx, my), &bs, q_qpc, p_qp, ¶ms); +} + +fn boundary_strengths(pic: &PicState, q: &MbState, sq: &SliceInfo, left: Option, top: Option, t8: bool) -> [[[u8; 4]; 4]; 2] { // bS[dir][edge][segment]; dir 0 = vertical edges (x), 1 = horizontal edges (y) let mut bs = [[[0u8; 4]; 4]; 2]; if q.kind.is_intra() { @@ -356,20 +372,18 @@ pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) { } } } - let qp_of = |st: &MbState| if st.kind == MbKind::IPcm { 0 } else { st.qp as i32 }; - let q_qp = qp_of(q); - let q_qpc = q.qpc; - let p_qp = [left.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc)), top.map(|n| (qp_of(&pic.mbs[n]), pic.mbs[n].qpc))]; - let params = |qpp: i32, qpq: i32, b: [u8; 4]| { - let qpav = (qpp + qpq + 1) >> 1; - let index_a = (qpav + alpha_off).clamp(0, 51) as usize; - let index_b = (qpav + beta_off).clamp(0, 51) as usize; - let tc = |b: u8| if (1..4).contains(&b) { TC0[index_a][b as usize - 1] as i32 } else { 0 }; - EdgeParams { bs: b, tc0: [tc(b[0]), tc(b[1]), tc(b[2]), tc(b[3])], alpha: ALPHA[index_a] as i32, beta: BETA[index_b] as i32 } - }; + bs +} + +fn filter_luma( + pic: &mut PicState, + (mx, my): (usize, usize), + bs: &[[[u8; 4]; 4]; 2], + q_qp: i32, + p_qp: [Option<(i32, [u8; 2])>; 2], + params: &impl Fn(i32, i32, [u8; 4]) -> EdgeParams, +) { let width = pic.planes.width; - let cwidth = pic.planes.cwidth; - // luma for dir in 0..2 { for e in 0..4 { if bs[dir][e] == [0; 4] { @@ -389,6 +403,17 @@ pub fn deblock_mb(pic: &mut PicState, addr: usize, mb_w: usize) { } } } +} + +fn filter_chroma( + pic: &mut PicState, + (mx, my): (usize, usize), + bs: &[[[u8; 4]; 4]; 2], + q_qpc: [u8; 2], + p_qp: [Option<(i32, [u8; 2])>; 2], + params: &impl Fn(i32, i32, [u8; 4]) -> EdgeParams, +) { + let cwidth = pic.planes.cwidth; // chroma (4:2:0): edges at chroma samples 0 and 4 use the bS of luma edges 0 and 2 for c in 0..2 { for dir in 0..2 { diff --git a/crates/video/src/h264/intra.rs b/crates/video/src/h264/intra.rs index decf2965..176d9a11 100644 --- a/crates/video/src/h264/intra.rs +++ b/crates/video/src/h264/intra.rs @@ -61,125 +61,146 @@ fn load_edge(plane: &[u8], stride: usize, x: usize, y: usize, n: usize, a: Avail /// Directional / DC prediction shared by Intra_4x4 and Intra_8x8 (8.3.1.2.x, 8.3.2.2.x). fn pred_nxn(mode: u8, e: &Edge, n: i32, a: Avail, out: &mut [u8], stride: usize) { - let mut put = |x: i32, y: i32, v: i32| out[y as usize * stride + x as usize] = v as u8; match mode { - 0 => { - for y in 0..n { - for x in 0..n { - put(x, y, e.t(x)); - } - } + 0 => pred_vertical(e, n, out, stride), + 1 => pred_horizontal(e, n, out, stride), + 2 => pred_dc(e, n, a, out, stride), + 3 => pred_down_left(e, n, out, stride), + 4 => pred_down_right(e, n, out, stride), + 5 => pred_vertical_right(e, n, out, stride), + 6 => pred_horizontal_down(e, n, out, stride), + 7 => pred_vertical_left(e, n, out, stride), + _ => pred_horizontal_up(e, n, out, stride), + } +} + +fn put(out: &mut [u8], stride: usize, x: i32, y: i32, value: i32) { + out[y as usize * stride + x as usize] = value as u8; +} + +fn pred_vertical(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + put(out, stride, x, y, e.t(x)); } - 1 => { - for y in 0..n { - for x in 0..n { - put(x, y, e.l(y)); - } - } + } +} + +fn pred_horizontal(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + put(out, stride, x, y, e.l(y)); } - 2 => { - let shift = if n == 4 { 2 } else { 3 }; - let st: i32 = (0..n).map(|x| e.t(x)).sum(); - let sl: i32 = (0..n).map(|y| e.l(y)).sum(); - let dc = match (a.top, a.left) { - (true, true) => (st + sl + n) >> (shift + 1), - (false, true) => (sl + (n >> 1)) >> shift, - (true, false) => (st + (n >> 1)) >> shift, - _ => 128, + } +} + +fn pred_dc(e: &Edge, n: i32, a: Avail, out: &mut [u8], stride: usize) { + let shift = if n == 4 { 2 } else { 3 }; + let st: i32 = (0..n).map(|x| e.t(x)).sum(); + let sl: i32 = (0..n).map(|y| e.l(y)).sum(); + let dc = match (a.top, a.left) { + (true, true) => (st + sl + n) >> (shift + 1), + (false, true) => (sl + (n >> 1)) >> shift, + (true, false) => (st + (n >> 1)) >> shift, + _ => 128, + }; + for y in 0..n { + for x in 0..n { + put(out, stride, x, y, dc); + } + } +} + +fn pred_down_left(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + let value = if x == n - 1 && y == n - 1 { + (e.t(2 * n - 2) + 3 * e.t(2 * n - 1) + 2) >> 2 + } else { + (e.t(x + y) + 2 * e.t(x + y + 1) + e.t(x + y + 2) + 2) >> 2 }; - for y in 0..n { - for x in 0..n { - put(x, y, dc); - } - } + put(out, stride, x, y, value); } - 3 => { - for y in 0..n { - for x in 0..n { - let v = if x == n - 1 && y == n - 1 { - (e.t(2 * n - 2) + 3 * e.t(2 * n - 1) + 2) >> 2 - } else { - (e.t(x + y) + 2 * e.t(x + y + 1) + e.t(x + y + 2) + 2) >> 2 - }; - put(x, y, v); - } - } + } +} + +fn pred_down_right(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + let value = if x > y { + (e.t(x - y - 2) + 2 * e.t(x - y - 1) + e.t(x - y) + 2) >> 2 + } else if x < y { + (e.l(y - x - 2) + 2 * e.l(y - x - 1) + e.l(y - x) + 2) >> 2 + } else { + (e.t(0) + 2 * e.tl + e.l(0) + 2) >> 2 + }; + put(out, stride, x, y, value); } - 4 => { - for y in 0..n { - for x in 0..n { - let v = if x > y { - (e.t(x - y - 2) + 2 * e.t(x - y - 1) + e.t(x - y) + 2) >> 2 - } else if x < y { - (e.l(y - x - 2) + 2 * e.l(y - x - 1) + e.l(y - x) + 2) >> 2 - } else { - (e.t(0) + 2 * e.tl + e.l(0) + 2) >> 2 - }; - put(x, y, v); - } - } + } +} + +fn pred_vertical_right(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + let z = 2 * x - y; + let value = if z >= 0 && z % 2 == 0 { + (e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 1) >> 1 + } else if z > 0 { + (e.t(x - (y >> 1) - 2) + 2 * e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 2) >> 2 + } else if z == -1 { + (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2 + } else { + (e.l(y - 2 * x - 1) + 2 * e.l(y - 2 * x - 2) + e.l(y - 2 * x - 3) + 2) >> 2 + }; + put(out, stride, x, y, value); } - 5 => { - for y in 0..n { - for x in 0..n { - let z = 2 * x - y; - let v = if z >= 0 && z % 2 == 0 { - (e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 1) >> 1 - } else if z > 0 { - (e.t(x - (y >> 1) - 2) + 2 * e.t(x - (y >> 1) - 1) + e.t(x - (y >> 1)) + 2) >> 2 - } else if z == -1 { - (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2 - } else { - (e.l(y - 2 * x - 1) + 2 * e.l(y - 2 * x - 2) + e.l(y - 2 * x - 3) + 2) >> 2 - }; - put(x, y, v); - } - } + } +} + +fn pred_horizontal_down(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + let z = 2 * y - x; + let value = if z >= 0 && z % 2 == 0 { + (e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 1) >> 1 + } else if z > 0 { + (e.l(y - (x >> 1) - 2) + 2 * e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 2) >> 2 + } else if z == -1 { + (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2 + } else { + (e.t(x - 2 * y - 1) + 2 * e.t(x - 2 * y - 2) + e.t(x - 2 * y - 3) + 2) >> 2 + }; + put(out, stride, x, y, value); } - 6 => { - for y in 0..n { - for x in 0..n { - let z = 2 * y - x; - let v = if z >= 0 && z % 2 == 0 { - (e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 1) >> 1 - } else if z > 0 { - (e.l(y - (x >> 1) - 2) + 2 * e.l(y - (x >> 1) - 1) + e.l(y - (x >> 1)) + 2) >> 2 - } else if z == -1 { - (e.l(0) + 2 * e.tl + e.t(0) + 2) >> 2 - } else { - (e.t(x - 2 * y - 1) + 2 * e.t(x - 2 * y - 2) + e.t(x - 2 * y - 3) + 2) >> 2 - }; - put(x, y, v); - } - } + } +} + +fn pred_vertical_left(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + for y in 0..n { + for x in 0..n { + let i = x + (y >> 1); + let value = if y % 2 == 0 { (e.t(i) + e.t(i + 1) + 1) >> 1 } else { (e.t(i) + 2 * e.t(i + 1) + e.t(i + 2) + 2) >> 2 }; + put(out, stride, x, y, value); } - 7 => { - for y in 0..n { - for x in 0..n { - let i = x + (y >> 1); - let v = if y % 2 == 0 { (e.t(i) + e.t(i + 1) + 1) >> 1 } else { (e.t(i) + 2 * e.t(i + 1) + e.t(i + 2) + 2) >> 2 }; - put(x, y, v); - } - } - } - _ => { - let zmax = 2 * n - 3; - for y in 0..n { - for x in 0..n { - let z = x + 2 * y; - let i = y + (x >> 1); - let v = if z < zmax && z % 2 == 0 { - (e.l(i) + e.l(i + 1) + 1) >> 1 - } else if z < zmax { - (e.l(i) + 2 * e.l(i + 1) + e.l(i + 2) + 2) >> 2 - } else if z == zmax { - (e.l(n - 2) + 3 * e.l(n - 1) + 2) >> 2 - } else { - e.l(n - 1) - }; - put(x, y, v); - } - } + } +} + +fn pred_horizontal_up(e: &Edge, n: i32, out: &mut [u8], stride: usize) { + let zmax = 2 * n - 3; + for y in 0..n { + for x in 0..n { + let z = x + 2 * y; + let i = y + (x >> 1); + let value = if z < zmax && z % 2 == 0 { + (e.l(i) + e.l(i + 1) + 1) >> 1 + } else if z < zmax { + (e.l(i) + 2 * e.l(i + 1) + e.l(i + 2) + 2) >> 2 + } else if z == zmax { + (e.l(n - 2) + 3 * e.l(n - 1) + 2) >> 2 + } else { + e.l(n - 1) + }; + put(out, stride, x, y, value); } } } diff --git a/crates/video/src/h264/slice.rs b/crates/video/src/h264/slice.rs index bd641d5a..06a2bc67 100644 --- a/crates/video/src/h264/slice.rs +++ b/crates/video/src/h264/slice.rs @@ -214,101 +214,9 @@ impl SliceHeader { num_ref_idx_active[0] = 0; } ensure!(nal.nal_unit_type != 20 && nal.nal_unit_type != 21, "MVC slices are not supported"); - let mut ref_pic_list_mod = [Vec::new(), Vec::new()]; - for (list, mods) in ref_pic_list_mod.iter_mut().enumerate() { - let present = if list == 0 { !slice_type.is_intra() } else { slice_type.is_b() }; - if present && r.read_flag()? { - loop { - let idc = r.read_ue()?; - ensure!(idc <= 5, "modification_of_pic_nums_idc out of range"); - if idc == 3 { - break; - } - let value = r.read_ue()?; - mods.push(RefPicListMod { idc, value }); - ensure!(mods.len() <= 66, "too many ref_pic_list_modification entries"); - } - } - } - let mut pred_weight_table = None; - if (pps.weighted_pred && slice_type.is_p()) || (pps.weighted_bipred_idc == 1 && slice_type.is_b()) { - let luma_log2_denom = r.read_ue()?; - ensure!(luma_log2_denom <= 7, "luma_log2_weight_denom out of range"); - let mut chroma_log2_denom = 0; - if sps.chroma_array_type() != 0 { - chroma_log2_denom = r.read_ue()?; - ensure!(chroma_log2_denom <= 7, "chroma_log2_weight_denom out of range"); - } - let mut lists = [Vec::new(), Vec::new()]; - let nlists = if slice_type.is_b() { 2 } else { 1 }; - for (l, entries) in lists.iter_mut().enumerate().take(nlists) { - for _ in 0..num_ref_idx_active[l] { - let mut e = WeightEntry { luma_weight: 1 << luma_log2_denom, chroma_weight: [1 << chroma_log2_denom; 2], ..Default::default() }; - if r.read_flag()? { - e.luma_flag = true; - e.luma_weight = r.read_se()?; - e.luma_offset = r.read_se()?; - ensure!((-128..=127).contains(&e.luma_weight) && (-128..=127).contains(&e.luma_offset), "luma weight out of range"); - } - if sps.chroma_array_type() != 0 && r.read_flag()? { - e.chroma_flag = true; - for j in 0..2 { - e.chroma_weight[j] = r.read_se()?; - e.chroma_offset[j] = r.read_se()?; - ensure!( - (-128..=127).contains(&e.chroma_weight[j]) && (-128..=127).contains(&e.chroma_offset[j]), - "chroma weight out of range" - ); - } - } - entries.push(e); - } - } - let [l0, l1] = lists; - pred_weight_table = Some(PredWeightTable { luma_log2_denom, chroma_log2_denom, l0, l1 }); - } - let mut no_output_of_prior_pics = false; - let mut long_term_reference = false; - let mut adaptive_ref_pic_marking = false; - let mut mmcos = Vec::new(); - if nal.nal_ref_idc != 0 { - if idr { - no_output_of_prior_pics = r.read_flag()?; - long_term_reference = r.read_flag()?; - } else { - adaptive_ref_pic_marking = r.read_flag()?; - if adaptive_ref_pic_marking { - loop { - let op = r.read_ue()?; - ensure!(op <= 6, "memory_management_control_operation out of range"); - if op == 0 { - break; - } - let mut m = Mmco { - op, - difference_of_pic_nums_minus1: 0, - long_term_pic_num: 0, - long_term_frame_idx: 0, - max_long_term_frame_idx_plus1: 0, - }; - if op == 1 || op == 3 { - m.difference_of_pic_nums_minus1 = r.read_ue()?; - } - if op == 2 { - m.long_term_pic_num = r.read_ue()?; - } - if op == 3 || op == 6 { - m.long_term_frame_idx = r.read_ue()?; - } - if op == 4 { - m.max_long_term_frame_idx_plus1 = r.read_ue()?; - } - mmcos.push(m); - ensure!(mmcos.len() <= 66, "too many MMCOs"); - } - } - } - } + let ref_fields = parse_reference_fields(&mut r, nal, idr, slice_type, pps, sps, num_ref_idx_active)?; + let RefFields { ref_pic_list_mod, pred_weight_table, no_output_of_prior_pics, long_term_reference, adaptive_ref_pic_marking, mmcos } = + ref_fields; let mut cabac_init_idc = 0; if pps.entropy_coding_mode && !slice_type.is_intra() { cabac_init_idc = r.read_ue()?; @@ -391,6 +299,134 @@ impl SliceHeader { } } +struct RefFields { + ref_pic_list_mod: [Vec; 2], + pred_weight_table: Option, + no_output_of_prior_pics: bool, + long_term_reference: bool, + adaptive_ref_pic_marking: bool, + mmcos: Vec, +} + +fn parse_reference_fields( + r: &mut BitReader<'_>, + nal: NalHeader, + idr: bool, + slice_type: SliceType, + pps: &Pps, + sps: &Sps, + num_ref_idx_active: [u32; 2], +) -> Result { + let ref_pic_list_mod = parse_ref_pic_list_mod(r, slice_type)?; + let pred_weight_table = parse_pred_weight_table(r, slice_type, pps, sps, num_ref_idx_active)?; + let (no_output_of_prior_pics, long_term_reference, adaptive_ref_pic_marking, mmcos) = parse_ref_pic_marking(r, nal, idr)?; + Ok(RefFields { ref_pic_list_mod, pred_weight_table, no_output_of_prior_pics, long_term_reference, adaptive_ref_pic_marking, mmcos }) +} + +fn parse_ref_pic_list_mod(r: &mut BitReader<'_>, slice_type: SliceType) -> Result<[Vec; 2]> { + let mut lists = [Vec::new(), Vec::new()]; + for (list, mods) in lists.iter_mut().enumerate() { + let present = if list == 0 { !slice_type.is_intra() } else { slice_type.is_b() }; + if present && r.read_flag()? { + loop { + let idc = r.read_ue()?; + ensure!(idc <= 5, "modification_of_pic_nums_idc out of range"); + if idc == 3 { + break; + } + mods.push(RefPicListMod { idc, value: r.read_ue()? }); + ensure!(mods.len() <= 66, "too many ref_pic_list_modification entries"); + } + } + } + Ok(lists) +} + +fn parse_pred_weight_table(r: &mut BitReader<'_>, slice_type: SliceType, pps: &Pps, sps: &Sps, active: [u32; 2]) -> Result> { + let weighted = (pps.weighted_pred && slice_type.is_p()) || (pps.weighted_bipred_idc == 1 && slice_type.is_b()); + if !weighted { + return Ok(None); + } + let luma_log2_denom = r.read_ue()?; + ensure!(luma_log2_denom <= 7, "luma_log2_weight_denom out of range"); + let chroma_log2_denom = if sps.chroma_array_type() == 0 { 0 } else { r.read_ue()? }; + ensure!(chroma_log2_denom <= 7, "chroma_log2_weight_denom out of range"); + let mut lists = [Vec::new(), Vec::new()]; + let list_count = if slice_type.is_b() { 2 } else { 1 }; + for (list, entries) in lists.iter_mut().enumerate().take(list_count) { + for _ in 0..active[list] { + entries.push(parse_weight_entry(r, luma_log2_denom, chroma_log2_denom, sps.chroma_array_type() != 0)?); + } + } + let [l0, l1] = lists; + Ok(Some(PredWeightTable { luma_log2_denom, chroma_log2_denom, l0, l1 })) +} + +fn parse_weight_entry(r: &mut BitReader<'_>, luma_denom: u32, chroma_denom: u32, has_chroma: bool) -> Result { + let mut entry = WeightEntry { luma_weight: 1 << luma_denom, chroma_weight: [1 << chroma_denom; 2], ..Default::default() }; + if r.read_flag()? { + entry.luma_flag = true; + entry.luma_weight = r.read_se()?; + entry.luma_offset = r.read_se()?; + ensure!((-128..=127).contains(&entry.luma_weight) && (-128..=127).contains(&entry.luma_offset), "luma weight out of range"); + } + if has_chroma && r.read_flag()? { + entry.chroma_flag = true; + for index in 0..2 { + entry.chroma_weight[index] = r.read_se()?; + entry.chroma_offset[index] = r.read_se()?; + ensure!( + (-128..=127).contains(&entry.chroma_weight[index]) && (-128..=127).contains(&entry.chroma_offset[index]), + "chroma weight out of range" + ); + } + } + Ok(entry) +} + +fn parse_ref_pic_marking(r: &mut BitReader<'_>, nal: NalHeader, idr: bool) -> Result<(bool, bool, bool, Vec)> { + let (mut no_output, mut long_term, mut adaptive) = (false, false, false); + let mut mmcos = Vec::new(); + if nal.nal_ref_idc == 0 { + return Ok((no_output, long_term, adaptive, mmcos)); + } + if idr { + no_output = r.read_flag()?; + long_term = r.read_flag()?; + } else { + adaptive = r.read_flag()?; + if adaptive { + parse_mmcos(r, &mut mmcos)?; + } + } + Ok((no_output, long_term, adaptive, mmcos)) +} + +fn parse_mmcos(r: &mut BitReader<'_>, mmcos: &mut Vec) -> Result<()> { + loop { + let op = r.read_ue()?; + ensure!(op <= 6, "memory_management_control_operation out of range"); + if op == 0 { + return Ok(()); + } + let mut m = Mmco { op, difference_of_pic_nums_minus1: 0, long_term_pic_num: 0, long_term_frame_idx: 0, max_long_term_frame_idx_plus1: 0 }; + if op == 1 || op == 3 { + m.difference_of_pic_nums_minus1 = r.read_ue()?; + } + if op == 2 { + m.long_term_pic_num = r.read_ue()?; + } + if op == 3 || op == 6 { + m.long_term_frame_idx = r.read_ue()?; + } + if op == 4 { + m.max_long_term_frame_idx_plus1 = r.read_ue()?; + } + mmcos.push(m); + ensure!(mmcos.len() <= 66, "too many MMCOs"); + } +} + /// POC decoding state carried between pictures (8.2.1). #[derive(Clone, Debug, Default)] pub struct PocState { diff --git a/crates/vst3-host/Cargo.toml b/crates/vst3-host/Cargo.toml index 00ace628..7a956118 100644 --- a/crates/vst3-host/Cargo.toml +++ b/crates/vst3-host/Cargo.toml @@ -54,7 +54,9 @@ harness = false unsafe_code = "deny" [lints.clippy] +cognitive_complexity = "deny" +wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" -too_many_arguments = "allow" +too_many_arguments = "deny" type_complexity = "allow" diff --git a/crates/vst3-host/src/ffi.rs b/crates/vst3-host/src/ffi.rs index ed42bd6f..dc65b7a8 100644 --- a/crates/vst3-host/src/ffi.rs +++ b/crates/vst3-host/src/ffi.rs @@ -39,7 +39,7 @@ mod process; pub(crate) use editor::EditorLink; pub(crate) use host::HostContext; -pub(crate) use instance::{Instance, PARAM_BYPASS, PARAM_HIDDEN, PARAM_READ_ONLY, RawParam}; +pub(crate) use instance::{Instance, PARAM_BYPASS, PARAM_HIDDEN, PARAM_READ_ONLY, ProcessInput, RawParam}; #[cfg(test)] use instance::{apply_transport, split_state}; pub(crate) use module::{Bundle, exit_modules, hex}; diff --git a/crates/vst3-host/src/ffi/editor.rs b/crates/vst3-host/src/ffi/editor.rs index aba22549..89d344fa 100644 --- a/crates/vst3-host/src/ffi/editor.rs +++ b/crates/vst3-host/src/ffi/editor.rs @@ -1,5 +1,8 @@ use super::instance::Instance; -use super::*; +use super::{ + Class, ComPtr, ComWrapper, IComponentTrait, IEditControllerTrait, IPlugFrameTrait, IPlugViewTrait, Mutex, Ordering, PoisonError, STATE_MAGIC, + c_void, ok, read_c16, sb, sv, window, +}; // ---- editor (IPlugView) -------------------------------------------------------------------- diff --git a/crates/vst3-host/src/ffi/host.rs b/crates/vst3-host/src/ffi/host.rs index a2a2a216..5157e6b2 100644 --- a/crates/vst3-host/src/ffi/host.rs +++ b/crates/vst3-host/src/ffi/host.rs @@ -1,5 +1,8 @@ use super::module::tuid_bytes; -use super::*; +use super::{ + AtomicBool, Class, ComWrapper, EDIT_CAP, FUnknown, IComponentHandlerTrait, IHostApplicationTrait, Interface, Mutex, Ordering, PoisonError, + c_void, sb, sv, write_c16, +}; // ---- host-side COM objects ----------------------------------------------------------------- diff --git a/crates/vst3-host/src/ffi/instance.rs b/crates/vst3-host/src/ffi/instance.rs index 64e9d4e0..7bc23e2a 100644 --- a/crates/vst3-host/src/ffi/instance.rs +++ b/crates/vst3-host/src/ffi/instance.rs @@ -2,7 +2,11 @@ use super::editor::EditorLink; use super::host::HostContext; use super::module::Bundle; use super::process::{BusBuffers, EventList, MemoryStream, NoteEvent, ParamChanges}; -use super::*; +use super::{ + Arc, ComPtr, ComWrapper, EVENT_CAP, IAudioProcessorTrait, IComponentTrait, IConnectionPointTrait, IEditControllerTrait, IMidiMappingTrait, + IPluginBaseTrait, MAX_BUS_CHANNELS, MAX_BUSES, MAX_PARAMS, MAX_STATE_BYTES, Mutex, Ordering, PARAM_QUEUE_CAP, PITCH_BEND, STATE_MAGIC, Transport, + Vst3Error, ok, read_c16, sb, sv, +}; // ---- instances ----------------------------------------------------------------------------- @@ -32,7 +36,9 @@ pub(crate) struct Layout { } pub(super) fn apply_transport(c: &mut sv::ProcessContext, t: &Transport) { - use sv::ProcessContext_::StatesAndFlags_::*; + use sv::ProcessContext_::StatesAndFlags_::{ + kBarPositionValid, kContTimeValid, kPlaying, kProjectTimeMusicValid, kRecording, kTempoValid, kTimeSigValid, + }; let mut state = kTempoValid | kTimeSigValid | kProjectTimeMusicValid | kBarPositionValid | kContTimeValid; if t.playing { state |= kPlaying; @@ -375,18 +381,8 @@ impl Instance { /// `controls` (time, id, value) one point at their time when it falls in this call (the last /// one wins per parameter), and `notes` (sorted by time) have their times made relative to /// `offset`. - pub fn process( - &mut self, - frames: usize, - inputs: &mut BusBuffers, - outputs: &mut BusBuffers, - params: &[(u32, f64)], - controls: &[(u32, u32, f64)], - notes: &[NoteEvent], - offset: u32, - project_time: i64, - transport: Option<&Transport>, - ) -> Result<(), Vst3Error> { + pub fn process(&mut self, input: ProcessInput<'_>) -> Result<(), Vst3Error> { + let ProcessInput { frames, inputs, outputs, params, controls, notes, offset, project_time, transport } = input; if !self.active { return Err(Vst3Error::Process("not active".into())); } @@ -450,6 +446,18 @@ impl Instance { } } +pub(crate) struct ProcessInput<'a> { + pub frames: usize, + pub inputs: &'a mut BusBuffers, + pub outputs: &'a mut BusBuffers, + pub params: &'a [(u32, f64)], + pub controls: &'a [(u32, u32, f64)], + pub notes: &'a [NoteEvent], + pub offset: u32, + pub project_time: i64, + pub transport: Option<&'a Transport>, +} + impl Drop for Instance { fn drop(&mut self) { // Close any editor and cut its handles off before the controller goes away. diff --git a/crates/vst3-host/src/ffi/module.rs b/crates/vst3-host/src/ffi/module.rs index 574156b7..61e415b4 100644 --- a/crates/vst3-host/src/ffi/module.rs +++ b/crates/vst3-host/src/ffi/module.rs @@ -2,7 +2,11 @@ use super::editor::{EditorInner, EditorLink}; use super::host::HostContext; use super::instance::Instance; use super::process::{EventList, ParamChanges}; -use super::*; +use super::{ + Arc, AtomicBool, AtomicUsize, ComPtr, ComWrapper, Duration, EVENT_CAP, FUnknown, IComponentTrait, IConnectionPointTrait, IEditControllerTrait, + IPluginBaseTrait, IPluginFactory2Trait, IPluginFactoryTrait, Interface, MAX_CLASSES, ManuallyDrop, Mutex, OnceLock, Ordering, PARAM_QUEUE_CAP, + Path, PathBuf, PoisonError, TryLockError, Vst3Error, c_char, c_int, c_void, mpsc, ok, read_c8, sb, scan, sv, +}; // ---- loaded binaries ----------------------------------------------------------------------- diff --git a/crates/vst3-host/src/ffi/process.rs b/crates/vst3-host/src/ffi/process.rs index 9e978496..bd0e1edd 100644 --- a/crates/vst3-host/src/ffi/process.rs +++ b/crates/vst3-host/src/ffi/process.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + AtomicI32, AtomicU32, AtomicU64, Class, ComWrapper, IBStreamTrait, IEventListTrait, IParamValueQueueTrait, IParameterChangesTrait, + MAX_BUS_CHANNELS, MAX_BUSES, MAX_STATE_BYTES, Mutex, Ordering, PoisonError, c_void, sb, sv, +}; /// One parameter's points for one block. SoundCraft sends at most one point per block; a /// plugin writing output changes may add more, of which only the last is kept. diff --git a/crates/vst3-host/src/plugin.rs b/crates/vst3-host/src/plugin.rs index b2264a66..726ad98b 100644 --- a/crates/vst3-host/src/plugin.rs +++ b/crates/vst3-host/src/plugin.rs @@ -1,6 +1,6 @@ //! `Vst3Plugin`: a loaded VST3 instance behind the safe `soundcraft_dsp::Plugin` trait. -use crate::ffi::{AFTERTOUCH, BusBuffers, EVENT_CAP, EditorLink, HostContext, Instance, NoteEvent, PARAM_QUEUE_CAP, PITCH_BEND}; +use crate::ffi::{AFTERTOUCH, BusBuffers, EVENT_CAP, EditorLink, HostContext, Instance, NoteEvent, PARAM_QUEUE_CAP, PITCH_BEND, ProcessInput}; use soundcraft_dsp::{Plugin, PluginEditor, PluginInfo, Transport, Unit}; use std::collections::HashMap; use std::sync::Arc; @@ -324,17 +324,17 @@ impl Plugin for Vst3Plugin { let k = self.notes.iter().position(|e| e.time() >= end).unwrap_or(self.notes.len()); let offset = u32::try_from(start).unwrap_or(u32::MAX); let notes = self.notes.get(..k).unwrap_or(&[]); - let r = self.inst.process( - n, - &mut self.inputs, - &mut self.outputs, - &self.pending, - &self.controls, + let r = self.inst.process(ProcessInput { + frames: n, + inputs: &mut self.inputs, + outputs: &mut self.outputs, + params: &self.pending, + controls: &self.controls, notes, offset, - self.position, - self.transport.as_ref(), - ); + project_time: self.position, + transport: self.transport.as_ref(), + }); self.pending.clear(); self.notes.drain(..k); self.position = self.position.saturating_add(i64::try_from(n).unwrap_or(0)); diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 00000000..eb94ab74 --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,145 @@ +# Command-line tool + +`soundcraft-cli` runs SoundCraft without a window: it converts and inspects audio, runs engine +commands on a session, serves MCP, and calls a running app. Follows +[RFC-0012](https://github.com/storytold/craft-contrib/pull/18) (command-line conventions for the +Craft apps). + +`soundcraft-cli --help` and `soundcraft-cli --help` are the source of truth for +flags, values and defaults. This page does not repeat them. + +| Subcommand | What it does | +|---|---| +| `info` | Prints an audio file's format as JSON, or a `.scraft` session's summary | +| `convert` | Converts an audio file: resample, change the bit depth, normalize | +| `run` | Runs engine commands on a new, demo or saved session; can bounce, save and inspect | +| `script` | Runs a file of engine commands, one `ID JSON` per line | +| `commands` | Lists the engine commands | +| `describe` | Prints one engine command's details as JSON | +| `app` | Calls a running app's control channel (see [the control protocol](control-protocol.md)) | +| `mcp` | Serves MCP on stdin and stdout (see [the MCP guide](mcp.md)) | +| `parity` | Prints the parity report as markdown | +| `plugins` | Lists the built-in plugins | + +```sh +soundcraft-cli --version # also -V; there is no `version` subcommand +soundcraft-cli help convert # the same as `convert --help` +soundcraft-cli info session.scraft +soundcraft-cli convert in.wav out.flac --bit-depth 16 --rate 44100 +soundcraft-cli run --demo --cmd 'mix.volume={"track":"Kick","db":-6}' --bounce mix.wav +soundcraft-cli script steps.txt --demo --keep-going --save out.scraft +soundcraft-cli commands bounce +soundcraft-cli describe file.bounce_mix +``` + +## Output and exit codes + +Results go to standard output, as JSON where a program is meant to read them. `info` (on an audio +file), `describe`, `app` and the `--inspect` output of `run` and `script` pretty-print it; `--compact` +prints the same JSON on one line. The result lines of `run` and `script` (`ID: JSON`) and the +`--bounce` and `--save` results are always one line each. `commands`, `plugins`, `parity` and the +`.scraft` summary of `info` are text. Errors go to standard error as `error: `. `mcp` writes only the protocol +to standard output. + +| Exit code | Meaning | +|---|---| +| 0 | Success | +| 1 | The command failed (a missing file, an unknown engine command, an app that is not running) | +| 2 | Usage error | + +Arguments are checked before any work starts. These are usage errors (exit 2): a flag the +subcommand does not take (`--fromat`), a flag given twice (only `--cmd` and the two automation +root flags repeat), a value of the wrong type or out of range, flags that conflict +(`--dither` with `--no-dither`, `--connect` with a root flag or `--demo`) and a missing value. A value flag +never takes the next flag as its value: write a value that starts with `-` as `--bounce=-x.wav`, or +give a file as `./-x.wav`. File names that are not valid Unicode reach the command unchanged. +The engine writes bounces and saved sessions through commands whose parameters are JSON text, so +those paths must be valid Unicode (`--bounce`, `--save`, and the `--in` session with +`--in-place`: exit 1). + +An output that is one of the inputs is a usage error too, however the path is spelt (`a.wav`, +`./a.wav`, a symbolic or hard link): + +| Subcommand | Inputs | Outputs | `--in-place` lets an output replace | +|---|---|---|---| +| `convert` | `IN` | `OUT` | `IN` | +| `run` | `--in` | `--bounce`, `--save` | the `--in` session, by `--save` only | +| `script` | `FILE`, `--in` | `--bounce`, `--save` | the `--in` session, by `--save` only; never `FILE` | + +`run` and `script` take `--in-place` only with `--in`. A `--bounce` naming the `--in` session, and +`--bounce` and `--save` naming one file, are refused with or without `--in-place`. With +`--in-place`, an output that is a symbolic link to the input replaces the file it links to; the +link stays. An existing file that is not an input is replaced without asking. + +## Environment variables + +| Variable | Flag | Notes | +|---|---|---| +| `SOUNDCRAFT_CONTROL_PORT` | `app --port` (CLI), `--control` (desktop app) | A port or `host:port`, an IPv6 host in brackets (`[::1]:7979`). The desktop app takes the port of a loopback `host:port` (`127.0.0.1`, `localhost`). Its control server listens on `127.0.0.1` only, so it ignores another host from the variable, with a log warning, and starts no control server; given to `--control`, another host is a usage error | + +- A flag wins over its variable. +- An empty variable counts as unset. +- A bad value is a usage error that names the variable. +- ` --help` lists the variable. +- The automation roots (`--automation-read-root`, `--automation-write-root`) are flags only. No + variable grants file access. + +`SOUNDCRAFT_CONFIG_DIR`, `SOUNDCRAFT_NO_PREFS`, `SOUNDCRAFT_NO_SYSTEM_FONTS`, `SOUNDCRAFT_WAYLAND` +(Linux) and `RUST_LOG` configure the desktop app (see the [README](../README.md#logs) and +[the control protocol](control-protocol.md)), not the CLI. `soundcraft --help` lists them. +An empty variable counts as unset (RFC-0012 rule 1.7), except `SOUNDCRAFT_CONFIG_DIR`: empty means +no settings folder. + +`SOUNDCRAFT_NO_PREFS`, `SOUNDCRAFT_NO_SYSTEM_FONTS` and `SOUNDCRAFT_WAYLAND` are on/off switches with +one rule: `1/on/true/yes` is on, `0/off/false/no` is off (any case, spaces ignored), and unset or +blank is the default (off). A value that isn't one of these spellings is ignored (the default applies) and logs a warning that +names the variable. + +## Desktop app launch flags + +`soundcraft [OPTIONS] [FILES]...` takes the same strict parsing and exit codes. +`soundcraft --help` lists the flags: + +| Flag | Meaning | +|---|---| +| `FILES` | Sessions, audio and MIDI files to open; put `--` before a name that starts with `-` | +| `--demo` (alias `--sample`) | Start with the demo session | +| `--no-audio` | Don't open an audio device | +| `--control ` | Start the control server on this port (`0` picks a free port and prints it); falls back to `SOUNDCRAFT_CONTROL_PORT` | +| `--version`, `-V` | Print the version | +| `--help`, `-h` | Print the flags and the environment variables | + +## Man pages and completions + +The Linux `.deb` and `.rpm` packages install `man soundcraft-cli` (plus a page per subcommand, such +as `man soundcraft-cli-convert`) and completions for bash, zsh and fish. The Linux and FreeBSD +tarballs carry the same files. The pages list each flag's environment variable, as `--help` does. +The desktop app has neither. + +Without a package, generate them from a source checkout: + +```sh +cargo run -p soundcraft-cli --example man-and-completions -- out/ +``` + +`out/` then holds `soundcraft-cli.bash`, `_soundcraft-cli` (zsh), `soundcraft-cli.fish`, +`soundcraft-cli.elv` (elvish), `_soundcraft-cli.ps1` (PowerShell) and the `.1` man pages. Copy +`soundcraft-cli.bash` to `~/.local/share/bash-completion/completions/soundcraft-cli`, +`soundcraft-cli.fish` into `~/.config/fish/completions/`, `_soundcraft-cli` into a directory on +zsh's `$fpath`, and read a page with `man -l out/soundcraft-cli.1`. + +## RFC-0012 + +soundcraft-cli follows [RFC-0012](https://github.com/storytold/craft-contrib/pull/18): clap derive +types, thiserror errors, `run(args, out, err)` behind `main`, environment variables declared on +their flags, generated completions and man pages, tests that pin help and every usage error, no +output replacing an input without `--in-place`, and the ast-grep rules in `lint/ast-grep`. The shared automation flags are declared once in +`crates/automation/src/args.rs`. + +Rules not followed yet: + +- **JSON flag (rule 1.3).** `commands`, `plugins`, `parity` and the `info` summary of a `.scraft` + session print text and have no `--json` flag. Whether such listings need one is an open question + in the RFC itself. +- **`string-error` rule (section 3).** Its ast-grep rule is on for the CLI code and the shared flags, + not yet for the rest of the workspace. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6b0c4932..470d3912 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -7,7 +7,7 @@ input), and every command is reachable from: | Surface | How | |---|---| | Desktop app control channel | `soundcraft --control ` (`0` = pick a free port; printed as `SOUNDCRAFT_CONTROL_PORT=…`) | -| CLI against a running app | `soundcraft-cli app --port [JSON]` | +| CLI against a running app | `soundcraft-cli app --port [JSON]` (see [cli.md](cli.md)) | | Headless CLI | `soundcraft-cli run --demo --cmd 'mix.volume={"track":"Kick","db":-6}' --bounce out.wav` | | MCP (headless) | `soundcraft-cli mcp [--demo]` | | MCP (bridged to the app) | `soundcraft-cli mcp --connect ` | diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 4aa45323..d0b789de 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -1004,7 +1004,7 @@ Regression assertions: If unavailable, this is an explicit rollout blocker, not a pass. - FreeBSD: existing nightly workflow; compile/packaging can be checked, but native UI/IME/audio acceptance needs an actual FreeBSD environment (not provided here). -- Native control channel: use `--control 0` and `SOUNDCRAFT_NO_PREFS`/a scratch +- Native control channel: use `--control 0` and `SOUNDCRAFT_NO_PREFS=1`/a scratch `SOUNDCRAFT_CONFIG_DIR` for isolation; never arm/monitor/record in an automated UI run (`docs/control-protocol.md:22-25`). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 924546d8..4d9009be 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -4,9 +4,9 @@ Every format Pro Tools reads or writes, and ours. The Pro Tools list comes from the document types its bundle declares (`CFBundleDocumentTypes` in Info.plist: names only, nothing else read) and its -documented import/bounce options. Ours comes from `crates/audio-io` (`detect_format`, `decode`, -`ENCODE_EXTENSIONS`), `crates/engine/src/cmd/file.rs`, `crates/engine/src/score.rs`, -`crates/engine/src/clip_group_file.rs` and `crates/video`. +documented import/bounce options. Ours comes from `crates/audio-io` (`FileFormat::READ` and +`FileFormat::WRITE`, `detect_format`, `decode`), `crates/engine/src/cmd/file.rs`, +`crates/engine/src/score.rs`, `crates/engine/src/clip_group_file.rs` and `crates/video`. **File formats: ~40 % ready** (estimated: weighted by how often a Pro Tools user hits each row; session interchange carries a third of the weight and is at 0 %). Remaining ≈ 70–120 h. diff --git a/docs/mcp.md b/docs/mcp.md index 93496258..26d367fd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,7 +1,8 @@ # MCP server SoundCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so -Claude and other agents can make music with it. +Claude and other agents can make music with it. The server is the `mcp` subcommand of +`soundcraft-cli`, which [docs/cli.md](cli.md) describes. ```sh soundcraft-cli mcp # headless engine (no window, no audio device) diff --git a/docs/releasing.md b/docs/releasing.md index c277b792..b877757c 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -120,7 +120,9 @@ nor the portable zip needs the Visual C++ redistributable. `SOUNDCRAFT_REQUIRE_WINRES=1` so a missing resource compiler fails the build. - The script checks both PE headers: the machine type matches `-Arch`, `soundcraft.exe` is a GUI app (no console window) and `soundcraft-cli.exe` a console app. -- `soundcraft.wxs` (WiX v5) is a per-machine install into Program Files with an advertised Start +- `soundcraft.wxs` (WiX v5) is a dual-scope package (per-user by default into + `%LOCALAPPDATA%\Programs\ArtCraft\SoundCraft`, per-machine into `Program Files\ArtCraft\SoundCraft` (`Program Files (x86)` for the 32-bit build), + see `packaging/windows/INSTALLATION.md`) with an advertised Start Menu shortcut. SoundCraft becomes the default app for `.scraft` and is listed under *Open with* for `.wav`, `.aif`, `.aiff`, `.flac`, `.mp3`, `.mid` and `.midi`. It also registers App Paths (Win+R `soundcraft`). The MSI version is the numeric `X.Y.Z`; same-version upgrades let release @@ -138,7 +140,12 @@ Locally on Windows: `dotnet tool install -g wix --version 5.0.2`, then `packaging/linux/package.sh` stages one FHS tree and makes every format from it: both binaries, `ai.storyteller.soundcraft.desktop` (with `MimeType=` for sessions, WAV, AIFF, FLAC, MP3 and MIDI), hicolor icons from 16 px to 512 px plus a scalable SVG, AppStream metainfo, and a -shared-mime-info file declaring `application/x-soundcraft-session` (`*.scraft`). +shared-mime-info file declaring `application/x-soundcraft-session` (`*.scraft`), and +`soundcraft-cli`'s man pages and bash, zsh and fish completions. The `man-and-completions` example, +built with the binaries, writes those; a cross build runs it through `EMULATOR` and leaves them out +without one. The zsh completion is in `/usr/share/zsh/site-functions`, which Fedora's and +openSUSE's zsh read; the `.deb` also links it from `/usr/share/zsh/vendor-completions`, which +Debian's zsh reads instead. - **AppImage** (maintained `AppImage/appimagetool`, static runtime: no libfuse2 needed). Each embeds the update information @@ -168,7 +175,8 @@ Locally (on Linux): install nfpm, then `packaging/linux/package.sh` (or `--forma GitHub has no FreeBSD runners, so the `freebsd` job builds inside a FreeBSD 14.3 VM (`vmactions/freebsd-vm`, pinned by commit) and runs `packaging/freebsd/package.sh`, which stages -a `/usr/local`-style tree (binaries, desktop entry, MIME type, metainfo, icons, docs) as a +a `/usr/local`-style tree (binaries, desktop entry, MIME type, metainfo, icons, docs, and +`soundcraft-cli`'s man pages and shell completions) as a `.tar.gz`. Install with `tar -xzf soundcraft-*-freebsd-x86_64.tar.gz --strip-components 1 -C /usr/local`. `.github/workflows/freebsd.yml` builds and tests the workspace there on every push to `main`. diff --git a/lint/ast-grep/rule-tests/args-os-test.yml b/lint/ast-grep/rule-tests/args-os-test.yml new file mode 100644 index 00000000..2e384b48 --- /dev/null +++ b/lint/ast-grep/rule-tests/args-os-test.yml @@ -0,0 +1,19 @@ +id: args-os +valid: + - let code = soundcraft_cli::run(std::env::args_os().skip(1), &mut out, &mut err); + - "let args: Vec = env::args_os().collect();" + - | + use std::env::args_os; + fn main() { let a: Vec<_> = args_os().collect(); } + - | + fn args() -> Vec { Vec::new() } + fn main() { let a = args(); } +invalid: + - "let args: Vec = std::env::args().collect();" + - for a in env::args().skip(1) {} + - | + use std::env::args; + fn main() { let a: Vec = args().collect(); } + - | + use std::env::{args, var}; + fn main() { for a in args() {} } diff --git a/lint/ast-grep/rule-tests/clap-error-message-test.yml b/lint/ast-grep/rule-tests/clap-error-message-test.yml new file mode 100644 index 00000000..385d46e9 --- /dev/null +++ b/lint/ast-grep/rule-tests/clap-error-message-test.yml @@ -0,0 +1,13 @@ +id: clap-error-message +valid: + - cmd.error(ErrorKind::ArgumentConflict, UsageError::BridgeRoots) + - cmd.error(ErrorKind::ArgumentConflict, Conflict { a, b }) + - sub.error(kind, self) + - log.error("not a clap error") +invalid: + - cmd.error(ErrorKind::ArgumentConflict, "configure automation roots on the desktop app") + - sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires {transport}")) + - sub.error(ErrorKind::ArgumentConflict, BRIDGE_ROOTS) + - cmd.error(ErrorKind::InvalidValue, e.to_string()) + - cmd.error(ErrorKind::InvalidValue, String::from("bad value")) + - clap::Error::raw(ErrorKind::InvalidValue, "bad value") diff --git a/lint/ast-grep/rule-tests/clap-error-message-variable-test.yml b/lint/ast-grep/rule-tests/clap-error-message-variable-test.yml new file mode 100644 index 00000000..18d6e443 --- /dev/null +++ b/lint/ast-grep/rule-tests/clap-error-message-variable-test.yml @@ -0,0 +1,47 @@ +id: clap-error-message-variable +valid: + - | + fn conflict(cmd: &mut Command, a: String, b: String) -> clap::Error { + cmd.error(ErrorKind::ArgumentConflict, Conflict { a, b }) + } + - | + fn wrap(cmd: &mut Command, e: UsageError) -> clap::Error { + cmd.error(ErrorKind::ValueValidation, e) + } + - | + fn unrelated(cmd: &mut Command, e: UsageError) -> clap::Error { + let shown = format!("{e}"); + eprintln!("{shown}"); + cmd.error(ErrorKind::ValueValidation, e) + } + - | + fn cloned(cmd: &mut Command, e: &UsageError) -> clap::Error { + let owned = e.to_owned(); + cmd.error(ErrorKind::ValueValidation, owned) + } +invalid: + - | + fn conflict(cmd: &mut Command, a: &str, b: &str) -> clap::Error { + let message = format!("the argument '{a}' cannot be used with '{b}'"); + cmd.error(ErrorKind::ArgumentConflict, message) + } + - | + fn bad(cmd: &mut Command, e: UsageError) -> clap::Error { + let message = e.to_string(); + cmd.error(ErrorKind::ValueValidation, message) + } + - | + fn typed(cmd: &mut Command, flag: &str) -> clap::Error { + let message: String = flag.into(); + clap::Error::raw(ErrorKind::InvalidValue, message) + } + - | + fn literal(cmd: &mut Command) -> clap::Error { + let message = "bad value".to_owned(); + cmd.error(ErrorKind::InvalidValue, message) + } + - | + fn from(cmd: &mut Command) -> clap::Error { + let message = String::from("bad value"); + cmd.error(ErrorKind::InvalidValue, message) + } diff --git a/lint/ast-grep/rule-tests/string-error-test.yml b/lint/ast-grep/rule-tests/string-error-test.yml new file mode 100644 index 00000000..4f14197c --- /dev/null +++ b/lint/ast-grep/rule-tests/string-error-test.yml @@ -0,0 +1,14 @@ +id: string-error +valid: + - "fn parse(s: &str) -> Result { todo!() }" + - "fn name() -> Option { None }" + - "fn ok() -> Result { Ok(String::new()) }" + - Err(PortError::Range) + - Err(e) +invalid: + - "fn parse(s: &str) -> Result { todo!() }" + - "type R = Result<(), String>;" + - Err(format!("bad port {s}")) + - Err(e.to_string()) + - Err(String::from("bad port")) + - Err("bad port") diff --git a/lint/ast-grep/rules/args-os.yml b/lint/ast-grep/rules/args-os.yml new file mode 100644 index 00000000..a852cfcc --- /dev/null +++ b/lint/ast-grep/rules/args-os.yml @@ -0,0 +1,21 @@ +id: args-os +language: rust +severity: error +message: std::env::args() panics on an argument that isn't valid Unicode +note: | + Read std::env::args_os() and let clap parse the OsStrings, so a Latin-1 file name reaches the + command (or is a usage error) instead of aborting before anything is printed. +rule: + any: + - pattern: std::env::args() + - pattern: env::args() + # A bare args() only where the file imports std::env::args, not any function named args. + - all: + - pattern: args() + - inside: + kind: source_file + stopBy: end + has: + kind: use_declaration + stopBy: end + regex: std::env::(args\b|\{[^}]*\bargs\b) diff --git a/lint/ast-grep/rules/clap-error-message-variable.yml b/lint/ast-grep/rules/clap-error-message-variable.yml new file mode 100644 index 00000000..3f476be4 --- /dev/null +++ b/lint/ast-grep/rules/clap-error-message-variable.yml @@ -0,0 +1,35 @@ +id: clap-error-message-variable +language: rust +severity: error +message: clap error built from a string held in a variable +note: | + The message was built with format!, .to_string(), String::from or a literal's .to_owned() a + few lines up. Give it a variant on a + #[derive(thiserror::Error)] enum instead, with the parts as fields, and pass the variant. +rule: + # In this order: the call binds $MSG, then the function must hold a `let` of that same name. + all: + - any: + - pattern: $CMD.error($KIND, $MSG) + - pattern: Error::raw($KIND, $MSG) + - pattern: clap::Error::raw($KIND, $MSG) + - inside: + kind: function_item + stopBy: end + has: + stopBy: end + any: + - pattern: let $MSG = format!($$$); + - pattern: "let $MSG: String = $VAL;" + - pattern: let $MSG = $SRC.to_string(); + - pattern: let $MSG = String::from($$$); + # .to_owned() only on a string literal: on anything else it may clone a typed error. + - all: + - kind: let_declaration + - regex: '=\s*"(?s:.*)"\s*\.to_owned\(\)\s*;?$' + - has: + field: pattern + pattern: $MSG +constraints: + MSG: + kind: identifier diff --git a/lint/ast-grep/rules/clap-error-message.yml b/lint/ast-grep/rules/clap-error-message.yml new file mode 100644 index 00000000..e18b824b --- /dev/null +++ b/lint/ast-grep/rules/clap-error-message.yml @@ -0,0 +1,26 @@ +id: clap-error-message +language: rust +severity: error +message: clap error built from a string +note: | + Give the message a variant on a #[derive(thiserror::Error)] enum and pass the variant, e.g. + `cmd.error(ErrorKind::ArgumentConflict, UsageError::BridgeRoots)`. A string literal, format!, + .to_string() or a SCREAMING_CASE const keeps the message apart from the error's type. +rule: + any: + - pattern: $CMD.error($KIND, $MSG) + - pattern: Error::raw($KIND, $MSG) + - pattern: clap::Error::raw($KIND, $MSG) +constraints: + MSG: + any: + - kind: string_literal + - all: + - kind: macro_invocation + - regex: ^format! + - all: + - kind: identifier + - regex: ^[A-Z][A-Z0-9_]*$ + - all: + - kind: call_expression + - regex: \.(to_string|to_owned)\(\)$|^String::from\( diff --git a/lint/ast-grep/rules/string-error.yml b/lint/ast-grep/rules/string-error.yml new file mode 100644 index 00000000..e79b83d0 --- /dev/null +++ b/lint/ast-grep/rules/string-error.yml @@ -0,0 +1,21 @@ +id: string-error +language: rust +severity: error +message: String as an error type +note: | + Return a #[derive(thiserror::Error)] enum, so a caller can match on what failed and the + messages live with their variants. +rule: + any: + - pattern: + context: type T = Result<$OK, String>; + selector: generic_type + - pattern: Err(format!($$$)) + - pattern: Err($S.to_string()) + - pattern: Err(String::from($$$)) + - all: + - pattern: Err($S) + - has: + kind: arguments + has: + kind: string_literal diff --git a/lint/ast-grep/sgconfig.yml b/lint/ast-grep/sgconfig.yml new file mode 100644 index 00000000..9c94bd0a --- /dev/null +++ b/lint/ast-grep/sgconfig.yml @@ -0,0 +1,6 @@ +# Structural rules for the command-line code (RFC-0012), run by .github/workflows/ast-grep.yml. +# Each rule in rules/ has its cases in rule-tests/, which CI checks before the scan. +ruleDirs: + - rules +testConfigs: + - testDir: rule-tests diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 9ec31a55..98d86199 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -2,8 +2,8 @@ # Build and package SoundCraft for FreeBSD: # # $DIST/soundcraft--freebsd-x86_64.tar.gz a /usr/local-style tree: -# soundcraft--freebsd-x86_64/{bin, share/applications, share/icons, share/mime, -# share/metainfo, share/doc/soundcraft} +# soundcraft--freebsd-x86_64/{bin, man/man1, share/applications, share/icons, +# share/mime, share/metainfo, share/doc/soundcraft, share/{bash-completion,zsh,fish}} # # Install by copying the tree's contents into /usr/local, e.g. # tar -xzf soundcraft-*-freebsd-x86_64.tar.gz --strip-components 1 -C /usr/local @@ -55,8 +55,16 @@ BASENAME="soundcraft-$VERSION-freebsd-$ARCH" echo "==> SoundCraft $VERSION for FreeBSD $ARCH" +# The man-and-completions example is built with the binaries: it writes soundcraft-cli's man pages +# and shell completions below. A cross build's example cannot run here, so it is built again for +# this machine (the pages and completions do not depend on the target). if [[ "$SKIP_BUILD" = 0 ]]; then - (cd "$ROOT" && cargo build --release --locked -p soundcraft -p soundcraft-cli) + (cd "$ROOT" && cargo build --release --locked -p soundcraft -p soundcraft-cli \ + --bins --example man-and-completions) + if [[ -n "${CARGO_BUILD_TARGET:-}" ]]; then + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p soundcraft-cli \ + --example man-and-completions) + fi fi # Cargo puts a cross build under target//release. BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release" @@ -76,6 +84,20 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$SOUNDCRAFT_BUILD_DATE/g" \ "$LINUX/$APP_ID.metainfo.xml.in" >"$STAGE/share/metainfo/$APP_ID.metainfo.xml" cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/soundcraft" +# soundcraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above. +CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" +if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is missing: build it with the binaries (without --skip-build)" >&2 + exit 1 +fi +"$CLI_DOCS" "$WORK/cli-docs" +mkdir -p "$STAGE/man/man1" "$STAGE/share/bash-completion/completions" \ + "$STAGE/share/zsh/site-functions" "$STAGE/share/fish/vendor_completions.d" +install -m 644 "$WORK"/cli-docs/*.1 "$STAGE/man/man1/" +install -m 644 "$WORK/cli-docs/soundcraft-cli.bash" "$STAGE/share/bash-completion/completions/soundcraft-cli" +install -m 644 "$WORK/cli-docs/_soundcraft-cli" "$STAGE/share/zsh/site-functions/_soundcraft-cli" +install -m 644 "$WORK/cli-docs/soundcraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/soundcraft-cli.fish" # ---- .tar.gz ------------------------------------------------------------------------------------- tar -C "$WORK" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index c9f2eb78..55f040e6 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -69,6 +69,12 @@ contents: - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree + # Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and + # openSUSE's do (its debian/rules sets --enable-additional-fpath). + - src: /usr/share/zsh/site-functions/_soundcraft-cli + dst: /usr/share/zsh/vendor-completions/_soundcraft-cli + type: symlink + packager: deb scripts: postinstall: packaging/linux/postinst.sh diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index f27357be..aa4d577a 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -16,7 +16,8 @@ # # Cross-compiling (CI's linux-riscv64 job, tar.gz only): set CROSS_ARCH (riscv64), CROSS_TARGET # (the Rust target), CROSS_COMPILE (the binutils prefix, for strip) and optionally EMULATOR -# (e.g. qemu-riscv64) to smoke-test the CLI. +# (e.g. qemu-riscv64) to smoke-test the CLI and run the example that writes its man pages and +# completions. set -euo pipefail # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" @@ -29,7 +30,7 @@ while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; - -h | --help) sed -n '2,19p' "$0"; exit 0 ;; + -h | --help) sed -n '2,20p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac done @@ -46,11 +47,15 @@ BASENAME="soundcraft-$VERSION-linux-$ARCH" echo "==> SoundCraft $VERSION for Linux $ARCH ($FORMATS)" +# The man-and-completions example is built with the binaries: it writes soundcraft-cli's man pages +# and shell completions below. if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then - (cd "$ROOT" && cargo build --release --locked -p soundcraft -p soundcraft-cli --target "$CROSS_TARGET") + (cd "$ROOT" && cargo build --release --locked -p soundcraft -p soundcraft-cli \ + --bins --example man-and-completions --target "$CROSS_TARGET") else - (cd "$ROOT" && cargo build --release --locked -p soundcraft -p soundcraft-cli) + (cd "$ROOT" && cargo build --release --locked -p soundcraft -p soundcraft-cli \ + --bins --example man-and-completions) fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" @@ -71,6 +76,28 @@ mkdir -p "$STAGE/usr/share/icons" cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/usr/share/icons/" mkdir -p "$STAGE/usr/share/doc/soundcraft" copy_docs "$STAGE/usr/share/doc/soundcraft" +# soundcraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above. A cross build runs it through $EMULATOR, like the --version check at the +# end, and leaves them out without one. zsh reads site-functions on Fedora and openSUSE; the deb +# also links the completion into Debian's vendor-completions (nfpm.yaml). +CLI_DOCS="$BIN/examples/man-and-completions" +if [[ -n "${CROSS_TARGET:-}" ]] && [[ -z "${EMULATOR:-}" ]]; then + warn "no EMULATOR to run the $CROSS_TARGET build, so soundcraft-cli's man pages and completions are left out" +else + if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is missing: build it with the binaries (without --skip-build)" >&2 + exit 1 + fi + if [[ -n "${CROSS_TARGET:-}" ]]; then + "$EMULATOR" "$CLI_DOCS" "$WORK/cli-docs" + else + "$CLI_DOCS" "$WORK/cli-docs" + fi + install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1 + install -Dm644 "$WORK/cli-docs/soundcraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/soundcraft-cli" + install -Dm644 "$WORK/cli-docs/_soundcraft-cli" "$STAGE/usr/share/zsh/site-functions/_soundcraft-cli" + install -Dm644 "$WORK/cli-docs/soundcraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/soundcraft-cli.fish" +fi if command -v desktop-file-validate >/dev/null; then desktop-file-validate "$STAGE/usr/share/applications/$APP_ID.desktop" @@ -98,7 +125,11 @@ if has deb || has rpm; then export VERSION export NFPM_ARCH="$DEB_ARCH" # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + # Without the completions (a cross build with no EMULATOR) the deb's zsh symlink would dangle, + # so its entry is dropped too. + DROP_ZSH_LINK= + [[ -f "$STAGE/usr/share/zsh/site-functions/_soundcraft-cli" ]] || DROP_ZSH_LINK='\|^ - src: /usr/share/zsh/site-functions/|,/packager: deb/d;' + sed "${DROP_ZSH_LINK}s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done diff --git a/packaging/windows/INSTALLATION.md b/packaging/windows/INSTALLATION.md new file mode 100644 index 00000000..982a5b42 --- /dev/null +++ b/packaging/windows/INSTALLATION.md @@ -0,0 +1,35 @@ +# Windows installation policy checks + +New installations default to the current account under `Programs\ArtCraft\`. +The first setup page offers installation for everyone. Scope is selected before duplicate +checks and directory costing. An update uses the existing context's remembered exact folder; +`INSTALLFOLDER` supplied explicitly is never replaced. It is a secure MSI property so the +chosen folder reaches the elevated installer. Silent machine updates pass `ALLUSERS=1`. +A cross-context copy is refused; changing context means uninstalling the old copy first. + +App registration follows the selected context. Existing optional shortcuts and file-handler +choices stay app-owned. No new cleanup operation or model/settings migration is introduced. +Packaged resources remain package-owned; separately downloaded shared models are not caches +and are outside this installer's ownership. + +## Repeatable metadata tests + +On Windows with WiX 5.0.2 and its matching UI/Util extensions: + +```powershell +./packaging/windows/test-install-policy.ps1 -OutputDirectory ./target/install-policy-tests +``` + +The script builds x64, x86 and arm64 packages with deliberately non-executable payloads. It +uses the actual package source and compiled database. A safe Windows Installer session checks +24 scope/registration/maintenance cases, remembered and explicit custom folders, sequencing, +upgrade identity and the original registration inventory recorded in `install-policy.json`. +The release packaging script runs the compiled checker before signing. Packaging CI runs the +small fixture builds without compiling the Rust application. + +Never install or distribute the `NOT-INSTALLABLE.msi` fixtures as an app. Passing these checks +does not prove real installation, elevation, legacy-version upgrades, registry writes, optional +shortcut/menu behaviour, cancellation, rollback or uninstall. Those still require the real +payload in an authorised clean Windows test environment. Cross-architecture metadata is not +execution evidence on those architectures. Existing open installer/association PRs must be +reconciled before publication. Nothing here changes macOS/Linux native packaging conventions. diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 new file mode 100644 index 00000000..cc9416e9 --- /dev/null +++ b/packaging/windows/check-install-policy.ps1 @@ -0,0 +1,296 @@ +<# +.SYNOPSIS + Check the compiled installation policy without installing any product. +.DESCRIPTION + Uses Windows Installer's safe session (OpenPackage option 1). Only property-setting custom + actions are exercised. No AppSearch, install, repair, removal or file-writing action runs. +#> +param([Parameter(Mandatory = $true)] [string] $MsiPath) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$policy = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'install-policy.json') | ConvertFrom-Json +function Read-Rows($Database, [string] $Sql, [int] $Columns) { + $view = $Database.OpenView($Sql) + try { + [void]$view.Execute() + while ($null -ne ($record = $view.Fetch())) { + try { + $values = @(for ($i = 1; $i -le $Columns; $i++) { + $record.GetType().InvokeMember('StringData', 'GetProperty', $null, $record, @($i)) + }) + ,$values + } finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($record) } + } + } finally { + [void]$view.Close() + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($view) + } +} +function Set-SessionProperty($Session, [string] $Name, [string] $Value) { + [void]$Session.GetType().InvokeMember('Property', 'SetProperty', $null, $Session, @($Name, $Value)) +} +function Get-SessionProperty($Session, [string] $Name) { + $Session.GetType().InvokeMember('Property', 'GetProperty', $null, $Session, @($Name)) +} +function Get-PackageTemplate($Database) { + # Summary information property 7 is the platform: "Intel;1033", "x64;1033" or "Arm64;1033". + $summary = $Database.GetType().InvokeMember('SummaryInformation', 'GetProperty', $null, $Database, @(0)) + try { [string]$summary.GetType().InvokeMember('Property', 'GetProperty', $null, $summary, @(7)) } + finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($summary) } +} +$installer = $null; $database = $null; $session = $null +try { + $installer = New-Object -ComObject WindowsInstaller.Installer + $file = (Resolve-Path -LiteralPath $MsiPath).Path + $database = $installer.OpenDatabase($file, 0) + $session = $installer.OpenPackage($file, 1) + $properties = @{} + foreach ($row in (Read-Rows $database 'SELECT `Property`, `Value` FROM `Property`' 2)) { $properties[$row[0]] = $row[1] } + $secureProperties = @($properties['SecureCustomProperties'] -split ';') + if ('INSTALLFOLDER' -notin $secureProperties) { + throw 'The selected installation folder must survive elevation (secure INSTALLFOLDER).' + } + if ($policy.mode -eq 'perUser') { + if ($properties.ContainsKey('ALLUSERS')) { throw 'Launcher must remain per-user; machine self-update is not part of this change.' } + if ($properties['UpgradeCode'].Trim('{}') -ne $policy.upgradeCode) { throw 'Launcher upgrade identity changed.' } + $dirs = @{} + foreach ($row in (Read-Rows $database 'SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`' 3)) { $dirs[$row[0]] = @($row[1],$row[2]) } + if ($dirs['INSTALLFOLDER'][0] -ne 'CraftSuiteFolder' -or $dirs['CraftSuiteFolder'][1] -ne 'ArtCraft' -or + $dirs['CraftSuiteFolder'][0] -ne 'LocalProgramsFolder' -or $dirs['LocalProgramsFolder'][0] -ne 'LocalAppDataFolder') { + throw 'Launcher new-install folder must be under the per-user ArtCraft suite root.' + } + foreach ($explicit in @('', 'F:\Chosen exact launcher')) { + Set-SessionProperty $session 'PREVIOUSINSTALLFOLDER' 'E:\Existing exact launcher' + Set-SessionProperty $session 'INSTALLFOLDER' $explicit + $row = @(Read-Rows $database 'SELECT `Condition` FROM `InstallUISequence` WHERE `Action` = ''CraftRestoreLauncherFolder''' 1)[0] + if ($session.EvaluateCondition($row[0]) -eq 1) { + if ($session.DoAction('CraftRestoreLauncherFolder') -ne 1) { throw 'Launcher restore action failed.' } + } + $expected = if ($explicit) { $explicit } else { 'E:\Existing exact launcher' } + if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Launcher custom or existing path was lost.' } + } + $rows = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) + if (@($rows | Where-Object { $_[0] -ne '1' }).Count) { throw 'Launcher registration must stay under the current account.' } + foreach ($entry in $policy.registry) { + if (@($rows | Where-Object { $_[0] -eq $entry[0] -and $_[1] -eq $entry[1] -and $_[2] -eq $entry[2] -and $_[3] -eq $entry[3] }).Count -ne 1) { + throw 'Launcher registration or shortcut preference changed unexpectedly.' + } + } + Write-Output 'PASS ArtCraft Launcher: per-user scope, suite folder, remembered/custom paths and existing registration. No installation performed.' + return + } + if ($properties['ALLUSERS'] -ne '2' -or $properties['MSIINSTALLPERUSER'] -ne '1') { + throw 'Policy regression: new packages must default to the per-user dual-scope context.' + } + if ($properties['UpgradeCode'].Trim('{}') -ne $policy.upgradeCode) { throw 'The existing upgrade identity must not change.' } + $directories = @{} + foreach ($row in (Read-Rows $database 'SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`' 3)) { + $directories[$row[0]] = @($row[1], $row[2]) + } + if ($directories['INSTALLFOLDER'][0] -ne 'CraftSuiteFolder' -or + $directories['CraftSuiteFolder'][1] -ne 'ArtCraft') { throw 'Expected the app under the ArtCraft suite folder.' } + $programs = $directories['CraftSuiteFolder'][0] + if ($programs -eq 'ProgramFiles6432Folder') { $programs = $directories[$programs][0] } + if ($programs -notin 'ProgramFilesFolder', 'ProgramFiles64Folder') { + throw 'Use Windows Installer native folder redirection, not a hard-coded profile path.' + } + $guards = @(Read-Rows $database 'SELECT `Condition`, `Description` FROM `LaunchCondition`' 2 | + Where-Object { $_[0] -match 'CRAFT_(USER|MACHINE)_DIR' }) + if ($guards.Count -ne 2) { throw 'Expected both duplicate-installation guards.' } + $cases = 0 + foreach ($scope in @('', '2', '1')) { + foreach ($user in @('', 'D:\Existing user app')) { + foreach ($machine in @('', 'E:\Existing machine app')) { + foreach ($installed in @('', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'Installed' $installed + Set-SessionProperty $session 'CRAFT_USER_DIR' $user + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' $machine + $allowed = $true + foreach ($guard in $guards) { + $value = $session.EvaluateCondition($guard[0]) + if ($value -notin 0, 1) { throw 'Invalid duplicate guard.' } + if ($value -eq 0) { $allowed = $false } + } + $opposite = if ($scope -eq '1') { $user } else { $machine } + $expected = [bool]$installed -or -not [bool]$opposite + if ($allowed -ne $expected) { throw "Scope regression: ALLUSERS='$scope', user=$([bool]$user), machine=$([bool]$machine), maintenance=$([bool]$installed)." } + $cases++ + } + } + } + } + # Execute the actual authored type-51 actions in a safe session, not copied resolver logic. + foreach ($scope in @('', '2', '1')) { + foreach ($explicit in @('', 'F:\Chosen exact app')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'INSTALLFOLDER' $explicit + Set-SessionProperty $session 'CRAFT_USER_DIR' 'D:\Existing user app' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' + $action = if ($scope -eq '1') { 'CraftRestoreMachineFolder' } else { 'CraftRestoreUserFolder' } + # Evaluate the compiled condition, so the test exercises it instead of calling the action directly. + $restore = @(Read-Rows $database ('SELECT `Condition` FROM `InstallExecuteSequence` WHERE `Action` = ''{0}''' -f $action) 1)[0] + $selected = $session.EvaluateCondition($restore[0]) -eq 1 + if ($selected -eq [bool]$explicit) { throw "$action must run only when no folder was supplied (condition: $($restore[0]))." } + if ($selected -and $session.DoAction($action) -ne 1) { throw 'Remembered-folder property action failed.' } + $expected = if ($explicit) { $explicit } elseif ($scope -eq '1') { 'E:\Existing machine app' } else { 'D:\Existing user app' } + if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Custom or remembered folder was not preserved.' } + } + } + $ui = @{} + foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallUISequence`' 2)) { $ui[$row[0]] = [int]$row[1] } + if (-not ($ui['AppSearch'] -lt $ui['CraftPreferMachineScope'] -and + $ui['CraftPreferMachineScope'] -lt $ui['CraftScopeDlg'] -and + $ui['CraftScopeDlg'] -lt $ui['FindRelatedProducts'] -and + $ui['FindRelatedProducts'] -lt $ui['LaunchConditions'] -and + $ui['CraftScopeDlg'] -lt $ui['CraftRestoreUserFolder'] -and $ui['CraftRestoreUserFolder'] -lt $ui['CostInitialize'])) { + throw 'Scope must be chosen after AppSearch and before FindRelatedProducts, launch checks and costing.' + } + # Windows Installer resolves Program Files for the context it started in, before the wizard's scope choice. + # The wizard therefore sets the new-install folder itself, and only in the wizard. + $defaults = @(Read-Rows $database 'SELECT `Action`, `Sequence`, `Condition` FROM `InstallUISequence`' 3 | Where-Object { $_[0] -like 'CraftDefault*' }) + if ($defaults.Count -lt 2) { throw 'The wizard must set the new-install folder after the scope page; Program Files is resolved before the choice.' } + foreach ($row in $defaults) { + if (-not ($ui['CraftScopeDlg'] -lt [int]$row[1] -and [int]$row[1] -lt $ui['CostInitialize'])) { throw "$($row[0]) must run after the scope page and before costing." } + } + if (@(Read-Rows $database 'SELECT `Action` FROM `InstallExecuteSequence`' 1 | Where-Object { $_[0] -like 'CraftDefault*' }).Count) { + throw 'Silent installs must not use the wizard-only default folder actions.' + } + # The machine default comes from the environment of the package architecture, not from a folder name. + # x86 packages use Program Files (x86) on 64-bit Windows; x64 and Arm64 packages use the 64-bit root. + $machineRoot = if ((Get-PackageTemplate $database) -match '^Intel') { + if (Get-SessionProperty $session 'VersionNT64') { ${env:ProgramFiles(x86)} } else { $env:ProgramFiles } + } elseif ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles } + $machineFolder = (Join-Path $machineRoot "ArtCraft\$($policy.name)") + '\' + foreach ($scope in @('1', '')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'INSTALLFOLDER' '' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' '' + Set-SessionProperty $session 'CRAFT_USER_DIR' '' + foreach ($row in @($defaults | Sort-Object { [int]$_[1] })) { + if ($session.EvaluateCondition($row[2]) -eq 1 -and $session.DoAction($row[0]) -ne 1) { throw "$($row[0]) failed." } + } + $folder = Get-SessionProperty $session 'INSTALLFOLDER' + $wanted = if ($scope -eq '1') { $machineFolder } else { (Join-Path $env:LOCALAPPDATA "Programs\ArtCraft\$($policy.name)") + '\' } + if ($folder -ine $wanted) { throw "Wizard default folder for ALLUSERS='$scope' is '$folder', expected '$wanted'." } + } + $execute = @{} + foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallExecuteSequence`' 2)) { $execute[$row[0]] = [int]$row[1] } + foreach ($action in @('CraftRestoreUserFolder','CraftRestoreMachineFolder')) { + if (-not ($execute['AppSearch'] -lt $execute[$action] -and $execute[$action] -lt $execute['CostInitialize'])) { + throw 'Silent updates must restore the folder before directory costing.' + } + } + foreach ($resolver in @('CraftUFromLegacyExe','CraftMFromLegacyExe')) { + if (-not ($execute['AppSearch'] -lt $execute[$resolver] -and $execute[$resolver] -lt $execute['LaunchConditions'])) { + throw 'Both legacy folder resolvers must run after AppSearch and before the launch checks.' + } + } + # Switching the first-page choice must reset BOTH properties, including a back-and-forth change. + $events = @(Read-Rows $database 'SELECT `Event`, `Argument`, `Condition`, `Ordering` FROM `ControlEvent` WHERE `Dialog_` = ''CraftScopeDlg'' AND `Control_` = ''Next'' ORDER BY `Ordering`' 4) + # Model the full-UI upgrade entry with an existing machine-wide copy. Run + # the actual preference action, then the compiled Next events before discovery. + Set-SessionProperty $session 'ALLUSERS' '2' + Set-SessionProperty $session 'CRAFT_SCOPE' 'user' + Set-SessionProperty $session 'CRAFT_USER_DIR' '' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' + $preference = @(Read-Rows $database 'SELECT `Condition` FROM `InstallUISequence` WHERE `Action` = ''CraftPreferMachineScope''' 1)[0] + if ($session.EvaluateCondition($preference[0]) -ne 1 -or $session.DoAction('CraftPreferMachineScope') -ne 1 -or + (Get-SessionProperty $session 'CRAFT_SCOPE') -ne 'machine') { + throw 'Full-UI machine upgrades must initially select the existing machine context.' + } + foreach ($choice in @('machine','user','machine','user')) { + Set-SessionProperty $session 'CRAFT_SCOPE' $choice + foreach ($event in $events) { + if ($event[0] -notmatch '^\[([^\]]+)\]$') { continue } + $property = $Matches[1] + if ($session.EvaluateCondition($event[2]) -eq 1) { + Set-SessionProperty $session $property $(if ($event[1] -eq '{}') { '' } else { $event[1] }) + } + } + $allUsers = Get-SessionProperty $session 'ALLUSERS' + $perUser = Get-SessionProperty $session 'MSIINSTALLPERUSER' + if (($choice -eq 'machine' -and ($allUsers -ne '1' -or $perUser)) -or + ($choice -eq 'user' -and ($allUsers -or $perUser -ne '1'))) { + throw 'Scope selector does not reset the requested installation context.' + } + } + $actions = @(Read-Rows $database 'SELECT `Action`, `Source`, `Target`, `Type` FROM `CustomAction`' 4) + $savedOptions = @($actions | Where-Object { $_[0] -match '^CraftLoadOption[0-9]+M$' }) + foreach ($option in $savedOptions) { + if ([int]$option[3] -ne 51) { throw 'Saved-option test may run only property-setting actions.' } + $number = [regex]::Match($option[0], '[0-9]+').Value + foreach ($scope in @('2','1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session "CRAFT_OPTION_${number}_M" 'saved-machine-choice' + Set-SessionProperty $session "CRAFT_OPTION_${number}_U" 'saved-user-choice' + Set-SessionProperty $session $option[1] '' + $action = "CraftLoadOption$number" + $(if ($scope -eq '1') { 'M' } else { 'U' }) + if ($session.DoAction($action) -ne 1) { throw 'Saved-option property action failed.' } + $expected = if ($scope -eq '1') { 'saved-machine-choice' } else { 'saved-user-choice' } + if ((Get-SessionProperty $session $option[1]) -ne $expected) { throw 'Saved installer choices leaked across contexts.' } + } + } + # Follow the compiled control conditions, not the source's intended appearance. + $controls = @(Read-Rows $database 'SELECT `Dialog_`, `Control`, `Type`, `Attributes`, `Text` FROM `Control`' 5) + $conditions = @() + if (@(Read-Rows $database 'SELECT `Name` FROM `_Tables` WHERE `Name` = ''ControlCondition''' 1).Count) { + $conditions = @(Read-Rows $database 'SELECT `Dialog_`, `Control_`, `Action`, `Condition` FROM `ControlCondition`' 4) + } + function Test-ControlVisible($Control) { + $visible = ([int]$Control[3] -band 1) -ne 0 + foreach ($condition in $conditions) { + if ($condition[0] -eq $Control[0] -and $condition[1] -eq $Control[1] -and $session.EvaluateCondition($condition[3]) -eq 1) { + if ($condition[2] -eq 'Show') { $visible = $true } + if ($condition[2] -eq 'Hide') { $visible = $false } + } + } + return $visible + } + foreach ($button in @($controls | Where-Object { $_[0] -in 'InstallWelcome','InstallMaintenance','DesktopShortcutDlg' -and ([int]$_[3] -band 8388608) -ne 0 })) { + $plain = @($controls | Where-Object { $_[0] -eq $button[0] -and $_[1] -eq ($button[1] + 'User') }) + if ($plain.Count -ne 1 -or ([int]$plain[0][3] -band 8388608)) { throw 'Scope-aware buttons need an unshielded per-user counterpart.' } + foreach ($scope in @('', '2', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + if ((Test-ControlVisible $button) -ne ($scope -eq '1') -or (Test-ControlVisible $plain[0]) -ne ($scope -ne '1')) { + throw 'The elevation shield must follow the selected scope.' + } + } + $dialog = $button[0]; $shieldId = $button[1]; $plainId = $plain[0][1] + $shieldEvents = @(Read-Rows $database "SELECT ``Event``, ``Argument``, ``Condition``, ``Ordering`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$shieldId' ORDER BY ``Ordering``" 4 | ForEach-Object { $_ -join '|' }) + $plainEvents = @(Read-Rows $database "SELECT ``Event``, ``Argument``, ``Condition``, ``Ordering`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$plainId' ORDER BY ``Ordering``" 4 | ForEach-Object { $_ -join '|' }) + if (($shieldEvents -join "`n") -ne ($plainEvents -join "`n")) { throw 'Per-user and machine buttons must perform the same operation.' } + } + foreach ($scope in @('', '2', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + foreach ($text in @($controls | Where-Object { $_[4] -like '*for all users*' })) { + if ((Test-ControlVisible $text) -ne ($scope -eq '1')) { throw 'The welcome-page scope text must follow the selected scope.' } + } + } + if ($policy.id -in 'deckcraft','filmcraft','soundcraft') { + foreach ($route in @(@('WelcomeDlg','Next','InstallDirDlg'),@('InstallDirDlg','Back','WelcomeDlg'))) { + $dialog = $route[0]; $control = $route[1] + $routes = @(Read-Rows $database "SELECT ``Argument``, ``Condition`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$control' AND ``Event`` = 'NewDialog' ORDER BY ``Ordering``" 2) + Set-SessionProperty $session 'Installed' '' + $destination = '' + foreach ($event in $routes) { if ($session.EvaluateCondition($event[1]) -eq 1) { $destination = $event[0] } } + if ($destination -ne $route[2]) { throw 'Skipping the licence page must work in both navigation directions.' } + } + } + $registry = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) + if (@($registry | Where-Object { $_[0] -in '1', '2' }).Count) { throw 'Registration must follow the selected context, not force HKCU or HKLM.' } + if (@($registry | Where-Object { $_[0] -eq '0' -and $_[1] -match '^Software\\Classes(\\|$)' }).Count) { + throw 'HKCR keys must be relative to Classes.' + } + foreach ($entry in $policy.registry) { + $found = @($registry | Where-Object { $_[0] -eq $entry[0] -and $_[1] -eq $entry[1] -and $_[2] -eq $entry[2] -and $_[3] -eq $entry[3] }) + if ($found.Count -ne 1) { throw "Lost or changed registration: $($entry[1]) / $($entry[2])" } + } + $installDir = @($registry | Where-Object { $_[0] -eq '-1' -and $_[1] -eq "Software\$($policy.name)" -and $_[2] -eq 'InstallDir' -and $_[3] -eq '[INSTALLFOLDER]' }) + if ($installDir.Count -ne 1) { throw 'A context-sensitive installation-folder record is required.' } + Write-Output "PASS $($policy.name): $cases scope cases, folder preservation, action sequencing and registry contract. No installation performed." +} finally { + foreach ($com in @($session, $database, $installer)) { + if ($null -ne $com) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($com) } + } +} diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json new file mode 100644 index 00000000..e8d7966e --- /dev/null +++ b/packaging/windows/install-policy.json @@ -0,0 +1,141 @@ +{ + "id": "soundcraft", + "name": "SoundCraft", + "upgradeCode": "EE53D3E5-D0AE-40F9-808D-9417FDEBF61A", + "sources": [ + "soundcraft.wxs" + ], + "icon": "assets/app-icon/soundcraft.ico", + "localization": [], + "extensions": [ + "UI" + ], + "payloads": [ + "NOTICE", + "soundcraft-cli.exe", + "soundcraft.exe" + ], + "registry": [ + [ + "-1", + "Software\\Classes\\SoundCraft.Audio\\shell\\open\\command", + "", + "\"[#SoundcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Classes\\SoundCraft.Midi\\shell\\open\\command", + "", + "\"[#SoundcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Classes\\.wav\\OpenWithProgids", + "SoundCraft.Audio", + "" + ], + [ + "-1", + "Software\\Classes\\.aif\\OpenWithProgids", + "SoundCraft.Audio", + "" + ], + [ + "-1", + "Software\\Classes\\.aiff\\OpenWithProgids", + "SoundCraft.Audio", + "" + ], + [ + "-1", + "Software\\Classes\\.flac\\OpenWithProgids", + "SoundCraft.Audio", + "" + ], + [ + "-1", + "Software\\Classes\\.mp3\\OpenWithProgids", + "SoundCraft.Audio", + "" + ], + [ + "-1", + "Software\\Classes\\.mid\\OpenWithProgids", + "SoundCraft.Midi", + "" + ], + [ + "-1", + "Software\\Classes\\.midi\\OpenWithProgids", + "SoundCraft.Midi", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe", + "FriendlyAppName", + "SoundCraft" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\shell\\open\\command", + "", + "\"[#SoundcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".scraft", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".wav", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".aif", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".aiff", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".flac", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".mp3", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".mid", + "" + ], + [ + "-1", + "Software\\Classes\\Applications\\soundcraft.exe\\SupportedTypes", + ".midi", + "" + ], + [ + "-1", + "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\soundcraft.exe", + "", + "[#SoundcraftExe]" + ] + ], + "mode": "dualScope" +} diff --git a/packaging/windows/install-policy.wxi b/packaging/windows/install-policy.wxi new file mode 100644 index 00000000..3290313f --- /dev/null +++ b/packaging/windows/install-policy.wxi @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index bc274d2b..636e6f91 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -95,11 +95,14 @@ Copy-Item -LiteralPath (Join-Path $Root 'NOTICE') -Destination $Stage # ---- MSI --------------------------------------------------------------------------------------- $Msi = Join-Path $Dist "soundcraft-$Version-windows-$Arch.msi" +Invoke-Native 'WiX UI extension' { wix extension add -g WixToolset.UI.wixext/5.0.2 } Invoke-Native 'wix build' { - wix build (Join-Path $PSScriptRoot 'soundcraft.wxs') -arch $Arch ` + wix build (Join-Path $PSScriptRoot 'soundcraft.wxs') -arch $Arch -ext WixToolset.UI.wixext ` -d "Version=$MsiVersion" -d "BinDir=$Stage" -d "IconPath=$(Join-Path $Root 'assets\app-icon\soundcraft.ico')" ` -o $Msi } +# Check the compiled scope, path and registration contract before signing. +& (Join-Path $PSScriptRoot 'check-install-policy.ps1') -MsiPath $Msi # wix writes its debug symbols (.wixpdb) next to the MSI; keep them out of the release assets. Remove-Item -Force -ErrorAction SilentlyContinue ([IO.Path]::ChangeExtension($Msi, '.wixpdb')) & (Join-Path $PSScriptRoot 'sign.ps1') $Msi diff --git a/packaging/windows/soundcraft.wxs b/packaging/windows/soundcraft.wxs index 4fd708f3..f11ab553 100644 --- a/packaging/windows/soundcraft.wxs +++ b/packaging/windows/soundcraft.wxs @@ -1,27 +1,11 @@ - - - + + + - + @@ -31,13 +15,20 @@ - + + + + + + + + @@ -47,9 +38,7 @@ - + @@ -61,29 +50,30 @@ - + - - - - - - - - + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + diff --git a/packaging/windows/test-install-policy.ps1 b/packaging/windows/test-install-policy.ps1 new file mode 100644 index 00000000..d455d19d --- /dev/null +++ b/packaging/windows/test-install-policy.ps1 @@ -0,0 +1,54 @@ +<# +.SYNOPSIS + Build non-executable installer metadata fixtures; never install them. +#> +param( + [Parameter(Mandatory = $true)] [string] $OutputDirectory, + [ValidateSet('x64','x86','arm64')] [string[]] $Architectures = @('x64','x86','arm64') +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$policy = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'install-policy.json') | ConvertFrom-Json +[void](New-Item -ItemType Directory -Force -Path $OutputDirectory) +$output = (Resolve-Path -LiteralPath $OutputDirectory).Path +Add-Type -AssemblyName System.Drawing +foreach ($arch in $Architectures) { + $stage = Join-Path $output $arch + [void](New-Item -ItemType Directory -Force -Path $stage) + foreach ($name in $policy.payloads) { + $destination = Join-Path $stage $name + [void](New-Item -ItemType Directory -Force -Path ([IO.Path]::GetDirectoryName($destination))) + Set-Content -LiteralPath $destination -Encoding Ascii -Value 'NON-EXECUTABLE MSI METADATA TEST FIXTURE' + } + foreach ($folder in @('docs','models','notices')) { + $path = Join-Path $stage $folder + [void](New-Item -ItemType Directory -Force -Path $path) + Set-Content -LiteralPath (Join-Path $path "$folder-fixture.txt") -Value 'Metadata test fixture, not a user file or model.' + } + foreach ($model in @('metadata-one.rten','metadata-two.rten')) { + Set-Content -LiteralPath (Join-Path (Join-Path $stage 'models') $model) -Encoding Ascii -Value 'NON-EXECUTABLE MODEL METADATA FIXTURE' + } + foreach ($spec in @(@('banner.bmp',493,58),@('dialog.bmp',493,312))) { + $bitmap = [Drawing.Bitmap]::new($spec[1],$spec[2],[Drawing.Imaging.PixelFormat]::Format24bppRgb) + try { $bitmap.Save((Join-Path $stage $spec[0]),[Drawing.Imaging.ImageFormat]::Bmp) } + finally { $bitmap.Dispose() } + } + Set-Content -LiteralPath (Join-Path $stage 'licence.rtf') -Encoding Ascii -Value '{\rtf1 Metadata test fixture.}' + $sources = @($policy.sources | ForEach-Object { Join-Path $PSScriptRoot $_ }) + $msi = Join-Path $stage "$($policy.id)-NOT-INSTALLABLE.msi" + $extensions = @($policy.extensions | ForEach-Object { '-ext'; "WixToolset.$_.wixext" }) + & wix build @sources -arch $arch @extensions ` + -culture en-US -d 'Version=0.0.1' -d 'DisplayVersion=0.0.1-metadata-test' ` + -d "BinDir=$stage" -d "IconPath=$(Join-Path $root $policy.icon)" ` + -d "DocsDir=$(Join-Path $stage 'docs')" -d "ModelsDir=$(Join-Path $stage 'models')" ` + -d "AppNoticesDir=$(Join-Path $stage 'notices')" -d 'HasCraftFontLicences=1' -d 'HasCli=1' ` + -d "BannerBmp=$(Join-Path $stage 'banner.bmp')" -d "DialogBmp=$(Join-Path $stage 'dialog.bmp')" ` + -d "UiBannerBmp=$(Join-Path $stage 'banner.bmp')" -d "UiDialogBmp=$(Join-Path $stage 'dialog.bmp')" ` + -d "LicenseRtf=$(Join-Path $stage 'licence.rtf')" -o $msi @($policy.localization | ForEach-Object { '-loc'; Join-Path $PSScriptRoot $_ }) + if ($LASTEXITCODE -ne 0) { throw "WiX validation failed for $arch (exit $LASTEXITCODE)." } + $shell = (Get-Process -Id $PID).Path + & $shell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'check-install-policy.ps1') -MsiPath $msi + if ($LASTEXITCODE -ne 0) { throw "Compiled installer policy failed for $arch (exit $LASTEXITCODE)." } + Write-Output "PASS $arch metadata-only package. This is not an executable installer." +}