diff --git a/src/audio/AudioEngine.cpp b/src/audio/AudioEngine.cpp index c537c20..f4641b8 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,13 @@ 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); + // The duplex callback isn't running yet: start from the current mutes + // so a muted output doesn't fade out (leak a block) on start. + duplexFanoutPrevMask = mutedOutputMask.load(std::memory_order_relaxed); + } if (testLoopback) { loopDelay = device->getOutputLatencyInSamples() + device->getInputLatencyInSamples(); @@ -930,8 +936,11 @@ 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. + // and the fan-out's previous mask (owned by that callback) are safe to + // reset here. + splitFanoutPrevMask = mutedOutputMask.load(std::memory_order_relaxed); outputRingTrim.prepare(device->getCurrentSampleRate()); if ((int) outputPullScratchL.size() < bs) outputPullScratchL.assign((size_t) bs, 0.0f); @@ -1046,9 +1055,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 +1078,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 +1139,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 +1180,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 +1196,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 +1205,12 @@ 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), + duplexFanoutPrevMask); } else { @@ -1403,12 +1422,62 @@ 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), + splitFanoutPrevMask); +} + +// -- 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(); } // ── Renderer-audio bus (Phase 2: WebAudio master → engine output) ──────────── diff --git a/src/audio/AudioEngine.h b/src/audio/AudioEngine.h index d9831d3..a2971ec 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,14 @@ 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); + // ── 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 +507,23 @@ 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}; + // The mask each output callback applied last block, so a changed mute + // fades over one block (fanOutStereoMix). Audio-thread owned; set to the + // current mask in the matching about-to-start, before callbacks run. + uint64_t duplexFanoutPrevMask = 0; + uint64_t splitFanoutPrevMask = 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..649e1c8 100644 --- a/src/audio/NodeAddon.cpp +++ b/src/audio/NodeAddon.cpp @@ -129,6 +129,7 @@ using slopsmith::addon::SetSourceMonitorMute; using slopsmith::addon::SetSourceVerifierOffset; using slopsmith::addon::SetStreamBus; using slopsmith::addon::SetStreamBusGain; +using slopsmith::addon::SetMutedOutputChannels; using slopsmith::addon::SetStreamOutputDevice; using slopsmith::addon::SetTonePolish; using slopsmith::addon::SetLivePitch; @@ -345,6 +346,7 @@ 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)); // 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..6f8c25f 100644 --- a/src/audio/addon/Bindings.h +++ b/src/audio/addon/Bindings.h @@ -104,6 +104,7 @@ 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 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 7f7fff0..c61e3b8 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,28 @@ 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)); +} + // 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..332ea46 --- /dev/null +++ b/src/audio/engine/OutputFanout.h @@ -0,0 +1,95 @@ +#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. +// +// A channel whose mute state changed since the previous block (`prevMask`) is +// faded over this one block instead of cut, so a live toggle doesn't click. +// `prevMask` is owned by the calling audio callback: it is updated to +// `mutedMask` on return, and set to the current mask before the device starts. +// +// Called on the audio thread AFTER master gain, metering and the loop-ring +// write (those keep reading the first pair). No allocation, no locks, no JUCE +// (so tests/engine_units can test it directly). +// +// Every channel >= 2 is written on every block (copied, faded 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; +} + +// dst[i] = src[i] * gain ramping linearly from g0 to g1 across the block. +// dst may alias src (the source pair is faded in place). +inline void rampOutputChannel(float* dst, const float* src, int numSamples, + float g0, float g1) noexcept +{ + const float step = (g1 - g0) / (float) numSamples; + float g = g0; + for (int i = 0; i < numSamples; ++i) + { + g += step; // ends exactly on g1 at the last sample + dst[i] = src[i] * g; + } +} + +inline void fanOutStereoMix(float* const* outputData, int numOutputChannels, + int numSamples, uint64_t mutedMask, + uint64_t& prevMask) 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; + const bool mutedNow = outputChannelMuted(mutedMask, ch); + const bool mutedBefore = outputChannelMuted(prevMask, ch); + if (! haveStereo || (mutedNow && mutedBefore)) + std::fill(dst, dst + numSamples, 0.0f); + else if (! mutedNow && ! mutedBefore) + std::copy(outputData[ch & 1], outputData[ch & 1] + numSamples, dst); + else + rampOutputChannel(dst, outputData[ch & 1], numSamples, + mutedBefore ? 0.0f : 1.0f, mutedNow ? 0.0f : 1.0f); + } + + // The source pair last: the copies above still needed its samples. + for (int ch = 0; ch < std::min(numOutputChannels, 2); ++ch) + { + float* const dst = outputData[ch]; + if (dst == nullptr) + continue; + const bool mutedNow = outputChannelMuted(mutedMask, ch); + const bool mutedBefore = outputChannelMuted(prevMask, ch); + if (mutedNow && mutedBefore) + std::fill(dst, dst + numSamples, 0.0f); + else if (mutedNow != mutedBefore) + rampOutputChannel(dst, dst, numSamples, + mutedBefore ? 0.0f : 1.0f, mutedNow ? 0.0f : 1.0f); + } + + prevMask = mutedMask; +} + +} // namespace slopsmith diff --git a/src/main/audio-bridge.ts b/src/main/audio-bridge.ts index 0ed4b00..47a3657 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,119 @@ 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; +} + +// Mutes are saved per output device: backends such as WASAPI name channels +// generically ("Output channel 1"), so a bare name would follow the user onto +// a different device. +function outputDeviceKey(outputType: unknown, outputDevice: unknown): string { + return `${String(outputType ?? '')}|${String(outputDevice ?? '')}`; +} + +function outputDeviceKeyFrom(device: unknown): string | null { + const record = asRecord(device); + if (!record) return null; + return outputDeviceKey(record.outputType, record.outputDevice); +} + +function savedOutputMutes(key: string | null): string[] { + if (key === null) return []; + const byDevice = asRecord(getDesktopConfig().mutedOutputChannelsByDevice); + return byDevice ? sanitizeOutputChannelNames(byDevice[key]) : []; +} + +// The output device the engine has open with EVERY output channel (the last +// successful multi-output setDevice), or null. Mutes reach the engine only +// for it: with just the first pair open, a saved mute on that pair would +// silence the app. +let multiOutputOpenKey: string | null = null; + +function pushOutputMutes(): void { + callAddon('setMutedOutputChannels', -1, savedOutputMutes(multiOutputOpenKey)); +} + +// Record what the last setDevice opened and push that device's saved mutes +// (or clear them). No addon call while multi-output was and stays off. +function noteOutputDeviceOpened(key: string | null): void { + const wasOpen = multiOutputOpenKey !== null; + multiOutputOpenKey = key; + if (wasOpen || key !== null) pushOutputMutes(); +} + +// One setDevice call with an object payload, falling back to the legacy +// positional call when the addon rejects the object form (same backend only). +// `multiOutput` says whether every output was requested: the legacy call +// can't carry it. +function openDeviceObject(normalizedPayload: DeviceConfigPayload): { + result: DeviceConfigOutcome; + multiOutput: boolean; +} { + try { + return { + result: normalizeDeviceConfigResult(audio!.setDevice(normalizedPayload)), + multiOutput: normalizedPayload.multiOutput, + }; + } catch (e: unknown) { + const objectError = e instanceof Error ? e.message : String(e); + console.warn(`[audio] setDevice object call threw: ${objectError}; retrying legacy device call`); + if (normalizedPayload.inputType !== normalizedPayload.outputType) { + return { result: normalizeDeviceConfigResult(false, objectError), multiOutput: false }; + } + if (normalizedPayload.multiOutput) { + console.warn('[audio] legacy setDevice fallback cannot carry "Play on multiple outputs"; opening the first output pair only'); + } + try { + return { + result: normalizeDeviceConfigResult( + audio!.setDevice( + normalizedPayload.inputDevice, + normalizedPayload.outputDevice, + normalizedPayload.sampleRate, + normalizedPayload.bufferSize, + ), + objectError, + ), + multiOutput: false, + }; + } catch (legacyError: unknown) { + const error = legacyError instanceof Error ? legacyError.message : String(legacyError); + console.warn(`[audio] legacy setDevice fallback threw: ${error}`); + return { result: { ok: false, error: error || objectError, duplex: true }, multiOutput: false }; + } + } +} + +type DeviceConfigOutcome = { + ok: boolean; + error: string; + duplex: boolean; + sampleRate?: number; + inputBlockSize?: number; + outputBlockSize?: number; +}; + function normalizeDeviceConfigResult(result: unknown, fallbackError = '') { if (typeof result === 'boolean') { return { @@ -544,33 +656,27 @@ 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); - try { - return normalizeDeviceConfigResult(audio.setDevice(normalizedPayload)); - } catch (e: unknown) { - const objectError = e instanceof Error ? e.message : String(e); - console.warn(`[audio] setDevice object call threw: ${objectError}; retrying legacy device call`); - if (normalizedPayload.inputType !== normalizedPayload.outputType) { - return normalizeDeviceConfigResult(false, objectError); - } - try { - return normalizeDeviceConfigResult( - audio.setDevice( - normalizedPayload.inputDevice, - normalizedPayload.outputDevice, - normalizedPayload.sampleRate, - normalizedPayload.bufferSize, - ), - objectError, - ); - } catch (legacyError: unknown) { - const error = legacyError instanceof Error ? legacyError.message : String(legacyError); - console.warn(`[audio] legacy setDevice fallback threw: ${error}`); - return { ok: false, error: error || objectError, duplex: true }; - } + normalizedPayload.multiOutput = multiOutputEnabled(); + const key = outputDeviceKey(normalizedPayload.outputType, normalizedPayload.outputDevice); + const opened = openDeviceObject(normalizedPayload); + if (!opened.result.ok && normalizedPayload.multiOutput) { + // A device that can't open every output fails closed in the + // engine. Fall back to the first pair rather than leave the + // user with no audio (the saved setting stays on). + console.warn(`[audio] multi-output open failed (${opened.result.error}); retrying with the first output pair only`); + const firstPair = openDeviceObject({ ...normalizedPayload, multiOutput: false }); + noteOutputDeviceOpened(null); + return firstPair.result.ok + ? { ...firstPair.result, multiOutputFallback: true, multiOutputError: opened.result.error } + : opened.result; } + noteOutputDeviceOpened(opened.result.ok && opened.multiOutput ? key : null); + return opened.result; } const [input, output, sampleRate, bufferSize] = args; - return normalizeDeviceConfigResult(audio.setDevice(input, output, sampleRate, bufferSize)); + const positional = normalizeDeviceConfigResult(audio.setDevice(input, output, sampleRate, bufferSize)); + noteOutputDeviceOpened(null); + return positional; } catch (e: unknown) { const error = e instanceof Error ? e.message : String(e); console.warn(`[audio] setDevice threw: ${error}`); @@ -578,6 +684,51 @@ export function initAudioBridge(): void { } }); + // "Play on multiple outputs" (desktop-config). get → the setting and the + // saved mutes of `device` ({outputType, outputDevice}; default: the device + // open with every output). setMultiOutput persists the switch; the + // renderer then re-applies the device, and that setDevice pushes the + // mutes. setMutedOutputChannels persists `device`'s mutes and applies them + // live when that device is the one open with every output. + ipcMain.handle('audio:getMultiOutput', (_event, device?: unknown) => { + const cfg = getDesktopConfig(); + return { + enabled: cfg.multiOutput === true, + mutedOutputChannels: savedOutputMutes(outputDeviceKeyFrom(device) ?? multiOutputOpenKey), + }; + }); + + 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(); + } + return enabled; + }); + + ipcMain.handle('audio:setMutedOutputChannels', (_event, names: unknown, device?: unknown) => { + const key = outputDeviceKeyFrom(device); + if (!Array.isArray(names) || key === null) return savedOutputMutes(key ?? multiOutputOpenKey); + const muted = sanitizeOutputChannelNames(names); + try { + const byDevice: Record = {}; + const saved = asRecord(getDesktopConfig().mutedOutputChannelsByDevice) || {}; + for (const [k, v] of Object.entries(saved)) { + const list = sanitizeOutputChannelNames(v); + if (list.length > 0) byDevice[k] = list; + } + if (muted.length > 0) byDevice[key] = muted; else delete byDevice[key]; + setDesktopConfig({ mutedOutputChannelsByDevice: byDevice }); + } catch (e: unknown) { + console.warn(`[audio] saving mutedOutputChannels failed: ${e instanceof Error ? e.message : String(e)}`); + } + if (key === multiOutputOpenKey) pushOutputMutes(); + return savedOutputMutes(key); + }); + ipcMain.handle('audio:getDeviceMetrics', () => { return callAddon('getDeviceMetrics', null); }); diff --git a/src/main/desktop-config.ts b/src/main/desktop-config.ts index 91d08e3..ca172b5 100644 --- a/src/main/desktop-config.ts +++ b/src/main/desktop-config.ts @@ -1,8 +1,8 @@ // 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, -// python.ts and soundfont-manager.ts. Moved out of soundfont-manager.ts -// unchanged (untangler I-002). +// geometry, fullscreen, pane pop-out windows, multi-output audio). Read by +// main.ts, pane-hosts.ts, python.ts, soundfont-manager.ts and audio-bridge.ts. +// Moved out of soundfont-manager.ts unchanged (untangler I-002). import { app } from 'electron'; import * as fs from 'fs'; @@ -33,6 +33,18 @@ 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, per output device ("|"). + // Keyed by name, not index, because ASIO4ALL reorders channels when + // devices are ticked in its panel; per device because some backends name + // channels generically ("Output channel 1"). Applied live (no reopen). + mutedOutputChannelsByDevice?: Record; } export interface SavedPaneWindow { diff --git a/src/main/preload.ts b/src/main/preload.ts index 8861988..a49b076 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -63,6 +63,10 @@ export interface DeviceConfig { bufferSize: number; } +// Output device a multi-output mute list belongs to (same values as the +// setDevice payload's outputType / outputDevice). +type OutputDeviceRef = { outputType: string; outputDevice: string }; + // setDevice result. `duplex` reports the resolved mode (the engine may pick // duplex even when the renderer sent type-mismatched devices, e.g. when the // user lands on the same driver via different UI dropdowns). On failure @@ -246,6 +250,15 @@ 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, saved per + // output device and applied live to the device open with every output. + getMultiOutput: (device?: OutputDeviceRef): Promise<{ enabled: boolean; mutedOutputChannels: string[] }> => + ipcRenderer.invoke('audio:getMultiOutput', device), + setMultiOutput: (enabled: boolean): Promise => + ipcRenderer.invoke('audio:setMultiOutput', enabled), + setMutedOutputChannels: (names: string[], device: OutputDeviceRef): Promise => + ipcRenderer.invoke('audio:setMutedOutputChannels', names, device), 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..585bb2b 100644 --- a/src/renderer/screen.html +++ b/src/renderer/screen.html @@ -92,6 +92,18 @@

Audio Device

+
+ + + +