From db30c32615a42d8f7dbe3e7e70015e1add7be02e Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:14:11 -0800 Subject: [PATCH 1/7] refactor(renderer): name the Apply device handler applyDeviceForm Moves the Apply Device Settings click handler body into a named function so another control can re-run the exact same flow (stop, setDevice, restore input/monitor state, start, save) instead of copying it. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- src/renderer/screen.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/renderer/screen.js b/src/renderer/screen.js index c9bc8c9..e9a5b71 100644 --- a/src/renderer/screen.js +++ b/src/renderer/screen.js @@ -1718,7 +1718,9 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; ); }); - applyDeviceBtn.addEventListener('click', async () => { + applyDeviceBtn.addEventListener('click', () => applyDeviceForm()); + + async function applyDeviceForm() { statusText.textContent = 'Configuring device...'; if (audioRunning) { await api.stopAudio(); @@ -1765,7 +1767,7 @@ window.__feedBackDesktopAudioHooks = window.__feedBackDesktopAudioHooks || {}; : 'Failed to configure device'; statusDot.className = 'w-3 h-3 rounded-full bg-red-500'; } - }); + } // Input channel inputChannelSelect.addEventListener('change', async () => { From f88095dbc364b120e664c4cc54c7e9a38da34629 Mon Sep 17 00:00:00 2001 From: mattromano <42412983+mattromano@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:14:45 -0800 Subject: [PATCH 2/7] feat(audio): play on multiple outputs, with a live mute per output Opt-in desktop setting "Play on multiple outputs" (off by default), stored in desktop-config. With it on, the engine opens every output channel the device advertises (for example ASIO4ALL with both a headset and the Realtek speakers ticked) and copies the finished stereo mix, after master gain, to every further pair. Each output pair also gets a live play/mute checkbox. Mutes are saved by output channel name, so they survive ASIO4ALL reordering channels, and apply without reopening the device. Toggling the switch reopens the device through the normal Apply flow, with no relaunch. - DeviceSetup: a single outputChannelsToOpen() helper feeds the duplex skip check, the open, the verify, and the split open, so the masks can't disagree. - Engine: duplex mixes into the first pair only. Metering and the loop ring still read that pair. fanOutStereoMix() (OutputFanout.h) then writes or clears every extra channel and silences the muted ones. - Main: the setDevice handler adds multiOutput from desktop-config, so every renderer caller gets it. Saved mutes are pushed to the engine at startup and on every change, and only while the switch is on. Intended contract changes: new addon exports set/getMutedOutputChannels; new IPC and preload audio:getMultiOutput / setMultiOutput / setMutedOutputChannels. The fallbacks snapshot was regenerated (UPDATE_SNAPSHOT=1) for those three handlers, and the handler count went from 111 to 114. Co-Authored-By: Claude Opus 5.5 --- src/audio/AudioEngine.cpp | 86 +++++++- src/audio/AudioEngine.h | 22 ++ src/audio/NodeAddon.cpp | 4 + src/audio/addon/Bindings.h | 2 + src/audio/addon/DeviceBindings.cpp | 39 ++++ src/audio/engine/DeviceSetup.cpp | 15 +- src/audio/engine/DeviceSetup.h | 17 +- src/audio/engine/OutputFanout.h | 57 +++++ src/main/audio-bridge.ts | 77 +++++++ src/main/desktop-config.ts | 12 +- src/main/preload.ts | 8 + src/renderer/screen.html | 12 + src/renderer/screen.js | 112 ++++++++++ tests/audio-bridge-fallbacks.test.js | 2 +- tests/contracts/addon-exports.json | 2 + tests/contracts/ipc-channels.json | 3 + tests/contracts/preload-audio-api.json | 3 + .../audio-bridge-fallbacks.snapshot.json | 54 +++++ tests/multi-output.test.js | 208 ++++++++++++++++++ tests/test-inventory.test.js | 2 +- 20 files changed, 717 insertions(+), 20 deletions(-) create mode 100644 src/audio/engine/OutputFanout.h create mode 100644 tests/multi-output.test.js diff --git a/src/audio/AudioEngine.cpp b/src/audio/AudioEngine.cpp index c537c20..4d6d07c 100644 --- a/src/audio/AudioEngine.cpp +++ b/src/audio/AudioEngine.cpp @@ -531,7 +531,7 @@ AudioEngine::DeviceConfigResult AudioEngine::setAudioDevices(const DeviceConfig& const juce::String err = deviceSetup.applyDuplex(resolvedInput, resolvedOutput, requestedSampleRate, requestedBufferSize, - source0()); + source0(), config.multiOutput); if (err.isEmpty()) { duplexMode.store(true, std::memory_order_relaxed); @@ -847,7 +847,10 @@ void AudioEngine::audioDeviceAboutToStart(juce::AudioIODevice* device) // Duplex: this device is the output too - its output latency places the // heard clock. Split mode records the output device's in audioOutputAboutToStart. if (duplexMode.load(std::memory_order_relaxed)) + { outputLatencySamples.store(device->getOutputLatencyInSamples(), std::memory_order_relaxed); + captureActiveOutputChannels(device); + } if (testLoopback) { loopDelay = device->getOutputLatencyInSamples() + device->getInputLatencyInSamples(); @@ -930,6 +933,7 @@ void AudioEngine::audioOutputAboutToStart(juce::AudioIODevice* device) device->getName().toRawUTF8(), device->getCurrentSampleRate(), bs); outputBlockSize.store(bs, std::memory_order_relaxed); outputLatencySamples.store(device->getOutputLatencyInSamples(), std::memory_order_relaxed); + captureActiveOutputChannels(device); // The output callback isn't running yet for this device, so the trim state // (owned by that callback) is safe to reset here. outputRingTrim.prepare(device->getCurrentSampleRate()); @@ -1046,9 +1050,13 @@ void AudioEngine::audioDeviceIOCallbackWithContext( // Duplex writes outputData directly. Split runs DSP into a private 2-channel // scratch and pushes the result to outputRing for OutputCallback. juce::AudioBuffer buffer; + // Duplex mixes into the first output pair only. With "Play on multiple + // outputs" the device has more channels; fanOutStereoMix() copies the + // finished pair onto them at the end of the block. + const int mixOutputChannels = duplex ? juce::jmin(numOutputChannels, 2) : 2; if (duplex) { - buffer.setDataToReferTo(outputData, numOutputChannels, numSamples); + buffer.setDataToReferTo(outputData, mixOutputChannels, numSamples); } else { @@ -1065,7 +1073,7 @@ void AudioEngine::audioDeviceIOCallbackWithContext( buffer.setDataToReferTo(outputBackingBuffer.getArrayOfWritePointers(), 2, numSamples); } - const int effectiveOutputChannels = duplex ? numOutputChannels : 2; + const int effectiveOutputChannels = mixOutputChannels; // Per-source capture + detect + monitor. // @@ -1126,7 +1134,7 @@ void AudioEngine::audioDeviceIOCallbackWithContext( publishBackingStamp(outSamples); const float bVol = backingVolume.load(); streamBackingFrames = outSamples; streamBackingVol = bVol; streamBackingOn = true; - const int mixChannels = juce::jmin(numOutputChannels, 2); + const int mixChannels = mixOutputChannels; float backingLevelSq = 0.0f; for (int ch = 0; ch < mixChannels; ++ch) { @@ -1167,15 +1175,15 @@ void AudioEngine::audioDeviceIOCallbackWithContext( // Renderer bus into the device output — like backing, before master gain. if (rendererFrames > 0) - for (int ch = 0; ch < juce::jmin(numOutputChannels, 2); ++ch) + for (int ch = 0; ch < mixOutputChannels; ++ch) buffer.addFrom(ch, 0, rendererBusPullScratch, ch, 0, rendererFrames); // Apply output gain buffer.applyGain(outputGain.load()); - // Output metering + // Output metering: the first pair (the mix), before fan-out / mute. float peak = 0.0f; - for (int ch = 0; ch < numOutputChannels; ++ch) + for (int ch = 0; ch < mixOutputChannels; ++ch) peak = juce::jmax(peak, buffer.getMagnitude(ch, 0, numSamples)); currentOutputLevel.store(peak); float prevPeak = outputPeak.load(); @@ -1183,7 +1191,7 @@ void AudioEngine::audioDeviceIOCallbackWithContext( if (loopNow) { - const int nOut = juce::jmin(numOutputChannels, 2); + const int nOut = mixOutputChannels; for (int j = 0; j < numSamples; ++j) { float m = 0.0f; @@ -1192,6 +1200,11 @@ void AudioEngine::audioDeviceIOCallbackWithContext( } loopWrite += (uint64_t) numSamples; } + + // Multi-output: copy the finished stereo mix (post master gain) to + // every further output pair, then silence muted channels. + slopsmith::fanOutStereoMix(outputData, numOutputChannels, numSamples, + mutedOutputMask.load(std::memory_order_relaxed)); } else { @@ -1403,12 +1416,67 @@ void AudioEngine::audioOutputCallback(const float* const* /*inputData*/, buffer.applyGain(outputGain.load()); + // Metering reads the first pair (the mix), before fan-out / mute. float peak = 0.0f; - for (int ch = 0; ch < numOutputChannels; ++ch) + for (int ch = 0; ch < copyChannels; ++ch) peak = juce::jmax(peak, buffer.getMagnitude(ch, 0, numSamples)); currentOutputLevel.store(peak); float prevPeak = outputPeak.load(); if (peak > prevPeak) outputPeak.store(peak); + + // Multi-output: copy the stereo mix to every further pair, silence mutes. + slopsmith::fanOutStereoMix(outputData, numOutputChannels, numSamples, + mutedOutputMask.load(std::memory_order_relaxed)); +} + +// -- Multi-output mute ("Play on multiple outputs") -------------------------- + +int AudioEngine::recomputeMutedOutputMaskLocked() +{ + uint64_t mask = 0; + int matched = 0; + const int n = juce::jmin(activeOutputNames.size(), 64); + for (int c = 0; c < n; ++c) + { + if (mutedOutputNames.contains(activeOutputNames[c])) + { + mask |= (uint64_t) 1 << c; + ++matched; + } + } + mutedOutputMask.store(mask, std::memory_order_relaxed); + return matched; +} + +void AudioEngine::captureActiveOutputChannels(juce::AudioIODevice* device) +{ + juce::StringArray active; + if (device != nullptr) + { + // The callback's outputData holds only the ACTIVE channels, in + // ascending channel order: map each to its advertised name. + const auto names = device->getOutputChannelNames(); + const auto bits = device->getActiveOutputChannels(); + for (int ch = 0; ch < names.size(); ++ch) + if (bits[ch]) + active.add(names[ch]); + } + const juce::ScopedLock sl(outputMuteLock); + activeOutputNames = active; + recomputeMutedOutputMaskLocked(); +} + +int AudioEngine::setMutedOutputChannels(const juce::StringArray& names) +{ + const juce::ScopedLock sl(outputMuteLock); + mutedOutputNames = names; + return recomputeMutedOutputMaskLocked(); +} + +juce::StringArray AudioEngine::getMutedOutputChannels() const +{ + const juce::ScopedLock sl(outputMuteLock); + return mutedOutputNames; } // ── Renderer-audio bus (Phase 2: WebAudio master → engine output) ──────────── diff --git a/src/audio/AudioEngine.h b/src/audio/AudioEngine.h index d9831d3..652b106 100644 --- a/src/audio/AudioEngine.h +++ b/src/audio/AudioEngine.h @@ -10,6 +10,7 @@ #include "engine/DeviceSetup.h" #include "engine/SourcePool.h" #include "engine/ExtraInputs.h" +#include "engine/OutputFanout.h" #include "BackingLeveler.h" #include "signalsmith-stretch.h" #include @@ -267,6 +268,15 @@ class AudioEngine : private juce::AudioIODeviceCallback void setStreamBus(bool includeBacking, bool includeGuitar, float gain) { streamSink.setBus(includeBacking, includeGuitar, gain); } void setStreamBusGain(float gain) { streamSink.setBusGain(gain); } + // Multi-output mute ("Play on multiple outputs"). `names` are output + // channel names as the device advertises them (probeDeviceOptions + // outputChannels); keyed by name, not index, because ASIO4ALL reorders + // channels when devices are ticked in its panel. Applies live (no device + // reopen) and is re-resolved against the new channel list on every + // device start. Returns how many of the names match an open channel. + int setMutedOutputChannels(const juce::StringArray& names); + juce::StringArray getMutedOutputChannels() const; + // ── Renderer-audio bus (Phase 2: WebAudio master → engine output) ───────── // The renderer pushes its WebAudio master mix here (via IPC) so song/stem // audio stays audible when the output device is exclusive-style and the OS @@ -498,6 +508,18 @@ class AudioEngine : private juce::AudioIODeviceCallback std::atomic currentBackingLevel{0.0f}; std::atomic outputPeak{0.0f}; + // Multi-output mute: bit c = output channel c (of the open output device's + // ACTIVE channels, callback order) is silenced by fanOutStereoMix(). + // Written on control / device-start threads, read once per block on the + // audio thread. + std::atomic mutedOutputMask{0}; + // Control-side state behind the mask (never touched by the audio thread). + mutable juce::CriticalSection outputMuteLock; + juce::StringArray mutedOutputNames; // what the user muted (persisted by main) + juce::StringArray activeOutputNames; // active output channels of the open device, in callback order + int recomputeMutedOutputMaskLocked(); + void captureActiveOutputChannels(juce::AudioIODevice* device); + // Backing track — transport/stretch/leveler moved to engine/BackingPlayer // (TLC phase 3). Declared after `state` (bound by reference). slopsmith::BackingPlayer backing{state}; diff --git a/src/audio/NodeAddon.cpp b/src/audio/NodeAddon.cpp index fb6157d..79a5a2a 100644 --- a/src/audio/NodeAddon.cpp +++ b/src/audio/NodeAddon.cpp @@ -129,6 +129,8 @@ using slopsmith::addon::SetSourceMonitorMute; using slopsmith::addon::SetSourceVerifierOffset; using slopsmith::addon::SetStreamBus; using slopsmith::addon::SetStreamBusGain; +using slopsmith::addon::SetMutedOutputChannels; +using slopsmith::addon::GetMutedOutputChannels; using slopsmith::addon::SetStreamOutputDevice; using slopsmith::addon::SetTonePolish; using slopsmith::addon::SetLivePitch; @@ -345,6 +347,8 @@ static Napi::Object InitModule(Napi::Env env, Napi::Object exports) exports.Set("setOutputDeviceType", Napi::Function::New(env, SetOutputDeviceType)); exports.Set("setDevice", Napi::Function::New(env, SetDevice)); exports.Set("getDeviceMetrics", Napi::Function::New(env, GetDeviceMetrics)); + exports.Set("setMutedOutputChannels", Napi::Function::New(env, SetMutedOutputChannels)); + exports.Set("getMutedOutputChannels", Napi::Function::New(env, GetMutedOutputChannels)); // Audio control exports.Set("startAudio", Napi::Function::New(env, StartAudio)); diff --git a/src/audio/addon/Bindings.h b/src/audio/addon/Bindings.h index 57a61b9..f4e0ef4 100644 --- a/src/audio/addon/Bindings.h +++ b/src/audio/addon/Bindings.h @@ -104,6 +104,8 @@ Napi::Value SetSourceMonitorMute(const Napi::CallbackInfo& info); Napi::Value SetSourceVerifierOffset(const Napi::CallbackInfo& info); Napi::Value SetStreamBus(const Napi::CallbackInfo& info); Napi::Value SetStreamBusGain(const Napi::CallbackInfo& info); +Napi::Value SetMutedOutputChannels(const Napi::CallbackInfo& info); +Napi::Value GetMutedOutputChannels(const Napi::CallbackInfo& info); Napi::Value SetStreamOutputDevice(const Napi::CallbackInfo& info); Napi::Value SetTonePolish(const Napi::CallbackInfo& info); Napi::Value SetLivePitch(const Napi::CallbackInfo& info); diff --git a/src/audio/addon/DeviceBindings.cpp b/src/audio/addon/DeviceBindings.cpp index 1ff809d..38da3f7 100644 --- a/src/audio/addon/DeviceBindings.cpp +++ b/src/audio/addon/DeviceBindings.cpp @@ -312,6 +312,9 @@ Napi::Value SetDevice(const Napi::CallbackInfo& info) else cfg.bufferSize = 256; } + // "Play on multiple outputs" (main injects it from desktop-config). + cfg.multiOutput = obj.Has("multiOutput") && obj.Get("multiOutput").IsBoolean() + && obj.Get("multiOutput").As().Value(); } else { @@ -415,6 +418,42 @@ Napi::Value SetStreamBusGain(const Napi::CallbackInfo& info) return info.Env().Undefined(); } +// setMutedOutputChannels(names:string[]) -> number +// "Play on multiple outputs" live mute: output channel names (as advertised by +// probeDeviceOptions().outputChannels) to silence. Applies without reopening +// the device. Returns how many names match a channel of the open device, or +// -1 when the engine is down / args are malformed. +Napi::Value SetMutedOutputChannels(const Napi::CallbackInfo& info) +{ + auto env = info.Env(); + auto liveEngine = snapshotEngine(); + if (!liveEngine || info.Length() < 1 || !info[0].IsArray()) + return Napi::Number::New(env, -1); + auto arr = info[0].As(); + juce::StringArray names; + for (uint32_t i = 0; i < arr.Length(); ++i) + { + Napi::Value v = arr.Get(i); + if (v.IsString()) + names.addIfNotAlreadyThere(juce::String::fromUTF8(v.As().Utf8Value().c_str())); + } + return Napi::Number::New(env, liveEngine->setMutedOutputChannels(names)); +} + +// getMutedOutputChannels() -> string[] +Napi::Value GetMutedOutputChannels(const Napi::CallbackInfo& info) +{ + auto env = info.Env(); + auto out = Napi::Array::New(env); + auto liveEngine = snapshotEngine(); + if (!liveEngine) + return out; + const auto names = liveEngine->getMutedOutputChannels(); + for (int i = 0; i < names.size(); ++i) + out.Set((uint32_t) i, names[i].toStdString()); + return out; +} + // setRendererBus(enabled:boolean, gain:number) Napi::Value SetRendererBus(const Napi::CallbackInfo& info) { diff --git a/src/audio/engine/DeviceSetup.cpp b/src/audio/engine/DeviceSetup.cpp index 65e11b0..1fb2499 100644 --- a/src/audio/engine/DeviceSetup.cpp +++ b/src/audio/engine/DeviceSetup.cpp @@ -285,7 +285,8 @@ DeviceOptions DeviceSetup::probeDual(const juce::String& inputTypeName, juce::String DeviceSetup::applyDuplex(const juce::String& inputName, const juce::String& outputName, double sampleRate, int bufferSize, - SourceChain& monitorChain) + SourceChain& monitorChain, + bool multiOutput) { juce::AudioDeviceManager::AudioDeviceSetup setup; setup.inputDeviceName = inputName; @@ -332,7 +333,7 @@ juce::String DeviceSetup::applyDuplex(const juce::String& inputName, const int advertisedOutputs = currentDevice->getOutputChannelNames().size(); juce::BigInteger expectedOutputs; - expectedOutputs.setRange(0, juce::jmin(advertisedOutputs > 0 ? advertisedOutputs : 2, 2), true); + expectedOutputs.setRange(0, outputChannelsToOpen(advertisedOutputs, multiOutput), true); if (current.inputDeviceName == setup.inputDeviceName && current.outputDeviceName == setup.outputDeviceName @@ -421,7 +422,7 @@ juce::String DeviceSetup::applyDuplex(const juce::String& inputName, if (outputChannelCount <= 0) outputChannelCount = 2; setup.inputChannels.setRange(0, inputChannelCount, true); - setup.outputChannels.setRange(0, juce::jmin(outputChannelCount, 2), true); + setup.outputChannels.setRange(0, outputChannelsToOpen(outputChannelCount, multiOutput), true); juce::String result; fprintf(stderr, "[AudioEngine] Duplex reconfigure phase=open begin sr=%.0f bs=%d\n", @@ -449,8 +450,8 @@ juce::String DeviceSetup::applyDuplex(const juce::String& inputName, const double sr = configuredDevice->getCurrentSampleRate(); const int bs = configuredDevice->getCurrentBufferSizeSamples(); - // For explicitly named endpoints, "all inputs / first two outputs" is - // the requested contract. Rebuild those masks from the opened device's + // For explicitly named endpoints, "all inputs / first two outputs" (all + // outputs with multiOutput) is the requested contract. Rebuild those masks from the opened device's // advertised channels so a failed pre-open probe cannot silently // collapse an 8-input ASIO interface to the old two-channel fallback. juce::BigInteger expectedInputs; @@ -464,7 +465,7 @@ juce::String DeviceSetup::applyDuplex(const juce::String& inputName, expectedOutputs = setup.outputChannels; else expectedOutputs.setRange( - 0, juce::jmin(configuredDevice->getOutputChannelNames().size(), 2), true); + 0, outputChannelsToOpen(configuredDevice->getOutputChannelNames().size(), multiOutput), true); const auto actualInputs = configuredDevice->getActiveInputChannels(); const auto actualOutputs = configuredDevice->getActiveOutputChannels(); @@ -707,7 +708,7 @@ DeviceConfigResult DeviceSetup::applySplit(const DeviceConfig& config, } if (outputChannelCount <= 0) outputChannelCount = 2; outSetup.inputChannels.clear(); - outSetup.outputChannels.setRange(0, juce::jmin(outputChannelCount, 2), true); + outSetup.outputChannels.setRange(0, outputChannelsToOpen(outputChannelCount, config.multiOutput), true); // Same JUCE_LINUX close-before-reconfigure as the input side above — also // protects when split mode is re-applied with a different output device. diff --git a/src/audio/engine/DeviceSetup.h b/src/audio/engine/DeviceSetup.h index 3921e42..bc00373 100644 --- a/src/audio/engine/DeviceSetup.h +++ b/src/audio/engine/DeviceSetup.h @@ -47,6 +47,10 @@ struct DeviceConfig juce::String outputDevice; double sampleRate = 48000.0; int bufferSize = 256; + // "Play on multiple outputs": open EVERY advertised output channel instead + // of the first pair. The engine still mixes stereo into 0/1 and fans it + // out to the other pairs (OutputFanout.h). Off = historical 2-output mask. + bool multiOutput = false; }; struct DeviceConfigResult @@ -84,7 +88,8 @@ class DeviceSetup juce::String applyDuplex(const juce::String& inputName, const juce::String& outputName, double sampleRate, int bufferSize, - SourceChain& monitorChain); + SourceChain& monitorChain, + bool multiOutput = false); // Open input-only + output-only devices at a shared nominal rate. On // success stores the achieved format, resets the split ring + counters, @@ -111,6 +116,16 @@ class DeviceSetup // SR preflight, and split open must all check the SAME concrete device). static juce::String resolveDeviceName(juce::AudioIODeviceType* t, bool isInput, const juce::String& name); + // How many leading output channels to open for a device advertising + // `advertised` outputs: the first pair normally, all of them with + // multiOutput. Shared by the duplex skip check, open, verify and the split + // open so the four masks can never disagree (a mismatch would either skip + // a needed reopen or fail the verify step closed). + static int outputChannelsToOpen(int advertised, bool multiOutput) + { + const int n = advertised > 0 ? advertised : 2; + return multiOutput ? n : juce::jmin(n, 2); + } // Whether `dev` (resolved) supports `sr` within tolerance. static bool rateSupportedBy(juce::AudioIODeviceType* t, const juce::String& dev, bool isInput, double sr); diff --git a/src/audio/engine/OutputFanout.h b/src/audio/engine/OutputFanout.h new file mode 100644 index 0000000..c3c1004 --- /dev/null +++ b/src/audio/engine/OutputFanout.h @@ -0,0 +1,57 @@ +#pragma once + +// Multi-output fan-out ("Play on multiple outputs"). +// +// The engine always renders one stereo mix into output channels 0/1. When the +// device was opened with more outputs (e.g. ASIO4ALL exposing a headset AND +// the Realtek speakers), every further pair gets a copy of that mix: even +// channels take L, odd channels take R. Then any channel whose bit is set in +// `mutedMask` is silenced — pair 0 included — so the user can switch between +// outputs live without reopening the device. +// +// Called on the audio thread AFTER master gain, metering and the loop-ring +// write (those keep reading the first pair). No allocation, no locks. +// +// Every channel >= 2 is written on every block (copied or cleared), so stale +// data — e.g. the single-source fast path broadcasting guitar-only audio to +// all channels — never reaches the extra outputs. + +#include +#include + +namespace slopsmith +{ + +// Bit `c` set = output channel `c` muted. Channels >= 64 are never muted. +inline bool outputChannelMuted(uint64_t mutedMask, int channel) noexcept +{ + return channel >= 0 && channel < 64 && ((mutedMask >> channel) & 1u) != 0; +} + +inline void fanOutStereoMix(float* const* outputData, int numOutputChannels, + int numSamples, uint64_t mutedMask) noexcept +{ + if (outputData == nullptr || numOutputChannels <= 0 || numSamples <= 0) + return; + + const bool haveStereo = numOutputChannels >= 2 + && outputData[0] != nullptr && outputData[1] != nullptr; + + for (int ch = 2; ch < numOutputChannels; ++ch) + { + float* const dst = outputData[ch]; + if (dst == nullptr) + continue; + if (haveStereo && ! outputChannelMuted(mutedMask, ch)) + juce::FloatVectorOperations::copy(dst, outputData[ch & 1], numSamples); + else + juce::FloatVectorOperations::clear(dst, numSamples); + } + + // Mute the source pair last: the copies above still needed its samples. + for (int ch = 0; ch < juce::jmin(numOutputChannels, 2); ++ch) + if (outputData[ch] != nullptr && outputChannelMuted(mutedMask, ch)) + juce::FloatVectorOperations::clear(outputData[ch], numSamples); +} + +} // namespace slopsmith diff --git a/src/main/audio-bridge.ts b/src/main/audio-bridge.ts index 0ed4b00..799963e 100644 --- a/src/main/audio-bridge.ts +++ b/src/main/audio-bridge.ts @@ -9,6 +9,7 @@ import { app } from 'electron'; import { isDebugEnabled, getDebugLogPath } from './debug-log'; import { initVstCrashGuard, armSentinel, disarmSentinel, armEditorSentinel, getSentinelPath } from './vst-crash-guard'; import { createAudioEffectsExecutor } from './audio-effects-executor'; +import { getDesktopConfig, setDesktopConfig } from './desktop-config'; type AudioModule = Record any>; @@ -152,6 +153,7 @@ type DeviceConfigPayload = { outputDevice: string; sampleRate: number; bufferSize: number; + multiOutput: boolean; }; function normalizeDeviceConfigPayload(payload: unknown): DeviceConfigPayload { @@ -166,9 +168,39 @@ function normalizeDeviceConfigPayload(payload: unknown): DeviceConfigPayload { outputDevice: String(record.outputDevice ?? record.output ?? ''), sampleRate: Number.isFinite(sampleRate) && sampleRate > 0 ? sampleRate : 48000, bufferSize: Number.isFinite(bufferSize) && bufferSize > 0 ? bufferSize : 256, + multiOutput: record.multiOutput === true, }; } +// ── "Play on multiple outputs" ────────────────────────────────────────────── +// The setting lives in desktop-config (main owns it, not the renderer's +// device settings), so every setDevice caller gets it without passing it. + +function multiOutputEnabled(): boolean { + return getDesktopConfig().multiOutput === true; +} + +function sanitizeOutputChannelNames(value: unknown): string[] { + if (!Array.isArray(value)) return []; + const out: string[] = []; + for (const v of value) { + if (typeof v !== 'string') continue; + const name = v.trim(); + if (name && name.length <= 256 && !out.includes(name)) out.push(name); + if (out.length >= 64) break; + } + return out; +} + +// Push the saved mutes to the engine. With multiOutput off nothing is muted: +// the device then only has its first pair open, and a stale mute on it would +// silence the app. +function pushOutputMutes(): void { + const cfg = getDesktopConfig(); + const muted = cfg.multiOutput === true ? sanitizeOutputChannelNames(cfg.mutedOutputChannels) : []; + callAddon('setMutedOutputChannels', -1, muted); +} + function normalizeDeviceConfigResult(result: unknown, fallbackError = '') { if (typeof result === 'boolean') { return { @@ -293,6 +325,11 @@ export function initAudioBridge(): void { } } + // Saved multi-output mutes: the engine re-resolves them against the + // channel list every time a device starts, so pushing once here covers + // every later setDevice. + if (audio) pushOutputMutes(); + // VST crash guard: promote any leftover crash sentinel into the blocklist, // then hand the blocklist to the addon so it sandboxes those plugins. if (audio) { @@ -544,6 +581,7 @@ export function initAudioBridge(): void { if (Number.isFinite(sr) && sr > 0) payload.sampleRate = sr; if (Number.isFinite(bs) && bs > 0) payload.bufferSize = bs; const normalizedPayload = normalizeDeviceConfigPayload(payload); + normalizedPayload.multiOutput = multiOutputEnabled(); try { return normalizeDeviceConfigResult(audio.setDevice(normalizedPayload)); } catch (e: unknown) { @@ -552,6 +590,9 @@ export function initAudioBridge(): void { if (normalizedPayload.inputType !== normalizedPayload.outputType) { return normalizeDeviceConfigResult(false, objectError); } + if (normalizedPayload.multiOutput) { + console.warn('[audio] legacy setDevice fallback cannot carry "Play on multiple outputs"; opening the first output pair only'); + } try { return normalizeDeviceConfigResult( audio.setDevice( @@ -578,6 +619,42 @@ export function initAudioBridge(): void { } }); + // "Play on multiple outputs" (desktop-config). get → current setting; + // setMultiOutput persists the switch (the renderer then re-applies the + // device so the new channel mask opens); setMutedOutputChannels persists + // and applies the per-output mutes live, without reopening. + ipcMain.handle('audio:getMultiOutput', () => { + const cfg = getDesktopConfig(); + return { + enabled: cfg.multiOutput === true, + mutedOutputChannels: sanitizeOutputChannelNames(cfg.mutedOutputChannels), + }; + }); + + ipcMain.handle('audio:setMultiOutput', (_event, enabled: unknown) => { + if (typeof enabled !== 'boolean') return multiOutputEnabled(); + try { + setDesktopConfig({ multiOutput: enabled }); + } catch (e: unknown) { + console.warn(`[audio] saving multiOutput failed: ${e instanceof Error ? e.message : String(e)}`); + return multiOutputEnabled(); + } + pushOutputMutes(); + return enabled; + }); + + ipcMain.handle('audio:setMutedOutputChannels', (_event, names: unknown) => { + if (!Array.isArray(names)) return sanitizeOutputChannelNames(getDesktopConfig().mutedOutputChannels); + const muted = sanitizeOutputChannelNames(names); + try { + setDesktopConfig({ mutedOutputChannels: muted }); + } catch (e: unknown) { + console.warn(`[audio] saving mutedOutputChannels failed: ${e instanceof Error ? e.message : String(e)}`); + } + pushOutputMutes(); + return sanitizeOutputChannelNames(getDesktopConfig().mutedOutputChannels); + }); + ipcMain.handle('audio:getDeviceMetrics', () => { return callAddon('getDeviceMetrics', null); }); diff --git a/src/main/desktop-config.ts b/src/main/desktop-config.ts index 91d08e3..4b067e2 100644 --- a/src/main/desktop-config.ts +++ b/src/main/desktop-config.ts @@ -1,6 +1,6 @@ // Desktop config — the main process's own settings file, // /slopsmith-desktop.json (soundfont quality, LAN access, window -// geometry, fullscreen, pane pop-out windows). Read by main.ts, pane-hosts.ts, +// geometry, fullscreen, pane pop-out windows, multi-output audio). Read by main.ts, pane-hosts.ts, // python.ts and soundfont-manager.ts. Moved out of soundfont-manager.ts // unchanged (untangler I-002). @@ -33,6 +33,16 @@ export interface DesktopConfig { // the renderer's localStorage because localStorage is shared with the pane // windows themselves (same origin), and a second writer there would race. paneWindows?: Record; + // "Play on multiple outputs": when true the audio engine opens EVERY output + // channel of the device (e.g. ASIO4ALL with a headset and the Realtek + // speakers both ticked) and plays the stereo mix on each pair, instead of + // only the first pair. Opt-in (default off). Read by audio-bridge.ts on + // every setDevice; toggling it reopens the device. + multiOutput?: boolean; + // Output channel names (as the device advertises them) silenced while + // multiOutput is on. Keyed by name, not index, because ASIO4ALL reorders + // channels when devices are ticked in its panel. Applied live (no reopen). + mutedOutputChannels?: string[]; } export interface SavedPaneWindow { diff --git a/src/main/preload.ts b/src/main/preload.ts index 2677eaa..fdf88a4 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -245,6 +245,14 @@ const feedBackDesktopApi = { (input: string, output: string, sampleRate: number, bufferSize: number): Promise; }, getDeviceMetrics: () => ipcRenderer.invoke('audio:getDeviceMetrics'), + // "Play on multiple outputs": the switch reopens the device (call + // setDevice again after it); mutes are output channel names, live. + getMultiOutput: (): Promise<{ enabled: boolean; mutedOutputChannels: string[] }> => + ipcRenderer.invoke('audio:getMultiOutput'), + setMultiOutput: (enabled: boolean): Promise => + ipcRenderer.invoke('audio:setMultiOutput', enabled), + setMutedOutputChannels: (names: string[]): Promise => + ipcRenderer.invoke('audio:setMutedOutputChannels', names), loadDeviceSettings: () => ipcRenderer.invoke('audio:loadDeviceSettings'), saveDeviceSettings: (settings: unknown) => ipcRenderer.invoke('audio:saveDeviceSettings', settings), diff --git a/src/renderer/screen.html b/src/renderer/screen.html index 54d6466..e3b3771 100644 --- a/src/renderer/screen.html +++ b/src/renderer/screen.html @@ -92,6 +92,18 @@

Audio Device

+
+ + + +