Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 79 additions & 10 deletions src/audio/AudioEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<float> 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
{
Expand All @@ -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.
//
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -1167,23 +1180,23 @@ 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();
if (peak > prevPeak) outputPeak.store(peak);

if (loopNow)
{
const int nOut = juce::jmin(numOutputChannels, 2);
const int nOut = mixOutputChannels;
for (int j = 0; j < numSamples; ++j)
{
float m = 0.0f;
Expand All @@ -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
{
Expand Down Expand Up @@ -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) ────────────
Expand Down
26 changes: 26 additions & 0 deletions src/audio/AudioEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <juce_audio_devices/juce_audio_devices.h>
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -498,6 +507,23 @@ class AudioEngine : private juce::AudioIODeviceCallback
std::atomic<float> currentBackingLevel{0.0f};
std::atomic<float> 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<uint64_t> 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};
Expand Down
2 changes: 2 additions & 0 deletions src/audio/NodeAddon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down
1 change: 1 addition & 0 deletions src/audio/addon/Bindings.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
25 changes: 25 additions & 0 deletions src/audio/addon/DeviceBindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<Napi::Boolean>().Value();
}
else
{
Expand Down Expand Up @@ -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<Napi::Array>();
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<Napi::String>().Utf8Value().c_str()));
}
return Napi::Number::New(env, liveEngine->setMutedOutputChannels(names));
}

// setRendererBus(enabled:boolean, gain:number)
Napi::Value SetRendererBus(const Napi::CallbackInfo& info)
{
Expand Down
15 changes: 8 additions & 7 deletions src/audio/engine/DeviceSetup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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;
Expand All @@ -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();
Expand Down Expand Up @@ -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.
Expand Down
17 changes: 16 additions & 1 deletion src/audio/engine/DeviceSetup.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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);
Expand Down
Loading
Loading