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
114 changes: 63 additions & 51 deletions src/Main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3332,10 +3332,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr
juce::String restoreSavedMixerSession(bool startupOnSavedDevice=false,
armix::session::MixerDeviceBindingPolicy::Mode bindingMode=
armix::session::MixerDeviceBindingPolicy::Mode::exact) {
if(!engine_.allOutputsDisarmed() || mixerSessionWorker_.busy() || logicalVendorEditor_ ||
nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending())
return "MUTE output and finish Studio IO before restoring mixer";
using Recovery=armix::session::NativeMixerSessionRecovery;
Recovery::RestoreContext restore;
restore.outputsDisarmed=engine_.allOutputsDisarmed();
restore.workerBusy=mixerSessionWorker_.busy();
restore.vendorEditorOpen=logicalVendorEditor_.has_value();
restore.showBusy=nativeShowBusy_;
restore.backupBusy=studioBackupBusy_;
restore.graphPending=engine_.isGraphSwitchPending();
const auto blocked=Recovery::restoreBlocker(restore);
if(blocked)return blocked;
const armix::session::NativeMixerSessionStore store(settingsDirectory());
armix::session::MixerSessionDocument doc;
std::vector<armix::shows::BinaryState> states;
Expand Down Expand Up @@ -3431,41 +3437,48 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr
bool shutdownCheckpoint=false) {
const bool automatic=exportFile==juce::File{};
ensureLogicalWorkspace();
if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_||
catalog_.busy()||engine_.isGraphSwitchPending())
return "Mixer is busy. Try again after the current operation.";
if(logicalMixer_.readOnly())
return "Saved mixer recovery required before writing a new session";
using Recovery=armix::session::NativeMixerSessionRecovery;
const auto liveState=engine_.status();
const auto live=liveState.getProperty("dryRoutingLab",{});
const auto observed=approvedNativeSnapshot(liveState);
const auto session=observed.getProperty("mixerSession",{});
const bool m4Active=session.getProperty("authority","").toString()=="M4";
if(!static_cast<bool>(live.getProperty("nativeChannelIdPcmActive",false)) &&
!m4Active && !engine_.secondaryArmed()) {
if(engine_.hasRetainedNativeSession())
return "Retained native mixer still owns the session";
// Logical edits and Open already commit HEAD before ACK.
if(automatic)return {};
const auto session=approvedNativeSnapshot(liveState)
.getProperty("mixerSession",{});
// JUCE AudioIODevice::isOpen() is deliberately non-const.
auto* audio=engine_.devices().getCurrentAudioDevice();
Recovery::SaveContext save;
save.automatic=automatic;
save.workerBusy=mixerSessionWorker_.busy();
save.showBusy=nativeShowBusy_;
save.backupBusy=studioBackupBusy_;
save.catalogBusy=catalog_.busy();
save.graphPending=engine_.isGraphSwitchPending();
save.deviceBusy=deviceApply_.busy();
save.vendorEditorOpen=logicalVendorEditor_.has_value();
save.readOnly=logicalMixer_.readOnly();
save.channelIdInstalled=static_cast<bool>(
live.getProperty("nativeChannelIdPcmActive",false));
save.m4Installed=session.getProperty("authority","").toString()=="M4";
save.secondaryArmed=engine_.secondaryArmed();
save.retainedNative=engine_.hasRetainedNativeSession();
save.recoveryPending=mixerSessionRecoveryPending_;
save.shutdownCheckpoint=shutdownCheckpoint;
save.physicalOpen=audio!=nullptr && audio->isOpen();
save.directAuthorized=engine_.directRouteAuthorized();
save.mainInterrupted=engine_.mainInterruptedByDevice();
const auto decision=Recovery::planSave(save);
if(decision.action==Recovery::SaveAction::reject)
return juce::String(decision.error);
if(decision.action==Recovery::SaveAction::unchanged)
return {}; // Offline autosave: prior logical transaction already committed HEAD.
if(decision.action==Recovery::SaveAction::exportLogical) {
auto safe=juce::Component::SafePointer<ConsoleWindow>(this);
if(!logicalMixer_.exportTo(exportFile,[safe](juce::String error){
if(safe!=nullptr)safe->emitMixerSessionAck("SAVE",error);
}))return "Mixer session IO worker unavailable";
return {};
}
if(automatic&&mixerSessionRecoveryPending_)
return "The retained mixer checkpoint is awaiting a verified device";
// Auto-checkpoints must never replace an acknowledged .smix with a
// transient STOP/default/empty device state. Keep the last verified
// file on disk until the original physical route has returned.
if(automatic && !shutdownCheckpoint) {
auto* audio=engine_.devices().getCurrentAudioDevice();
if(!audio || !audio->isOpen() || !engine_.directRouteAuthorized() ||
engine_.mainInterruptedByDevice())
return "Automatic checkpoint paused until audio device recovery";
}
// Only a CONTROL-approved installed session reaches the temporary
// output capture fence; never move plugin capture to the audio callback.
const bool monitoring=engine_.isMonitorEnabled();
if(engine_.secondaryArmed())return "Stop STREAM before saving the mixer";
const auto epoch=engine_.dryRoutingLabEpoch();
// Temporary capture fence is NOT an operator MUTE. Keep the
// persisted MAIN desire intact across device loss during Save.
Expand All @@ -3491,16 +3504,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr
// browser-provided plugin name or relocate an arbitrary VST3 path.
error=resolveMixerSessionCatalog(doc,true);
if(error.isNotEmpty())return error;
doc.savedMs=1; // signature excludes wall time; includes FX state hashes
const auto canonical=armix::session::Codec::encode(doc);
armix::session::MixerSessionDocument verified;
if(!armix::session::Codec::decode(canonical,verified))
return "Mixer session document validation rejected";
const auto fingerprint=juce::SHA256(canonical.toRawUTF8(),
canonical.getNumBytesAsUTF8()).toHexString();
if(automatic&&fingerprint==lastMixerSessionFingerprint_)
return {};
doc.savedMs=juce::Time::currentTimeMillis();
const auto staged=Recovery::stageSave(doc,automatic,
lastMixerSessionFingerprint_,juce::Time::currentTimeMillis());
if(staged.error.isNotEmpty())return staged.error;
if(staged.unchanged)return {};
const auto fingerprint=staged.fingerprint;
const auto pendingId=doc.id;
auto safe=juce::Component::SafePointer<ConsoleWindow>(this);
if(!mixerSessionWorker_.save(settingsDirectory(),std::move(doc),
Expand Down Expand Up @@ -3537,24 +3545,28 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr
std::vector<armix::shows::BinaryState> states) {
if(safe==nullptr)return;
auto& engine=safe->engine_;
if(error.isEmpty() && (safe->nativeShowBusy_||safe->studioBackupBusy_||
safe->catalog_.busy()||engine.isGraphSwitchPending()||
chosenEpoch!=engine.dryRoutingLabEpoch()))
error="Mixer or audio device changed while opening the file";
if(error.isEmpty()&&engine.secondaryArmed())
error="Stop STREAM before opening a mixer";
using Recovery=armix::session::NativeMixerSessionRecovery;
const auto liveState=engine.status();
const auto lab=liveState.getProperty("dryRoutingLab",{});
const auto session=safe->approvedNativeSnapshot(liveState)
.getProperty("mixerSession",{});
const bool physical=static_cast<bool>(lab.getProperty(
"nativeChannelIdPcmActive",false)) ||
session.getProperty("authority","").toString()=="M4";
if(error.isEmpty()&&!physical&&engine.hasRetainedNativeSession())
error="Retained native mixer still owns the session";
Recovery::OpenContext opening;
opening.operationBusy=safe->nativeShowBusy_ || safe->studioBackupBusy_ ||
safe->catalog_.busy() || safe->deviceApply_.busy() ||
engine.isGraphSwitchPending();
opening.vendorEditorOpen=safe->logicalVendorEditor_.has_value();
opening.epochChanged=chosenEpoch!=engine.dryRoutingLabEpoch();
opening.secondaryArmed=engine.secondaryArmed();
opening.channelIdInstalled=static_cast<bool>(
lab.getProperty("nativeChannelIdPcmActive",false));
opening.m4Installed=session.getProperty("authority","").toString()=="M4";
opening.retainedNative=engine.hasRetainedNativeSession();
const auto decision=Recovery::planOpen(opening);
if(error.isEmpty() && decision.action==Recovery::OpenAction::reject)
error=decision.error;
const auto importedHotkeys=doc.hotkeys;
const auto importedId=doc.id;
if(error.isEmpty()&&!physical) {
if(error.isEmpty() && decision.action==Recovery::OpenAction::openLogical) {
// Open the real .smix into the same stable-ID logical
// document. Never demand audio hardware or instantiate VST3
// just to inspect and edit a saved mixer.
Expand Down
123 changes: 123 additions & 0 deletions src/NativeMixerSessionRecovery.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,129 @@ class NativeMixerSessionRecovery final {
return {Source::head,std::move(error)};
}

struct RestoreContext {
bool outputsDisarmed = false;
bool workerBusy = false;
bool vendorEditorOpen = false;
bool showBusy = false;
bool backupBusy = false;
bool graphPending = false;
};
static const char* restoreBlocker(const RestoreContext& c) noexcept {
return (!c.outputsDisarmed || c.workerBusy || c.vendorEditorOpen ||
c.showBusy || c.backupBusy || c.graphPending) ?
"MUTE output and finish Studio IO before restoring mixer" : nullptr;
}

struct SaveStage {
juce::String error;
juce::String fingerprint;
bool unchanged = false;
};
// Canonical fingerprint deliberately ignores savedMs. A failed worker
// never promotes it; only an accepted automatic checkpoint may dedupe.
// Disk persistence, binary blob hashing and HEAD admission remain owned
// by the existing NativeMixerSessionStore/SaveWorker.
static SaveStage stageSave(MixerSessionDocument& doc,
bool automatic,
const juce::String& acceptedFingerprint,
juce::int64 capturedAtMs) {
doc.savedMs=1;
const auto canonical=Codec::encode(doc);
MixerSessionDocument verified;
if(!Codec::decode(canonical,verified))
return {"Mixer session document validation rejected",{},false};
const auto fingerprint=juce::SHA256(canonical.toRawUTF8(),
canonical.getNumBytesAsUTF8()).toHexString();
if(automatic && fingerprint==acceptedFingerprint)
return {{},fingerprint,true};
doc.savedMs=capturedAtMs;
return {{},fingerprint,false};
}

// One CONTROL-thread admission policy for .smix SAVE/OPEN. The host
// supplies observed native authority and keeps OS dialogs, callbacks,
// physical graph ownership and UI ACK/readback; no shadow session state.
enum class SaveAction { reject, unchanged, exportLogical, captureInstalled };
struct SaveContext {
bool automatic = false;
bool workerBusy = false;
bool showBusy = false;
bool backupBusy = false;
bool catalogBusy = false;
bool graphPending = false;
bool readOnly = false;
bool deviceBusy = false;
bool vendorEditorOpen = false;
bool channelIdInstalled = false;
bool m4Installed = false;
bool secondaryArmed = false;
bool retainedNative = false;
bool recoveryPending = false;
bool shutdownCheckpoint = false;
bool physicalOpen = false;
bool directAuthorized = false;
bool mainInterrupted = false;
};
struct SavePlan {
SaveAction action;
const char* error = nullptr;
};
static SavePlan planSave(const SaveContext& c) noexcept {
if(c.workerBusy || c.showBusy || c.backupBusy ||
c.catalogBusy || c.graphPending || c.deviceBusy)
return {SaveAction::reject,
"Mixer is busy. Try again after the current operation."};
if(c.vendorEditorOpen)
return {SaveAction::reject, "Close the vendor FX editor to save its settings first"};
if(c.readOnly)
return {SaveAction::reject,
"Saved mixer recovery required before writing a new session"};
if(!c.channelIdInstalled && !c.m4Installed && !c.secondaryArmed) {
if(c.retainedNative)
return {SaveAction::reject, "Retained native mixer still owns the session"};
return {c.automatic ? SaveAction::unchanged : SaveAction::exportLogical, nullptr};
}
if(c.automatic && c.recoveryPending)
return {SaveAction::reject,
"The retained mixer checkpoint is awaiting a verified device"};
if(c.automatic && !c.shutdownCheckpoint &&
(!c.physicalOpen || !c.directAuthorized || c.mainInterrupted))
return {SaveAction::reject,
"Automatic checkpoint paused until audio device recovery"};
if(c.secondaryArmed)
return {SaveAction::reject, "Stop STREAM before saving the mixer"};
return {SaveAction::captureInstalled, nullptr};
}

enum class OpenAction { reject, openLogical, restoreInstalled };
struct OpenContext {
bool operationBusy = false;
bool epochChanged = false;
bool vendorEditorOpen = false;
bool secondaryArmed = false;
bool channelIdInstalled = false;
bool m4Installed = false;
bool retainedNative = false;
};
struct OpenPlan {
OpenAction action;
const char* error = nullptr;
};
static OpenPlan planOpen(const OpenContext& c) noexcept {
if(c.operationBusy || c.epochChanged)
return {OpenAction::reject,
"Mixer or audio device changed while opening the file"};
if(c.vendorEditorOpen)
return {OpenAction::reject, "Close the vendor FX editor to save its settings first"};
if(c.secondaryArmed)
return {OpenAction::reject, "Stop STREAM before opening a mixer"};
if(!c.channelIdInstalled && !c.m4Installed && c.retainedNative)
return {OpenAction::reject, "Retained native mixer still owns the session"};
return {c.channelIdInstalled || c.m4Installed ?
OpenAction::restoreInstalled : OpenAction::openLogical, nullptr};
}

struct Context {
BindingMode bindingMode;
Source source;
Expand Down
14 changes: 11 additions & 3 deletions tests/audio_continuity_contract_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const main=read('src/Main.cpp');
const engine=read('src/LiveAudioEngine.h');
const policy=read('engine/device/AudioContinuityPolicy.h');
const coordinator=read('src/NativeDeviceApplyCoordinator.h');
const sessionRecovery=read('src/NativeMixerSessionRecovery.h');
const cmake=read('CMakeLists.txt');

test('display sleep never changes logical mixer intent or device configuration',()=>{
Expand Down Expand Up @@ -69,7 +70,7 @@ test('WASAPI recovery fails closed against substituted endpoint names or pin mas

test('session capture and shutdown keep requested MAIN through a device STOP',()=>{
const capture=main.split('juce::String saveMixerSession(bool resumeMain')[1]
.split('const auto canonical=')[0];
.split('const auto pendingId=doc.id;')[0];
assert.match(capture,/if\(monitoring\)engine_\.setOutputMuted\(true\)/);
assert.match(capture,/engine_\.setOutputMuted\(false\)/);
assert.doesNotMatch(capture,/engine_\.setMonitorEnabled\(/);
Expand All @@ -82,9 +83,16 @@ test('session capture and shutdown keep requested MAIN through a device STOP',()
test('automatic checkpoints cannot overwrite saved MAIN and device binding during STOP',()=>{
const save=main.split('juce::String saveMixerSession(bool resumeMain')[1]
.split('void openMixerFile(')[0];
assert.match(save,/!audio \|\| !audio->isOpen\(\)/);
assert.match(save,/if\(automatic && !shutdownCheckpoint\)/);
// Recovery is the single SAVE admission owner; Main provides physical
// readback evidence. STOP must never be an implicit checkpoint success.
const admit=sessionRecovery.split('static SavePlan planSave(')[1]
.split('enum class OpenAction')[0];
assert.match(save,/audio!=nullptr && audio->isOpen\(\)/);
assert.match(save,/engine_\.mainInterruptedByDevice\(\)/);
assert.match(save,/Recovery::planSave\(/);
assert.match(admit,/c\.automatic && !c\.shutdownCheckpoint/);
assert.match(admit,/!c\.physicalOpen \|\| !c\.directAuthorized \|\| c\.mainInterrupted/);
assert.match(admit,/SaveAction::reject/);
assert.match(save,/doc\.resumeMain=resumeMain \|\|/);
assert.match(save,/engine_\.wantsMainContinuation\(\) && !operatorOutputMuted_/);
const persistence=main.split('if (deviceSettingsDirty_)')[1]
Expand Down
9 changes: 8 additions & 1 deletion tests/mixer_io_operator_contract_test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,14 @@ test('offline checkpoints stay protected until verified native restore',()=>{
assert.match(open,/if\(openError.isEmpty\(\)\)[\s\S]*?"LOGICAL_SESSION_OPENED_UNBOUND"/);
const control=read('src/NativeLogicalMixerControl.h');
assert.match(control,/workspace_=std::move\(\*candidate\);[\s\S]*?checkpointSaved_\(workspace_.document\(\).id\)/);
assert.match(save,/if\(automatic&&mixerSessionRecoveryPending_\)[\s\S]*?return "[^"]+";[\s\S]*?captureNativeMixerSession/);
// Admission is now the existing NativeMixerSessionRecovery owner, not
// an inline ConsoleWindow conditional. The rejection must occur before PCM capture.
const recovery=read('src/NativeMixerSessionRecovery.h');
const policy=recovery.slice(recovery.indexOf('static SavePlan planSave('),
recovery.indexOf('enum class OpenAction'));
assert.match(policy,/if\(c\.automatic && c\.recoveryPending\)[\s\S]*?SaveAction::reject/);
assert.match(save,/save\.recoveryPending=mixerSessionRecoveryPending_/);
assert.match(save,/Recovery::planSave\(save\)[\s\S]*?SaveAction::reject[\s\S]*?captureNativeMixerSession/);
});

// Exact control-thread serialization source contract for nested JUCE modal loops.
Expand Down
Loading
Loading