From da1ce7f60a9de87b25f883a725ace46293603b56 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:17:36 +0700 Subject: [PATCH 01/24] refactor(native-mv14): extract Player v1-v3 setlist archive codec from ConsoleWindow Keep one Player deck and native disk writer. Isolate schema validation/migration/serialization in a control-only service, reject inconsistent song/control state before persistence, add JUCE CTest for legacy migration and safe round-trip. --- CMakeLists.txt | 12 ++ src/Main.cpp | 128 ++++------------------ src/PlayerSetlistArchive.h | 152 ++++++++++++++++++++++++++ tests/player_setlist_archive_test.cpp | 112 +++++++++++++++++++ 4 files changed, 295 insertions(+), 109 deletions(-) create mode 100644 src/PlayerSetlistArchive.h create mode 100644 tests/player_setlist_archive_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b65591033..ac70ad7e2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1234,6 +1234,18 @@ if(BUILD_TESTING) add_dependencies(ARMixMixerRoutingTests ARMixPlayerShowEditTests ARMixPlayerWaveformTests ARMixPlayerCrossfadeTests ARMixPlayerShowTransitionTests) + # MV-N14: isolated archive codec regression, no extra CI workflow, + # playback owner, audio callback or device requirement. + juce_add_console_app(ARMixPlayerSetlistArchiveTests + PRODUCT_NAME "ArSonMix Player Setlist Archive Contract") + target_sources(ARMixPlayerSetlistArchiveTests PRIVATE + tests/player_setlist_archive_test.cpp) + target_link_libraries(ARMixPlayerSetlistArchiveTests PRIVATE + juce::juce_core juce::juce_recommended_config_flags) + target_compile_features(ARMixPlayerSetlistArchiveTests PRIVATE cxx_std_20) + add_test(NAME ArSonPlayerV1V2V3SetlistArchiveMigrationAndPersistence + COMMAND ARMixPlayerSetlistArchiveTests) + add_dependencies(ARMixMixerRoutingTests ARMixPlayerSetlistArchiveTests) juce_add_console_app(ARMixPlayerDecodeTests PRODUCT_NAME "ArSon Player Native Decoder Integration") target_sources(ARMixPlayerDecodeTests PRIVATE tests/player_native_decode_test.cpp) target_link_libraries(ARMixPlayerDecodeTests PRIVATE diff --git a/src/Main.cpp b/src/Main.cpp index 7b5e76c1b..94143ee08 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -45,6 +45,7 @@ #include "NativeChannelAppearanceStore.h" #include "NativeMixerSessionSaveWorker.h" #include "NativeLogicalMixerControl.h" +#include "PlayerSetlistArchive.h" #include "NativeHotkeyRegistry.h" #include "NativeFxParameterHotkey.h" #include "NativeFxControlRequest.h" @@ -541,16 +542,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // library/controls so decoder bindings and FX routing do not change. // Save/restore swaps complete sets, not two independently mutated arrays. std::vector playerLibrary_; - struct PlayerTrackSettings { - int key=0,tempo=100; - double cueIn=0.,cueOut=0.; // seconds, 0 OUT means media end - }; + using PlayerTrackSettings=armix::player::PlayerTrackSettings; + using PlayerSavedSet=armix::player::PlayerSavedSet; std::vector playerTrackSettings_; - struct PlayerSavedSet { - juce::String name; - std::vector files; - std::vector controls; - }; std::vector playerSets_; int playerActiveSet_=0; std::vector playerQueue_; // transient ordered PLAY NEXT queue @@ -4011,6 +4005,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerOutputPendingIndex_=-1; playerUndoRemove_={}; } + // Player archive owns only v1/v2/v3 JSON policy and deterministic mapping. + // ConsoleWindow retains the sole disk writer, set activation and deck. void restorePlayerLibrary() { playerSets_.clear(); const auto file=settingsDirectory().getChildFile("player-library.json"); @@ -4018,116 +4014,30 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerSets_.push_back({"My Setlist",{},{}}); return; } - const auto json=juce::JSON::parse(file.loadFileAsString()); - const int version=static_cast(json.getProperty("version",0)); - if(!json.isObject() || (version!=1 && version!=2 && version!=3)) { + auto parsed=armix::player::PlayerSetlistArchive::parse( + juce::JSON::parse(file.loadFileAsString())); + if(!parsed) { playerSets_.push_back({"My Setlist",{},{}}); playerError_="Setlists could not be read; no music files were changed"; return; } - const auto parseSongs=[&](const juce::var& items,int itemVersion, - PlayerSavedSet& destination) { - if(const auto* list=items.getArray()) { - for(const auto& item:*list) { - if(destination.files.size()>=2000)break; - if((itemVersion==1 && !item.isString()) || - (itemVersion>=2 && !item.isObject()))continue; - const auto path=itemVersion==1?item.toString(): - item.getProperty("path","").toString(); - if(path.isEmpty() || path.length()>4096 || - !juce::File::isAbsolutePath(path))continue; - const juce::File source(path); - if(!source.hasFileExtension("wav;mp3;flac;aif;aiff;ogg") || - std::find(destination.files.begin(), - destination.files.end(),source) - !=destination.files.end())continue; - PlayerTrackSettings preset; - if(itemVersion>=2) { - preset.key=static_cast(item.getProperty("key",0)); - preset.tempo=static_cast(item.getProperty("tempo",100)); - if(preset.key< -6 || preset.key>6 || - preset.tempo<80 || preset.tempo>120)preset={}; - } - if(itemVersion>=3) { - const double in=static_cast( - item.getProperty("cueIn",0.0)); - const double out=static_cast( - item.getProperty("cueOut",0.0)); - // Invalid saved markers never alter native playback. - if(std::isfinite(in) && std::isfinite(out) && - in>=0. && out>=0. && in<86400. && - out<86400. && (out==0. || out>in+0.05)) { - preset.cueIn=in;preset.cueOut=out; - } - } - destination.files.push_back(source); - destination.controls.push_back(preset); - } - } - }; - // Keep the variant alive throughout the array walk. A pointer - // returned from a temporary juce::var would dangle in the body. - const auto savedSets=json.getProperty("setlists",{}); - if(version<=2) { - PlayerSavedSet migrated{"My Setlist",{},{}}; - parseSongs(json.getProperty("files",{}),version,migrated); - playerSets_.push_back(std::move(migrated)); - } else if(const auto* sets=savedSets.getArray()) { - for(const auto& source:*sets) { - if(playerSets_.size()>=32)break; - if(!source.isObject())continue; - auto name=source.getProperty("name","").toString().trim(); - if(name.isEmpty() || name.length()>64)continue; - const bool duplicate=std::any_of( - playerSets_.begin(),playerSets_.end(), - [&](const PlayerSavedSet& set) { - return set.name.equalsIgnoreCase(name); - }); - if(duplicate)continue; - PlayerSavedSet next{name,{},{}}; - parseSongs(source.getProperty("files",{}),3,next); - playerSets_.push_back(std::move(next)); - } - } - if(playerSets_.empty())playerSets_.push_back({"My Setlist",{},{}}); - const int active=version==3? - static_cast(json.getProperty("activeSetlist",0)):0; - activatePlayerSet(std::clamp(active,0, - static_cast(playerSets_.size())-1)); - playerAutoNext_=json.getProperty("autoNext",false).isBool() && - static_cast(json.getProperty("autoNext",false)); - const int fade=static_cast(json.getProperty("crossfadeMs",180)); - playerFadeMilliseconds_=(fade>=0 && fade<=3000)?fade:180; + playerSets_=std::move(parsed->sets); + activatePlayerSet(parsed->active); + playerAutoNext_=parsed->autoNext; + playerFadeMilliseconds_=parsed->fadeMs; } void persistPlayerLibrary() { saveActivePlayerSet(); - auto document=std::make_unique(); - document->setProperty("version",3); - document->setProperty("activeSetlist",playerActiveSet_); - document->setProperty("autoNext",playerAutoNext_); - document->setProperty("crossfadeMs",playerFadeMilliseconds_); - juce::Array sets; - for(const auto& set:playerSets_) { - auto object=std::make_unique(); - object->setProperty("name",set.name); - juce::Array files; - for(std::size_t i=0;i(); - entry->setProperty("path",set.files[i].getFullPathName()); - entry->setProperty("key",set.controls[i].key); - entry->setProperty("tempo",set.controls[i].tempo); - entry->setProperty("cueIn",set.controls[i].cueIn); - entry->setProperty("cueOut",set.controls[i].cueOut); - files.add(juce::var(entry.release())); - } - object->setProperty("files",juce::var(files)); - sets.add(juce::var(object.release())); - } - document->setProperty("setlists",juce::var(sets)); + const auto document=armix::player::PlayerSetlistArchive::serialize( + playerSets_,playerActiveSet_,playerAutoNext_,playerFadeMilliseconds_); + if(!document.isObject()) { + playerError_="Unable to save setlists; invalid setlist state"; + return; + } const auto target=settingsDirectory().getChildFile("player-library.json"); juce::TemporaryFile staging(target); if(!staging.getFile().replaceWithText( - juce::JSON::toString(juce::var(document.release()),false)) || + juce::JSON::toString(document,false)) || !staging.overwriteTargetFileWithTemporary()) playerError_="Unable to save setlists; check folder permissions"; } diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h new file mode 100644 index 000000000..4d8586057 --- /dev/null +++ b/src/PlayerSetlistArchive.h @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// MV-N14: control-thread-only schema v1/v2/v3 codec. One Player deck remains +// owned by ConsoleWindow/LiveAudioEngine; this codec does no file I/O, +// transport, device access, mutation of a live setlist or realtime work. +namespace armix::player { +struct PlayerTrackSettings { + int key=0, tempo=100; + double cueIn=0., cueOut=0.; +}; +struct PlayerSavedSet { + juce::String name; + std::vector files; + std::vector controls; +}; +struct PlayerSetlistDocument { + std::vector sets; + int active=0; + bool autoNext=false; + int fadeMs=180; +}; +class PlayerSetlistArchive final { + static void parseSongs(const juce::var& items,int version, + PlayerSavedSet& destination) { + const auto* entries=items.getArray(); + if(entries==nullptr)return; + for(const auto& item:*entries) { + if(destination.files.size()>=2000)break; + if((version==1&&!item.isString()) || + (version>=2&&!item.isObject()))continue; + const auto path=version==1?item.toString(): + item.getProperty("path","").toString(); + if(path.isEmpty()||path.length()>4096|| + !juce::File::isAbsolutePath(path))continue; + const juce::File source(path); + if(!source.hasFileExtension("wav;mp3;flac;aif;aiff;ogg") || + std::find(destination.files.begin(),destination.files.end(),source) + !=destination.files.end())continue; + PlayerTrackSettings settings; + if(version>=2) { + settings.key=static_cast(item.getProperty("key",0)); + settings.tempo=static_cast(item.getProperty("tempo",100)); + if(settings.key< -6||settings.key>6|| + settings.tempo<80||settings.tempo>120)settings={}; + } + if(version>=3) { + const double cueIn=static_cast( + item.getProperty("cueIn",0.0)); + const double cueOut=static_cast( + item.getProperty("cueOut",0.0)); + if(std::isfinite(cueIn)&&std::isfinite(cueOut)&& + cueIn>=0.&&cueOut>=0.&&cueIn<86400.&&cueOut<86400.&& + (cueOut==0.||cueOut>cueIn+0.05)) { + settings.cueIn=cueIn; + settings.cueOut=cueOut; + } + } + destination.files.push_back(source); + destination.controls.push_back(settings); + } + } +public: + static std::optional parse(const juce::var& json) { + if(!json.isObject())return std::nullopt; + const int version=static_cast(json.getProperty("version",0)); + if(version!=1&&version!=2&&version!=3)return std::nullopt; + PlayerSetlistDocument document; + // Retain the variant while walking arrays; a pointer into a + // temporary juce::var would dangle. + const auto setlists=json.getProperty("setlists",{}); + if(version<=2) { + PlayerSavedSet migrated{"My Setlist",{},{}}; + parseSongs(json.getProperty("files",{}),version,migrated); + document.sets.push_back(std::move(migrated)); + } else if(const auto* saved=setlists.getArray()) { + for(const auto& item:*saved) { + if(document.sets.size()>=32)break; + if(!item.isObject())continue; + auto name=item.getProperty("name","").toString().trim(); + if(name.isEmpty()||name.length()>64)continue; + const bool duplicate=std::any_of(document.sets.begin(), + document.sets.end(),[&](const PlayerSavedSet& s) { + return s.name.equalsIgnoreCase(name); + }); + if(duplicate)continue; + PlayerSavedSet next{name,{},{}}; + parseSongs(item.getProperty("files",{}),3,next); + document.sets.push_back(std::move(next)); + } + } + if(document.sets.empty()) + document.sets.push_back({"My Setlist",{},{}}); + const int active=version==3? + static_cast(json.getProperty("activeSetlist",0)):0; + document.active=std::clamp(active,0, + static_cast(document.sets.size())-1); + const auto autoNext=json.getProperty("autoNext",false); + document.autoNext=autoNext.isBool()&&static_cast(autoNext); + const int fade=static_cast(json.getProperty("crossfadeMs",180)); + document.fadeMs=(fade>=0&&fade<=3000)?fade:180; + return document; + } + + static juce::var serialize(const std::vector& sets, + int active,bool autoNext,int fadeMs) { + // Reject inconsistent in-memory state BEFORE writing a checkpoint. + // Never truncate song/control pairs or silently persist a broken show. + if(sets.empty()||sets.size()>32||active<0|| + active>=static_cast(sets.size())|| + fadeMs<0||fadeMs>3000)return {}; + for(const auto& s:sets) + if(s.files.size()!=s.controls.size()||s.files.size()>2000) + return {}; + auto document=juce::var(new juce::DynamicObject()); + auto* out=document.getDynamicObject(); + out->setProperty("version",3); + out->setProperty("activeSetlist",active); + out->setProperty("autoNext",autoNext); + out->setProperty("crossfadeMs",fadeMs); + juce::Array savedSets; + for(const auto& set:sets) { + auto row=juce::var(new juce::DynamicObject()); + row.getDynamicObject()->setProperty("name",set.name); + juce::Array songs; + for(std::size_t i=0;isetProperty( + "path",set.files[i].getFullPathName()); + song.getDynamicObject()->setProperty("key",set.controls[i].key); + song.getDynamicObject()->setProperty( + "tempo",set.controls[i].tempo); + song.getDynamicObject()->setProperty( + "cueIn",set.controls[i].cueIn); + song.getDynamicObject()->setProperty( + "cueOut",set.controls[i].cueOut); + songs.add(std::move(song)); + } + row.getDynamicObject()->setProperty("files",juce::var(songs)); + savedSets.add(std::move(row)); + } + out->setProperty("setlists",juce::var(savedSets)); + return document; + } +}; +} // namespace armix::player diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp new file mode 100644 index 000000000..1e03693d7 --- /dev/null +++ b/tests/player_setlist_archive_test.cpp @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include "../src/PlayerSetlistArchive.h" + +using Archive=armix::player::PlayerSetlistArchive; +using SavedSet=armix::player::PlayerSavedSet; +using Track=armix::player::PlayerTrackSettings; + +static juce::var object() {return juce::var(new juce::DynamicObject());} +static juce::var song(const juce::String& path,int key=0,int tempo=100, + double in=0.,double out=0.) { + auto v=object(); + auto* d=v.getDynamicObject(); + d->setProperty("path",path); + d->setProperty("key",key); + d->setProperty("tempo",tempo); + d->setProperty("cueIn",in); + d->setProperty("cueOut",out); + return v; +} +static juce::var set(const juce::String& name, + const juce::Array& songs) { + auto v=object(); + v.getDynamicObject()->setProperty("name",name); + v.getDynamicObject()->setProperty("files",juce::var(songs)); + return v; +} +int main() { + const auto path=juce::File::getSpecialLocation( + juce::File::tempDirectory).getChildFile("arsonmix-mv14-setlist.wav") + .getFullPathName(); + const auto other=juce::File::getSpecialLocation( + juce::File::tempDirectory).getChildFile("arsonmix-mv14-other.mp3") + .getFullPathName(); + // Invalid document/version never causes disk or player changes. + assert(!Archive::parse(juce::var{})); + assert(!Archive::parse(juce::JSON::parse("{\"version\":8}"))); + auto v1=object();v1.getDynamicObject()->setProperty("version",1); + juce::Array paths; + paths.add(path);paths.add(path);paths.add("relative.mp3"); + paths.add(juce::File(path).withFileExtension(".txt").getFullPathName()); + v1.getDynamicObject()->setProperty("files",juce::var(paths)); + auto doc=Archive::parse(v1); + assert(doc && doc->sets.size()==1 && doc->sets[0].files.size()==1); + assert(doc->sets[0].name=="My Setlist"); + assert(doc->sets[0].controls[0].key==0); + assert(doc->sets[0].controls[0].tempo==100); + + auto v2=object();v2.getDynamicObject()->setProperty("version",2); + juce::Array oldSongs; + oldSongs.add(song(path,4,105));oldSongs.add(song(other,7,99)); + v2.getDynamicObject()->setProperty("files",juce::var(oldSongs)); + doc=Archive::parse(v2); + assert(doc && doc->sets[0].files.size()==2); + assert(doc->sets[0].controls[0].key==4); + assert(doc->sets[0].controls[0].tempo==105); + assert(doc->sets[0].controls[1].key==0); + assert(doc->sets[0].controls[1].tempo==100); + + auto v3=object();v3.getDynamicObject()->setProperty("version",3); + juce::Array sets; + juce::Array songs; + songs.add(song(path,-5,115,2.0,9.0)); + songs.add(song(other,2,105,10.0,9.0)); // invalid OUT, cue stays zero + sets.add(set("Soundcheck",songs)); + sets.add(set("soundCHECK",songs)); // duplicate case-insensitive name + sets.add(set("Live Show",{})); + v3.getDynamicObject()->setProperty("setlists",juce::var(sets)); + v3.getDynamicObject()->setProperty("activeSetlist",999); + v3.getDynamicObject()->setProperty("autoNext",true); + v3.getDynamicObject()->setProperty("crossfadeMs",3100); + doc=Archive::parse(v3); + assert(doc && doc->sets.size()==2 && doc->active==1); + assert(doc->autoNext && doc->fadeMs==180); + assert(doc->sets[0].files.size()==2); + assert(doc->sets[0].controls[0].cueIn==2.0); + assert(doc->sets[0].controls[0].cueOut==9.0); + assert(doc->sets[0].controls[1].cueIn==0.0); + assert(doc->sets[0].controls[1].cueOut==0.0); + + // Canonical v3 JSON is a complete round trip, no copying/deleting media. + const auto encoded=Archive::serialize(doc->sets,doc->active,true,250); + assert(encoded.isObject()); + assert(encoded.getProperty("version",0)==juce::var(3)); + auto decoded=Archive::parse(juce::JSON::parse( + juce::JSON::toString(encoded,false))); + assert(decoded && decoded->sets.size()==2); + assert(decoded->active==1 && decoded->fadeMs==250); + assert(decoded->sets[0].files[0].getFullPathName()==path); + assert(decoded->sets[0].controls[0].cueIn==2.0); + + // Broken song/control cardinality must fail closed before staging JSON. + std::vector broken{{"Broken",{juce::File(path)}, {}}}; + assert(!Archive::serialize(broken,0,false,180).isObject()); + assert(!Archive::serialize(doc->sets,5,false,180).isObject()); + assert(!Archive::serialize(doc->sets,1,false,-1).isObject()); + assert(!Archive::serialize({},0,false,180).isObject()); + + // Legacy empty v3 content migrates to a non-destructive default setlist. + const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); + assert(empty && empty->sets.size()==1); + assert(empty->sets[0].name=="My Setlist"); + assert(empty->sets[0].files.empty()); + + std::cout<<"PASS: v1/v2/v3 migration, physical path identity, cue fence, " + "safe archive round-trip and fail-closed persistence\n"; + return 0; +} From a565269698ee2f82b3d2d8d6bb961b9c68eac566 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:19:29 +0700 Subject: [PATCH 02/24] test(native-mv14): resolve PlayerTrackSettings owner after archive extraction --- tests/native_caption_wire_geometry_contract.test.cjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index c0c985b41..82cdb7144 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -128,7 +128,10 @@ assert.match(page, /document\.addEventListener\('visibilitychange'/); assert.doesNotMatch(page, /resizeQueued=false;render\(\)/); // Reconciled main Player M3 controls must survive the native caption branch. const playerHtml = read('site/preview-v2/assets/mixer-contextual-buttons.js'); -assert.match(main, /struct PlayerTrackSettings/); +// Player native metadata is now owned by the extracted pure archive codec. +const playerArchive = read('src/PlayerSetlistArchive.h'); +assert.match(playerArchive, /struct PlayerTrackSettings/); +assert.match(main, /using PlayerTrackSettings=armix::player::PlayerTrackSettings/); assert.match(main, /action=="playerKeyStep" \|\| action=="playerTempoStep"/); assert.match(main, /setPlayerPitchTempo\(next\.key,next\.tempo\)/); assert.match(playerHtml, /id="playerKeyMinus"/); From 8247cf615925e1626276ad6d3d9d5cbc22983af8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:45:17 +0700 Subject: [PATCH 03/24] fix(native-mv14): keep saved setlist schema round-trip lossless Preflight canonical set names, duplicate audio paths, supported media type and native cue/key/tempo ranges before staging JSON, with deterministic JUCE archive regression cases. --- src/PlayerSetlistArchive.h | 35 +++++++++++++++++++++++++-- tests/player_setlist_archive_test.cpp | 26 ++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index 4d8586057..2dc29dfab 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -2,6 +2,7 @@ #pragma once #include #include +#include #include #include #include @@ -115,9 +116,39 @@ class PlayerSetlistArchive final { if(sets.empty()||sets.size()>32||active<0|| active>=static_cast(sets.size())|| fadeMs<0||fadeMs>3000)return {}; - for(const auto& s:sets) - if(s.files.size()!=s.controls.size()||s.files.size()>2000) + for(std::size_t index=0;index64||name!=s.name|| + s.files.size()!=s.controls.size()||s.files.size()>2000) return {}; + // A saved setlist must be loadable without silently dropping a + // set, song or cue on the next startup. Validate before touching + // the staging file; active Player/PCM ownership is unchanged. + for(std::size_t previous=0;previous4096|| + !juce::File::isAbsolutePath(path)|| + !s.files[i].hasFileExtension("wav;mp3;flac;aif;aiff;ogg")) + return {}; + if(std::find(s.files.begin(),s.files.begin()+static_cast(i), + s.files[i])!=s.files.begin()+static_cast(i)) + return {}; + const auto& settings=s.controls[i]; + if(settings.key< -6||settings.key>6|| + settings.tempo<80||settings.tempo>120|| + !std::isfinite(settings.cueIn)|| + !std::isfinite(settings.cueOut)|| + settings.cueIn<0.||settings.cueOut<0.|| + settings.cueIn>=86400.||settings.cueOut>=86400.|| + (settings.cueOut!=0.&& + settings.cueOut<=settings.cueIn+0.05)) + return {}; + } + } auto document=juce::var(new juce::DynamicObject()); auto* out=document.getDynamicObject(); out->setProperty("version",3); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 1e03693d7..6df9c276c 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -100,6 +100,32 @@ int main() { assert(!Archive::serialize(doc->sets,1,false,-1).isObject()); assert(!Archive::serialize({},0,false,180).isObject()); + // Serializer mirrors the parser's admission rules. Otherwise a saved + // show could silently lose songs or an entire set on the next launch. + auto invalid=doc->sets; + invalid[0].name="Live Show"; // collides case-insensitively with set 1 + assert(!Archive::serialize(invalid,0,false,180).isObject()); + invalid=doc->sets; + invalid[0].name=" "; + assert(!Archive::serialize(invalid,0,false,180).isObject()); + invalid=doc->sets; + invalid[0].files[0]=juce::File(path).withFileExtension(".txt"); + assert(!Archive::serialize(invalid,0,false,180).isObject()); + invalid=doc->sets; + invalid[0].files[0]=invalid[0].files[1]; + assert(!Archive::serialize(invalid,0,false,180).isObject()); + invalid=doc->sets; + invalid[0].controls[0].key=9; + assert(!Archive::serialize(invalid,0,false,180).isObject()); + invalid=doc->sets; + invalid[0].controls[0].tempo=75; + assert(!Archive::serialize(invalid,0,false,180).isObject()); + invalid=doc->sets; + invalid[0].controls[0].cueOut=1.0; // earlier than IN=2 + assert(!Archive::serialize(invalid,0,false,180).isObject()); + // A valid, canonical document still saves and round-trips unchanged. + assert(Archive::serialize(doc->sets,doc->active,true,250).isObject()); + // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); assert(empty && empty->sets.size()==1); From 8820b49f2607f6bee3de88fed300ca242aa813dd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:46:57 +0700 Subject: [PATCH 04/24] perf(native-mv14): enforce duplicate-path safety in O(n log n) save preflight --- src/PlayerSetlistArchive.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index 2dc29dfab..42699c6f0 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -2,9 +2,10 @@ #pragma once #include #include -#include #include #include +#include +#include #include #include @@ -128,14 +129,21 @@ class PlayerSetlistArchive final { for(std::size_t previous=0;previous uniquePaths; for(std::size_t i=0;i4096|| !juce::File::isAbsolutePath(path)|| !s.files[i].hasFileExtension("wav;mp3;flac;aif;aiff;ogg")) return {}; - if(std::find(s.files.begin(),s.files.begin()+static_cast(i), - s.files[i])!=s.files.begin()+static_cast(i)) +#if JUCE_WINDOWS + const auto pathKey=path.toLowerCase().toStdString(); +#else + const auto pathKey=path.toStdString(); +#endif + if(!uniquePaths.insert(pathKey).second) return {}; const auto& settings=s.controls[i]; if(settings.key< -6||settings.key>6|| From dd883f77e7939d4f8ddf3c8c9e66bad5262ab3a0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:50:25 +0700 Subject: [PATCH 05/24] fix(native-mv14): keep setlist creation unique after delete/recreate Use pure PlayerSetlistArchive naming policy to prevent native console creating duplicate setlist names that are correctly rejected by archive persistence. Cover create/delete/create and case-insensitive rename with JUCE CTest. --- src/Main.cpp | 9 +++++++-- src/PlayerSetlistArchive.h | 16 ++++++++++++++++ tests/player_setlist_archive_test.cpp | 15 +++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 94143ee08..16d4b32b5 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -4058,8 +4058,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerError_="Maximum 32 setlists";emitPlayerState();return; } saveActivePlayerSet(); - const int next=static_cast(playerSets_.size())+1; - playerSets_.push_back({"Setlist "+juce::String(next),{},{}}); + const auto next=armix::player::PlayerSetlistArchive:: + nextGeneratedName(playerSets_); + if(next.isEmpty()) { + playerError_="No available setlist name"; + emitPlayerState();return; + } + playerSets_.push_back({next,{},{}}); engine_.playerStop(); activatePlayerSet(static_cast(playerSets_.size())-1); } else { diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index 42699c6f0..d33f83dbf 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -69,6 +69,22 @@ class PlayerSetlistArchive final { } } public: + // Keep automatic creation consistent with the archive's case-insensitive + // uniqueness rule, including a delete-then-create cycle. At <32 sets, + // candidate numbers 2..33 always contain an unused name. + static juce::String nextGeneratedName( + const std::vector& sets) { + for(int number=2;number<=33;++number) { + const auto candidate="Setlist "+juce::String(number); + const bool used=std::any_of(sets.begin(),sets.end(), + [&](const PlayerSavedSet& s) { + return s.name.equalsIgnoreCase(candidate); + }); + if(!used)return candidate; + } + return {}; + } + static std::optional parse(const juce::var& json) { if(!json.isObject())return std::nullopt; const int version=static_cast(json.getProperty("version",0)); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 6df9c276c..0a6073de9 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -126,6 +126,21 @@ int main() { // A valid, canonical document still saves and round-trips unchanged. assert(Archive::serialize(doc->sets,doc->active,true,250).isObject()); + // Create -> delete -> create must never generate a colliding archive name. + std::vector names{ + {"My Setlist",{},{}}, + {"Setlist 2",{},{}}, + {"Setlist 3",{},{}} + }; + assert(Archive::nextGeneratedName(names)=="Setlist 4"); + names.erase(names.begin()+1); // delete Setlist 2, Setlist 3 remains + const auto newName=Archive::nextGeneratedName(names); + assert(newName=="Setlist 2"); + names.push_back({newName,{},{}}); + assert(Archive::serialize(names,2,false,180).isObject()); + names[1].name="SETLIST 2"; // user rename still checked case-insensitively + assert(Archive::nextGeneratedName(names)=="Setlist 4"); + // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); assert(empty && empty->sets.size()==1); From 92991eaaea08cd60eedb7f28a28c10b7be25eceb Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:50:55 +0700 Subject: [PATCH 06/24] test(native-mv14): prove reused setlist number remains unique across case variants --- tests/player_setlist_archive_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 0a6073de9..c3a6b86c1 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -138,7 +138,7 @@ int main() { assert(newName=="Setlist 2"); names.push_back({newName,{},{}}); assert(Archive::serialize(names,2,false,180).isObject()); - names[1].name="SETLIST 2"; // user rename still checked case-insensitively + names[1].name="setLIST 3"; // case-folded name remains occupied assert(Archive::nextGeneratedName(names)=="Setlist 4"); // Legacy empty v3 content migrates to a non-destructive default setlist. From 9210ab3bb92ac642506dd1076871df338a1486b7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:52:10 +0700 Subject: [PATCH 07/24] fix(native-mv14): match JUCE File identity for portable duplicate checks Use std::set to retain O(n log n) deduplication while matching the JUCE parser's platform-specific case comparison; add platform-dynamic case-variant Save/Open regression. --- src/PlayerSetlistArchive.h | 12 ++++-------- tests/player_setlist_archive_test.cpp | 12 ++++++++++++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index d33f83dbf..cdbb40994 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -147,19 +146,16 @@ class PlayerSetlistArchive final { return {}; // O(n log n), rather than O(n^2) file comparisons for large // setlists (up to 2,000 tracks in each of 32 saved sets). - std::set uniquePaths; + // JUCE File::operator< matches File::operator== platform rules, + // including case-insensitive path identity on Windows/macOS. + std::set uniquePaths; for(std::size_t i=0;i4096|| !juce::File::isAbsolutePath(path)|| !s.files[i].hasFileExtension("wav;mp3;flac;aif;aiff;ogg")) return {}; -#if JUCE_WINDOWS - const auto pathKey=path.toLowerCase().toStdString(); -#else - const auto pathKey=path.toStdString(); -#endif - if(!uniquePaths.insert(pathKey).second) + if(!uniquePaths.insert(s.files[i]).second) return {}; const auto& settings=s.controls[i]; if(settings.key< -6||settings.key>6|| diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index c3a6b86c1..80453ff8d 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -114,6 +114,18 @@ int main() { invalid=doc->sets; invalid[0].files[0]=invalid[0].files[1]; assert(!Archive::serialize(invalid,0,false,180).isObject()); + // Duplicate path admission MUST match the same JUCE File equality + // used by parseSongs() on every supported platform. + invalid=doc->sets; + invalid[0].files[1]=juce::File(path.toUpperCase()); + const bool sameFile=invalid[0].files[0]==invalid[0].files[1]; + assert(Archive::serialize(invalid,0,false,180).isObject()!=sameFile); + if(!sameFile) { + // A case-sensitive filesystem treats these as separate file names. + const auto archive=Archive::serialize(invalid,0,false,180); + const auto reopened=Archive::parse(archive); + assert(reopened && reopened->sets[0].files.size()==2); + } invalid=doc->sets; invalid[0].controls[0].key=9; assert(!Archive::serialize(invalid,0,false,180).isObject()); From 97a4a0140a438cae7d5a223eef0325c692bd59f6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:53:00 +0700 Subject: [PATCH 08/24] test(native-mv14): contract-lock unique native setlist creation policy --- tests/native_caption_wire_geometry_contract.test.cjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 82cdb7144..6d24ffbac 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -131,6 +131,9 @@ const playerHtml = read('site/preview-v2/assets/mixer-contextual-buttons.js'); // Player native metadata is now owned by the extracted pure archive codec. const playerArchive = read('src/PlayerSetlistArchive.h'); assert.match(playerArchive, /struct PlayerTrackSettings/); +assert.match(playerArchive, /nextGeneratedName/); +assert.match(main, /PlayerSetlistArchive::\\s*nextGeneratedName/); +assert.doesNotMatch(main, /const int next=static_cast\\(playerSets_\\.size\\(\\)\\)\\+1/); assert.match(main, /using PlayerTrackSettings=armix::player::PlayerTrackSettings/); assert.match(main, /action=="playerKeyStep" \|\| action=="playerTempoStep"/); assert.match(main, /setPlayerPitchTempo\(next\.key,next\.tempo\)/); From 718742d22715e21d80337f22758eb45c19c991ea Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 04:53:30 +0700 Subject: [PATCH 09/24] test(native-mv14): correct literal native contract regex escaping --- tests/native_caption_wire_geometry_contract.test.cjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 6d24ffbac..7c64cd21b 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -132,8 +132,8 @@ const playerHtml = read('site/preview-v2/assets/mixer-contextual-buttons.js'); const playerArchive = read('src/PlayerSetlistArchive.h'); assert.match(playerArchive, /struct PlayerTrackSettings/); assert.match(playerArchive, /nextGeneratedName/); -assert.match(main, /PlayerSetlistArchive::\\s*nextGeneratedName/); -assert.doesNotMatch(main, /const int next=static_cast\\(playerSets_\\.size\\(\\)\\)\\+1/); +assert.match(main, /PlayerSetlistArchive::\s*nextGeneratedName/); +assert.doesNotMatch(main, /const int next=static_cast\(playerSets_\.size\(\)\)\+1/); assert.match(main, /using PlayerTrackSettings=armix::player::PlayerTrackSettings/); assert.match(main, /action=="playerKeyStep" \|\| action=="playerTempoStep"/); assert.match(main, /setPlayerPitchTempo\(next\.key,next\.tempo\)/); From fbf693c7322ee82fb361b5e4118d2aa0e36aebda Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:01:24 +0700 Subject: [PATCH 10/24] fix(native-mv14): prevent full-setlist Undo from invalidating archive Fence playerUndoRemove against 2000-song cap and control cardinality before mutation; keep UI canUndoRemove consistent with native admission. Add boundary and remove-import-undo regression to JUCE archive contract. --- src/Main.cpp | 14 ++++++++++++-- src/PlayerSetlistArchive.h | 9 +++++++++ tests/player_setlist_archive_test.cpp | 10 ++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 16d4b32b5..ec9060b54 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -4168,6 +4168,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(action=="playerUndoRemove") { const auto removed=playerUndoRemove_; if(removed.set!=playerActiveSet_ || removed.index<0)return; + if(!armix::player::PlayerSetlistArchive::canUndoRemove( + playerActiveSet_,removed.set,removed.index, + playerLibrary_.size(),playerTrackSettings_.size())) { + // The removed slot may have been filled by an import. Do not + // create 2,001 songs or block all subsequent session saves. + playerError_="Setlist is full; remove a song before undoing"; + emitPlayerState(true);return; + } if(std::find(playerLibrary_.begin(),playerLibrary_.end(), removed.file)!=playerLibrary_.end())return; const int index=std::clamp(removed.index,0, @@ -4257,8 +4265,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr obj->setProperty("queueRevision",playerQueueEpoch_.revision()); obj->setProperty("crossfadeMs",playerFadeMilliseconds_); obj->setProperty("canUndoRemove", - playerUndoRemove_.set==playerActiveSet_ && - playerUndoRemove_.index>=0); + armix::player::PlayerSetlistArchive::canUndoRemove( + playerActiveSet_,playerUndoRemove_.set, + playerUndoRemove_.index,playerLibrary_.size(), + playerTrackSettings_.size())); obj->setProperty("libraryBusy",playerFolderBusy_); obj->setProperty("error",playerError_); obj->setProperty("chooseOutput", diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index cdbb40994..44ab8497c 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -71,6 +71,15 @@ class PlayerSetlistArchive final { // Keep automatic creation consistent with the archive's case-insensitive // uniqueness rule, including a delete-then-create cycle. At <32 sets, // candidate numbers 2..33 always contain an unused name. + // Undo is an insertion. Reject it before mutating live library/control + // arrays if an intervening import refilled the 2,000-song capacity. + // Keep this identical to serialize()/parseSongs() admission. + static bool canUndoRemove(int activeSet,int undoSet,int undoIndex, + std::size_t songs,std::size_t controls) noexcept { + return undoSet==activeSet && undoIndex>=0 && + songs==controls && songs<2000; + } + static juce::String nextGeneratedName( const std::vector& sets) { for(int number=2;number<=33;++number) { diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 80453ff8d..469185049 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -153,6 +153,16 @@ int main() { names[1].name="setLIST 3"; // case-folded name remains occupied assert(Archive::nextGeneratedName(names)=="Setlist 4"); + // Regression: full 2,000-song setlist -> Remove -> Import another + // song -> Undo. Undo is rejected before mutation; after removing an + // unrelated song the original undo remains available. + assert(Archive::canUndoRemove(0,0,1999,1999,1999)); + assert(!Archive::canUndoRemove(0,0,1999,2000,2000)); + assert(!Archive::canUndoRemove(0,0,1999,2001,2001)); + assert(!Archive::canUndoRemove(0,1,1999,1999,1999)); + assert(!Archive::canUndoRemove(0,0,-1,1999,1999)); + assert(!Archive::canUndoRemove(0,0,1999,1999,1998)); + // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); assert(empty && empty->sets.size()==1); From cfceb869ef0dbb1ab798092f01baa48095d23ecc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:02:09 +0700 Subject: [PATCH 11/24] test(native-mv14): pin full-library Undo policy at native action and projection --- tests/native_caption_wire_geometry_contract.test.cjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 7c64cd21b..b8816bee6 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -133,6 +133,9 @@ const playerArchive = read('src/PlayerSetlistArchive.h'); assert.match(playerArchive, /struct PlayerTrackSettings/); assert.match(playerArchive, /nextGeneratedName/); assert.match(main, /PlayerSetlistArchive::\s*nextGeneratedName/); +assert.match(playerArchive, /static bool canUndoRemove/); +assert.match(main, /PlayerSetlistArchive::canUndoRemove/); +assert.match(main, /Setlist is full; remove a song before undoing/); assert.doesNotMatch(main, /const int next=static_cast\(playerSets_\.size\(\)\)\+1/); assert.match(main, /using PlayerTrackSettings=armix::player::PlayerTrackSettings/); assert.match(main, /action=="playerKeyStep" \|\| action=="playerTempoStep"/); From 875eb0283ed016ed40134eda4c2b7966f369cdfd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:05:17 +0700 Subject: [PATCH 12/24] test(native-mv14): exercise real 2000-song Save/Remove/Import/Undo archive boundary --- tests/player_setlist_archive_test.cpp | 31 ++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 469185049..5b8f5f11e 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -153,9 +153,7 @@ int main() { names[1].name="setLIST 3"; // case-folded name remains occupied assert(Archive::nextGeneratedName(names)=="Setlist 4"); - // Regression: full 2,000-song setlist -> Remove -> Import another - // song -> Undo. Undo is rejected before mutation; after removing an - // unrelated song the original undo remains available. + // Undo admission must reject full or malformed live library state. assert(Archive::canUndoRemove(0,0,1999,1999,1999)); assert(!Archive::canUndoRemove(0,0,1999,2000,2000)); assert(!Archive::canUndoRemove(0,0,1999,2001,2001)); @@ -163,6 +161,33 @@ int main() { assert(!Archive::canUndoRemove(0,0,-1,1999,1999)); assert(!Archive::canUndoRemove(0,0,1999,1999,1998)); + // Real archive at capacity: Remove -> Import -> Undo must not turn + // a valid 2,000-track library into an unpersistable 2,001-track document. + std::vector full{{"At capacity",{}, {}}}; + const auto tempRoot=juce::File::getSpecialLocation( + juce::File::tempDirectory); + for(int i=0;i<2000;++i) { + full[0].files.push_back(tempRoot.getChildFile( + "arsonmix-mv14-capacity-"+juce::String(i)+".wav")); + full[0].controls.emplace_back(); + } + assert(Archive::serialize(full,0,false,180).isObject()); + const auto removedSong=full[0].files[1000]; + const auto removedPreset=full[0].controls[1000]; + full[0].files.erase(full[0].files.begin()+1000); + full[0].controls.erase(full[0].controls.begin()+1000); + assert(Archive::canUndoRemove(0,0,1000,1999,1999)); + full[0].files.push_back(tempRoot.getChildFile( + "arsonmix-mv14-import-after-remove.wav")); + full[0].controls.emplace_back(); + assert(Archive::serialize(full,0,false,180).isObject()); + assert(!Archive::canUndoRemove(0,0,1000,2000,2000)); + // Simulating the old unconditional Undo proves the serializer rejects + // the oversized state; the native caller now refuses this insertion. + full[0].files.insert(full[0].files.begin()+1000,removedSong); + full[0].controls.insert(full[0].controls.begin()+1000,removedPreset); + assert(!Archive::serialize(full,0,false,180).isObject()); + // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); assert(empty && empty->sets.size()==1); From 72b768081e16bc976de4d957807b27b9c60a2ef7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:08:34 +0700 Subject: [PATCH 13/24] fix(native-mv14): validate rounded Player cues before native/deck or archive mutation Extract pure PlayerCueEditPolicy for canonical 10ms cue edits and v3 archive admission. Accept deck cue ACK before updating stored song metadata; rejected rounded OUT leaves valid metadata and unrelated Save intact. Add C++ and native-source regressions. --- engine/player/PlayerCueEditPolicy.h | 44 +++++++++++++++++++ src/Main.cpp | 35 ++++++++------- src/PlayerSetlistArchive.h | 13 ++---- ...ve_caption_wire_geometry_contract.test.cjs | 8 ++++ tests/player_setlist_archive_test.cpp | 23 ++++++++++ 5 files changed, 99 insertions(+), 24 deletions(-) create mode 100644 engine/player/PlayerCueEditPolicy.h diff --git a/engine/player/PlayerCueEditPolicy.h b/engine/player/PlayerCueEditPolicy.h new file mode 100644 index 000000000..b30ed9538 --- /dev/null +++ b/engine/player/PlayerCueEditPolicy.h @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +// Pure Player metadata edit policy. CONTROL thread only; neither disk nor +// native deck/PCM is mutated until the live deck accepts the proposed range. +namespace armix::player { +struct PlayerCueEditPolicy final { + enum class Command { clear, markIn, markOut }; + struct Range { + double in=0., out=0.; + }; + // Match the v3 archive's loadable range, rather than admitting a cue + // that silently disappears when player-library.json is reopened. + static bool validArchive(Range range) noexcept { + return std::isfinite(range.in) && std::isfinite(range.out) && + range.in>=0. && range.out>=0. && + range.in<86400. && range.out<86400. && + (range.out==0. || range.out>range.in+0.05); + } + static std::optional plan(Range existing,Command action, + double position,double duration) noexcept { + if(action==Command::clear)return Range{}; + if(!validArchive(existing) || + !std::isfinite(position)||!std::isfinite(duration)|| + duration<=0.||position<0.||position>=duration) + return std::nullopt; + // Quantize BEFORE validating. A native time 1.059 must not create + // an unsavable OUT=1.05 when IN=1.00. + const double rounded=std::floor(position*100.)/100.; + Range candidate=existing; + if(action==Command::markIn) { + candidate.in=rounded; + if(candidate.out>0.&&candidate.out<=candidate.in+0.05) + candidate.out=0.; + } else { + candidate.out=rounded; + } + if(!validArchive(candidate))return std::nullopt; + return candidate; + } +}; +} // namespace armix::player diff --git a/src/Main.cpp b/src/Main.cpp index ec9060b54..126a684e3 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -65,6 +65,7 @@ #include "../engine/player/PlayerSetlistPolicy.h" #include "../engine/player/PlayerShowEditPolicy.h" #include "../engine/player/PlayerShowTransitionPolicy.h" +#include "../engine/player/PlayerCueEditPolicy.h" #include "../engine/player/PlayerLibraryPolicy.h" #include #include @@ -4718,27 +4719,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else playerError_.clear(); emitPlayerState();return; } - if(action=="playerCueClear") { - cues.cueIn=0.;cues.cueOut=0.; - } else if(!std::isfinite(now) || !std::isfinite(total) || - total<=0. || now<0. || now>=total) { + if(action!="playerCueClear" && + (!std::isfinite(now)||!std::isfinite(total)|| + total<=0.||now<0.||now>=total)) { playerError_="Cue position is unavailable"; emitPlayerState();return; - } else if(action=="playerCueIn") { - cues.cueIn=std::floor(now*100.)/100.; - if(cues.cueOut>0. && cues.cueOut<=cues.cueIn+0.05) - cues.cueOut=0.; - } else { - if(now<=cues.cueIn+0.05) { - playerError_="OUT must be after IN"; - emitPlayerState();return; - } - cues.cueOut=std::floor(now*100.)/100.; } - if(!engine_.setPlayerCueRange(cues.cueIn,cues.cueOut)) { + using CuePolicy=armix::player::PlayerCueEditPolicy; + const auto command=action=="playerCueClear"? + CuePolicy::Command::clear:action=="playerCueIn"? + CuePolicy::Command::markIn:CuePolicy::Command::markOut; + const auto nextCue=CuePolicy::plan( + {cues.cueIn,cues.cueOut},command,now,total); + if(!nextCue) { + playerError_=action=="playerCueOut"? + "OUT must be after IN":"Invalid song cue marker"; + emitPlayerState();return; + } + // Deck admission FIRST. Failed or invalid edits must never + // poison the persisted v3 archive or the WebView readback. + if(!engine_.setPlayerCueRange(nextCue->in,nextCue->out)) { playerError_="Could not update native song markers"; emitPlayerState();return; } + cues.cueIn=nextCue->in; + cues.cueOut=nextCue->out; if(playerLoopCurrent_ && !armix::player::PlayerShowTransitionPolicy::validLoop( cues.cueIn,cues.cueOut,playerFadeMilliseconds_)) diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index 44ab8497c..f78894270 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once #include +#include "../engine/player/PlayerCueEditPolicy.h" #include #include #include @@ -56,9 +57,7 @@ class PlayerSetlistArchive final { item.getProperty("cueIn",0.0)); const double cueOut=static_cast( item.getProperty("cueOut",0.0)); - if(std::isfinite(cueIn)&&std::isfinite(cueOut)&& - cueIn>=0.&&cueOut>=0.&&cueIn<86400.&&cueOut<86400.&& - (cueOut==0.||cueOut>cueIn+0.05)) { + if(PlayerCueEditPolicy::validArchive({cueIn,cueOut})) { settings.cueIn=cueIn; settings.cueOut=cueOut; } @@ -169,12 +168,8 @@ class PlayerSetlistArchive final { const auto& settings=s.controls[i]; if(settings.key< -6||settings.key>6|| settings.tempo<80||settings.tempo>120|| - !std::isfinite(settings.cueIn)|| - !std::isfinite(settings.cueOut)|| - settings.cueIn<0.||settings.cueOut<0.|| - settings.cueIn>=86400.||settings.cueOut>=86400.|| - (settings.cueOut!=0.&& - settings.cueOut<=settings.cueIn+0.05)) + !PlayerCueEditPolicy::validArchive( + {settings.cueIn,settings.cueOut})) return {}; } } diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index b8816bee6..00657552b 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -138,6 +138,14 @@ assert.match(main, /PlayerSetlistArchive::canUndoRemove/); assert.match(main, /Setlist is full; remove a song before undoing/); assert.doesNotMatch(main, /const int next=static_cast\(playerSets_\.size\(\)\)\+1/); assert.match(main, /using PlayerTrackSettings=armix::player::PlayerTrackSettings/); +const cuePolicy=read('engine/player/PlayerCueEditPolicy.h'); +assert.match(cuePolicy, /struct PlayerCueEditPolicy/); +assert.match(main, /CuePolicy::plan/); +const cueAction=main.slice(main.indexOf('if(action=="playerCueIn"'), + main.indexOf('if(action=="playerPlay")')); +assert.ok(cueAction.indexOf('engine_.setPlayerCueRange(nextCue->in,nextCue->out)') >= 0); +assert.ok(cueAction.indexOf('cues.cueIn=nextCue->in') > + cueAction.indexOf('engine_.setPlayerCueRange(nextCue->in,nextCue->out)')); assert.match(main, /action=="playerKeyStep" \|\| action=="playerTempoStep"/); assert.match(main, /setPlayerPitchTempo\(next\.key,next\.tempo\)/); assert.match(playerHtml, /id="playerKeyMinus"/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 5b8f5f11e..40a69b837 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -4,6 +4,7 @@ #endif #include #include +#include #include "../src/PlayerSetlistArchive.h" using Archive=armix::player::PlayerSetlistArchive; @@ -138,6 +139,28 @@ int main() { // A valid, canonical document still saves and round-trips unchanged. assert(Archive::serialize(doc->sets,doc->active,true,250).isObject()); + // Native cue edit is a pure candidate: quantize THEN validate. At + // IN=1.00, an OUT request at 1.059 becomes 1.05 (invalid) and must + // not mutate metadata or poison a subsequent unrelated archive Save. + using Cue=armix::player::PlayerCueEditPolicy; + const Cue::Range originalCue{1.00,0.0}; + assert(!Cue::plan(originalCue,Cue::Command::markOut,1.059,20.)); + assert(originalCue.in==1. && originalCue.out==0.); + auto untouched=doc->sets; + untouched[0].controls[0].cueIn=1.0; + untouched[0].controls[0].cueOut=0.0; + assert(Archive::serialize(untouched,doc->active,true,250).isObject()); + const auto nextOut=Cue::plan( + originalCue,Cue::Command::markOut,1.09,20.); + assert(nextOut && nextOut->out>nextOut->in+0.05); + const auto nextIn=Cue::plan( + Cue::Range{1.,5.},Cue::Command::markIn,5.0,20.); + assert(nextIn && nextIn->in==5. && nextIn->out==0.); + const auto cleared=Cue::plan( + Cue::Range{1.,5.},Cue::Command::clear, + std::numeric_limits::quiet_NaN(),0.); + assert(cleared && cleared->in==0. && cleared->out==0.); + // Create -> delete -> create must never generate a colliding archive name. std::vector names{ {"My Setlist",{},{}}, From 5c05d4595abb6dc6ca8fcdee1c498130edfd7145 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:13:14 +0700 Subject: [PATCH 14/24] fix(native-mv14): reject OUT marker quantized to media-end sentinel Only explicit cue Clear may set OUT=0. Mark OUT must exceed IN+50ms after 10ms quantization, including media-start clicks; protect existing persisted cue against accidental silent reset. --- engine/player/PlayerCueEditPolicy.h | 3 +++ tests/player_setlist_archive_test.cpp | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/engine/player/PlayerCueEditPolicy.h b/engine/player/PlayerCueEditPolicy.h index b30ed9538..95d7a6cc6 100644 --- a/engine/player/PlayerCueEditPolicy.h +++ b/engine/player/PlayerCueEditPolicy.h @@ -35,6 +35,9 @@ struct PlayerCueEditPolicy final { if(candidate.out>0.&&candidate.out<=candidate.in+0.05) candidate.out=0.; } else { + // Mark OUT must never impersonate the OUT=0 media-end sentinel. + // In particular, positions below 10ms quantize to zero. + if(rounded<=candidate.in+0.05)return std::nullopt; candidate.out=rounded; } if(!validArchive(candidate))return std::nullopt; diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 40a69b837..8e5478277 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -145,6 +145,12 @@ int main() { using Cue=armix::player::PlayerCueEditPolicy; const Cue::Range originalCue{1.00,0.0}; assert(!Cue::plan(originalCue,Cue::Command::markOut,1.059,20.)); + // Zero-quantized OUT must not silently clear an existing OUT marker. + const Cue::Range existingOut{1.0,5.0}; + assert(!Cue::plan(existingOut,Cue::Command::markOut,0.009,20.)); + assert(!Cue::plan(Cue::Range{0.,5.}, + Cue::Command::markOut,0.009,20.)); + assert(existingOut.in==1.0 && existingOut.out==5.0); assert(originalCue.in==1. && originalCue.out==0.); auto untouched=doc->sets; untouched[0].controls[0].cueIn=1.0; From 705ccc5a5232434276c29e9658ed034ffb6be5cc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:32:29 +0700 Subject: [PATCH 15/24] perf(native-nmod): O(n log n) Player archive import with JUCE file identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace quadratic 2000-song duplicate scans with ordered JUCE File keys matching Save admission across platforms. Exercise full 2000-song Save→JSON→Open round-trip and stable song/control indexes before Remove/Import/Undo regression. --- src/PlayerSetlistArchive.h | 7 +++++-- tests/player_setlist_archive_test.cpp | 10 +++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h index f78894270..9b69608e2 100644 --- a/src/PlayerSetlistArchive.h +++ b/src/PlayerSetlistArchive.h @@ -33,6 +33,10 @@ class PlayerSetlistArchive final { PlayerSavedSet& destination) { const auto* entries=items.getArray(); if(entries==nullptr)return; + // Use the same JUCE File identity as serialize(). A 2,000-track + // archive must not do quadratic duplicate scans on every startup. + std::set knownPaths( + destination.files.begin(),destination.files.end()); for(const auto& item:*entries) { if(destination.files.size()>=2000)break; if((version==1&&!item.isString()) || @@ -43,8 +47,7 @@ class PlayerSetlistArchive final { !juce::File::isAbsolutePath(path))continue; const juce::File source(path); if(!source.hasFileExtension("wav;mp3;flac;aif;aiff;ogg") || - std::find(destination.files.begin(),destination.files.end(),source) - !=destination.files.end())continue; + !knownPaths.insert(source).second)continue; PlayerTrackSettings settings; if(version>=2) { settings.key=static_cast(item.getProperty("key",0)); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 8e5478277..431425598 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -200,7 +200,15 @@ int main() { "arsonmix-mv14-capacity-"+juce::String(i)+".wav")); full[0].controls.emplace_back(); } - assert(Archive::serialize(full,0,false,180).isObject()); + const auto fullDocument=Archive::serialize(full,0,false,180); + assert(fullDocument.isObject()); + const auto fullReload=Archive::parse(juce::JSON::parse( + juce::JSON::toString(fullDocument,false))); + assert(fullReload && fullReload->sets.size()==1); + assert(fullReload->sets[0].files.size()==2000); + assert(fullReload->sets[0].controls.size()==2000); + assert(fullReload->sets[0].files[1000]==full[0].files[1000]); + assert(fullReload->sets[0].files[1999]==full[0].files[1999]); const auto removedSong=full[0].files[1000]; const auto removedPreset=full[0].controls[1000]; full[0].files.erase(full[0].files.begin()+1000); From 10906be36a8c27a0c3b45d1287be195675b98248 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 05:52:59 +0700 Subject: [PATCH 16/24] refactor(native N-MOD-15): isolate atomic Player setlist disk repository Move durable v1/v2/v3 Player JSON load/validation and atomic staged write from ConsoleWindow into control-only PlayerSetlistRepository. Preserve exact missing/invalid/I/O status text, deck/selection/native PCM ownership and Save/Open shape. Add real filesystem CTest for corrupt JSON, failed write, no clobber on invalid Save and 2k-song recovery. --- src/Main.cpp | 36 +++++++-------- src/PlayerSetlistRepository.h | 44 +++++++++++++++++++ ...ve_caption_wire_geometry_contract.test.cjs | 11 +++++ tests/player_setlist_archive_test.cpp | 43 ++++++++++++++++++ 4 files changed, 114 insertions(+), 20 deletions(-) create mode 100644 src/PlayerSetlistRepository.h diff --git a/src/Main.cpp b/src/Main.cpp index 83df3aa78..88521cd3f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -46,6 +46,7 @@ #include "NativeMixerSessionSaveWorker.h" #include "NativeLogicalMixerControl.h" #include "PlayerSetlistArchive.h" +#include "PlayerSetlistRepository.h" #include "NativeHotkeyRegistry.h" #include "NativeHotkeyCommandPlan.h" #include "NativeFxParameterHotkey.h" @@ -3907,40 +3908,35 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerOutputPendingIndex_=-1; playerUndoRemove_={}; } - // Player archive owns only v1/v2/v3 JSON policy and deterministic mapping. - // ConsoleWindow retains the sole disk writer, set activation and deck. + // The repository owns only durable Player JSON I/O. ConsoleWindow + // retains the single deck, live selection and accepted native control. void restorePlayerLibrary() { playerSets_.clear(); - const auto file=settingsDirectory().getChildFile("player-library.json"); - if(!file.existsAsFile()) { + auto result=armix::player::PlayerSetlistRepository::load( + settingsDirectory().getChildFile("player-library.json")); + if(result.status==armix::player::PlayerSetlistRepository::LoadStatus::missing) { playerSets_.push_back({"My Setlist",{},{}}); return; } - auto parsed=armix::player::PlayerSetlistArchive::parse( - juce::JSON::parse(file.loadFileAsString())); - if(!parsed) { + if(!result.document) { playerSets_.push_back({"My Setlist",{},{}}); playerError_="Setlists could not be read; no music files were changed"; return; } - playerSets_=std::move(parsed->sets); - activatePlayerSet(parsed->active); - playerAutoNext_=parsed->autoNext; - playerFadeMilliseconds_=parsed->fadeMs; + auto& parsed=*result.document; + playerSets_=std::move(parsed.sets); + activatePlayerSet(parsed.active); + playerAutoNext_=parsed.autoNext; + playerFadeMilliseconds_=parsed.fadeMs; } void persistPlayerLibrary() { saveActivePlayerSet(); - const auto document=armix::player::PlayerSetlistArchive::serialize( + const auto result=armix::player::PlayerSetlistRepository::save( + settingsDirectory().getChildFile("player-library.json"), playerSets_,playerActiveSet_,playerAutoNext_,playerFadeMilliseconds_); - if(!document.isObject()) { + if(result==armix::player::PlayerSetlistRepository::SaveStatus::invalidState) playerError_="Unable to save setlists; invalid setlist state"; - return; - } - const auto target=settingsDirectory().getChildFile("player-library.json"); - juce::TemporaryFile staging(target); - if(!staging.getFile().replaceWithText( - juce::JSON::toString(document,false)) || - !staging.overwriteTargetFileWithTemporary()) + else if(result==armix::player::PlayerSetlistRepository::SaveStatus::ioError) playerError_="Unable to save setlists; check folder permissions"; } bool playerShowMaySwitchSet() { diff --git a/src/PlayerSetlistRepository.h b/src/PlayerSetlistRepository.h new file mode 100644 index 000000000..4f76b4c71 --- /dev/null +++ b/src/PlayerSetlistRepository.h @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "PlayerSetlistArchive.h" +#include +#include + +// N-MOD-15: one control-thread disk boundary around the pure Player archive. +// Callers still own the active deck, song selection, engine and status ACK. +// This class never manipulates media paths, PCM, WebView or session routing. +namespace armix::player { +class PlayerSetlistRepository final { +public: + enum class LoadStatus { missing, loaded, invalid }; + enum class SaveStatus { saved, invalidState, ioError }; + struct LoadResult { + LoadStatus status; + std::optional document; + }; + static LoadResult load(const juce::File& target) { + if (!target.existsAsFile()) + return {LoadStatus::missing,std::nullopt}; + auto parsed=PlayerSetlistArchive::parse( + juce::JSON::parse(target.loadFileAsString())); + if (!parsed)return {LoadStatus::invalid,std::nullopt}; + return {LoadStatus::loaded,std::move(parsed)}; + } + static SaveStatus save(const juce::File& target, + const std::vector& sets, + int active,bool autoNext,int fadeMs) { + // Do not begin writing until *every* set is loadable by the codec. + const auto document=PlayerSetlistArchive::serialize( + sets,active,autoNext,fadeMs); + if (!document.isObject())return SaveStatus::invalidState; + // JUCE creates a sibling staging file and replaces only after the + // complete payload was written. Never mutate live media files. + juce::TemporaryFile staging(target); + if (!staging.getFile().replaceWithText( + juce::JSON::toString(document,false)) || + !staging.overwriteTargetFileWithTemporary()) + return SaveStatus::ioError; + return SaveStatus::saved; + } +}; +} // namespace armix::player diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 00657552b..e1a879d30 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -138,6 +138,17 @@ assert.match(main, /PlayerSetlistArchive::canUndoRemove/); assert.match(main, /Setlist is full; remove a song before undoing/); assert.doesNotMatch(main, /const int next=static_cast\(playerSets_\.size\(\)\)\+1/); assert.match(main, /using PlayerTrackSettings=armix::player::PlayerTrackSettings/); +const playerRepository=read('src/PlayerSetlistRepository.h'); +assert.match(playerRepository, /class PlayerSetlistRepository final/); +assert.match(playerRepository, /juce::TemporaryFile staging\(target\)/); +assert.match(playerRepository, /overwriteTargetFileWithTemporary\(\)/); +assert.match(main, /PlayerSetlistRepository::load/); +assert.match(main, /PlayerSetlistRepository::save/); +const persistence=main.slice(main.indexOf('void restorePlayerLibrary()'), + main.indexOf('bool playerShowMaySwitchSet()')); +assert.doesNotMatch(persistence, + /JSON::parse|JSON::toString|loadFileAsString|replaceWithText|juce::TemporaryFile/); + const cuePolicy=read('engine/player/PlayerCueEditPolicy.h'); assert.match(cuePolicy, /struct PlayerCueEditPolicy/); assert.match(main, /CuePolicy::plan/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 431425598..9b15c4259 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -6,6 +6,7 @@ #include #include #include "../src/PlayerSetlistArchive.h" +#include "../src/PlayerSetlistRepository.h" using Archive=armix::player::PlayerSetlistArchive; using SavedSet=armix::player::PlayerSavedSet; @@ -225,6 +226,48 @@ int main() { full[0].controls.insert(full[0].controls.begin()+1000,removedPreset); assert(!Archive::serialize(full,0,false,180).isObject()); + // N-MOD-15: REAL disk adapter regression. Use an isolated directory, + // never the operator's settings or media library. + using Store=armix::player::PlayerSetlistRepository; + const auto sandbox=juce::File::getSpecialLocation( + juce::File::tempDirectory).getChildFile( + "arsonmix-nmod15-"+juce::Uuid().toString()); + assert(sandbox.createDirectory().wasOk()); + const auto target=sandbox.getChildFile("player-library.json"); + assert(Store::load(target).status==Store::LoadStatus::missing); + assert(Store::save(target,doc->sets,doc->active,true,250) + ==Store::SaveStatus::saved); + const auto roundTrip=Store::load(target); + assert(roundTrip.status==Store::LoadStatus::loaded); + assert(roundTrip.document && roundTrip.document->sets.size()==2); + assert(roundTrip.document->active==1 && roundTrip.document->autoNext); + assert(roundTrip.document->fadeMs==250); + assert(roundTrip.document->sets[0].controls[0].cueOut==9.0); + const auto acceptedBytes=target.loadFileAsString(); + assert(Store::save(target,broken,0,false,180) + ==Store::SaveStatus::invalidState); + assert(target.loadFileAsString()==acceptedBytes); + // An invalid parent (it is a regular file, NOT a folder) must fail + // atomically without modifying the already accepted setlist. + const auto notDirectory=sandbox.getChildFile("not-a-directory"); + assert(notDirectory.replaceWithText("must not be replaced")); + const auto blocked=notDirectory.getChildFile("player-library.json"); + assert(Store::save(blocked,doc->sets,doc->active,true,250) + ==Store::SaveStatus::ioError); + assert(notDirectory.loadFileAsString()=="must not be replaced"); + assert(target.loadFileAsString()==acceptedBytes); + assert(target.replaceWithText("{bad JSON")); + assert(Store::load(target).status==Store::LoadStatus::invalid); + assert(target.loadFileAsString()=="{bad JSON"); + // A valid operator save recovers a corrupt archive without touching + // the media paths referenced by song records. + assert(Store::save(target,fullReload->sets,0,false,180) + ==Store::SaveStatus::saved); + const auto largeReload=Store::load(target); + assert(largeReload.document && largeReload.document->sets[0].files.size()==2000); + assert(largeReload.document->sets[0].controls.size()==2000); + assert(sandbox.deleteRecursively()); + // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); assert(empty && empty->sets.size()==1); From 89c76e6c2c6f4666e744b2e1c5be90633762e262 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 10:14:25 +0700 Subject: [PATCH 17/24] refactor(native N-MOD-16): durable-first Player setlist metadata transaction --- src/Main.cpp | 82 ++++++---------- src/PlayerSetlistEditTransaction.h | 95 +++++++++++++++++++ ...ve_caption_wire_geometry_contract.test.cjs | 5 +- tests/player_setlist_archive_test.cpp | 60 ++++++++++++ 4 files changed, 189 insertions(+), 53 deletions(-) create mode 100644 src/PlayerSetlistEditTransaction.h diff --git a/src/Main.cpp b/src/Main.cpp index 88521cd3f..c77f9af3c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -47,6 +47,7 @@ #include "NativeLogicalMixerControl.h" #include "PlayerSetlistArchive.h" #include "PlayerSetlistRepository.h" +#include "PlayerSetlistEditTransaction.h" #include "NativeHotkeyRegistry.h" #include "NativeHotkeyCommandPlan.h" #include "NativeFxParameterHotkey.h" @@ -3948,61 +3949,38 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return !playerFolderBusy_; } void playerEditSetlist(const juce::String& action,const juce::var& value) { + // Setlist metadata is durable BEFORE a deck stop or live state + // mutation. A failed disk write cannot switch/delete a live set. if(action=="playerNewSetlist" || action=="playerSelectSetlist" || - action=="playerDeleteSetlist") { - if(!playerShowMaySwitchSet())return; - if(action=="playerNewSetlist") { - if(playerSets_.size()>=32) { - playerError_="Maximum 32 setlists";emitPlayerState();return; - } - saveActivePlayerSet(); - const auto next=armix::player::PlayerSetlistArchive:: - nextGeneratedName(playerSets_); - if(next.isEmpty()) { - playerError_="No available setlist name"; - emitPlayerState();return; - } - playerSets_.push_back({next,{},{}}); - engine_.playerStop(); - activatePlayerSet(static_cast(playerSets_.size())-1); - } else { - const int index=static_cast(value); - if(index<0 || index>=static_cast(playerSets_.size()))return; - saveActivePlayerSet(); - if(action=="playerSelectSetlist") { - engine_.playerStop();activatePlayerSet(index); - } else if(playerSets_.size()>1) { - engine_.playerStop(); - int destination=playerActiveSet_; - if(index(playerSets_.size())-2); - playerSets_.erase(playerSets_.begin()+index); - activatePlayerSet(destination); - } else { - playerError_="Keep at least one setlist"; - emitPlayerState();return; - } + action=="playerDeleteSetlist" || action=="playerRenameSetlist") { + const bool rename=action=="playerRenameSetlist"; + if(!rename && !playerShowMaySwitchSet())return; + using Edit=armix::player::PlayerSetlistEditTransaction; + const auto command=action=="playerNewSetlist"?Edit::Command::create: + action=="playerSelectSetlist"?Edit::Command::select: + action=="playerDeleteSetlist"?Edit::Command::remove: + Edit::Command::rename; + const int index=rename || command==Edit::Command::create? + -1:static_cast(value); + // Preserve the historical silent no-op for stale row IDs. + if(!rename && command!=Edit::Command::create && + (index<0 || index>=static_cast(playerSets_.size())))return; + auto outcome=Edit::apply( + settingsDirectory().getChildFile("player-library.json"), + playerSets_,playerActiveSet_,playerLibrary_,playerTrackSettings_, + playerAutoNext_,playerFadeMilliseconds_,command,index, + rename?value.toString():juce::String{}); + if(!outcome.committed()) { + playerError_=outcome.error; + emitPlayerState(true);return; } - playerError_.clear();persistPlayerLibrary();emitPlayerState(true); - return; - } - if(action=="playerRenameSetlist") { - auto name=value.toString().trim(); - if(name.isEmpty() || name.length()>64)return; - const bool exists=std::any_of( - playerSets_.begin(),playerSets_.end(), - [&](const PlayerSavedSet& set) { - return set.name.equalsIgnoreCase(name) && - &set!=&playerSets_[static_cast(playerActiveSet_)]; - }); - if(exists) { - playerError_="Setlist name already exists"; - emitPlayerState();return; + playerSets_=std::move(outcome.sets); + if(!rename) { + engine_.playerStop(); + activatePlayerSet(outcome.active); } - playerSets_[static_cast(playerActiveSet_)].name=name; - playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + playerError_.clear(); + emitPlayerState(true); return; } if(action=="playerMoveSong") { diff --git a/src/PlayerSetlistEditTransaction.h b/src/PlayerSetlistEditTransaction.h new file mode 100644 index 000000000..250d9087b --- /dev/null +++ b/src/PlayerSetlistEditTransaction.h @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "PlayerSetlistRepository.h" +#include +#include +#include + +// N-MOD-16: durable-first setlist metadata use case, CONTROL thread only. +// Stage against the current live tracks, persist the complete validated v3 +// archive, then return a candidate to the one ConsoleWindow owner. No deck, +// PCM callback, WebView, UI acknowledgement, or other state is changed here. +namespace armix::player { +class PlayerSetlistEditTransaction final { +public: + enum class Command { create, select, remove, rename }; + using SaveStatus = PlayerSetlistRepository::SaveStatus; + struct Result { + SaveStatus status = SaveStatus::invalidState; + juce::String error; + std::vector sets; + int active = -1; + bool committed() const noexcept { + return status == SaveStatus::saved; + } + }; + + static Result apply(const juce::File& archive, + const std::vector& original, + int active, + const std::vector& liveFiles, + const std::vector& liveControls, + bool autoNext, int fadeMs, Command command, + int index = -1, const juce::String& proposedName = {}) { + if(original.empty() || active < 0 || + active >= static_cast(original.size()) || + liveFiles.size() != liveControls.size()) + return reject(SaveStatus::invalidState,"Unable to save setlists; invalid setlist state"); + + auto candidate = original; + candidate[static_cast(active)].files = liveFiles; + candidate[static_cast(active)].controls = liveControls; + int destination = active; + switch(command) { + case Command::create: { + if(candidate.size() >= 32) + return reject(SaveStatus::invalidState,"Maximum 32 setlists"); + auto name = PlayerSetlistArchive::nextGeneratedName(candidate); + if(name.isEmpty()) + return reject(SaveStatus::invalidState,"No available setlist name"); + candidate.push_back({std::move(name),{},{}}); + destination = static_cast(candidate.size()) - 1; + break; + } + case Command::select: + if(index < 0 || index >= static_cast(candidate.size())) + return reject(SaveStatus::invalidState,"Invalid setlist"); + destination = index; + break; + case Command::remove: + if(candidate.size() < 2) + return reject(SaveStatus::invalidState,"Keep at least one setlist"); + if(index < 0 || index >= static_cast(candidate.size())) + return reject(SaveStatus::invalidState,"Invalid setlist"); + if(index < active) + --destination; + else if(index == active) + destination = std::min(index,static_cast(candidate.size())-2); + candidate.erase(candidate.begin()+index); + break; + case Command::rename: { + const auto name = proposedName.trim(); + if(name.isEmpty() || name.length() > 64) + return reject(SaveStatus::invalidState,"Invalid setlist name"); + for(int i=0;i(candidate.size());++i) + if(i != active && candidate[static_cast(i)].name.equalsIgnoreCase(name)) + return reject(SaveStatus::invalidState,"Setlist name already exists"); + candidate[static_cast(active)].name = name; + break; + } + } + + const auto stored = PlayerSetlistRepository::save( + archive,candidate,destination,autoNext,fadeMs); + if(stored == SaveStatus::invalidState) + return reject(stored,"Unable to save setlists; invalid setlist state"); + if(stored == SaveStatus::ioError) + return reject(stored,"Unable to save setlists; check folder permissions"); + return {SaveStatus::saved,{},std::move(candidate),destination}; + } +private: + static Result reject(SaveStatus status,juce::String error) { + return {status,std::move(error),{},-1}; + } +}; +} // namespace armix::player diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index e1a879d30..a0d83c3a3 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -132,7 +132,10 @@ const playerHtml = read('site/preview-v2/assets/mixer-contextual-buttons.js'); const playerArchive = read('src/PlayerSetlistArchive.h'); assert.match(playerArchive, /struct PlayerTrackSettings/); assert.match(playerArchive, /nextGeneratedName/); -assert.match(main, /PlayerSetlistArchive::\s*nextGeneratedName/); +const playerEditTransaction=read('src/PlayerSetlistEditTransaction.h'); +assert.match(playerEditTransaction, /PlayerSetlistArchive::nextGeneratedName/); +assert.match(playerEditTransaction, /PlayerSetlistRepository::save/); +assert.match(main, /PlayerSetlistEditTransaction::apply/); assert.match(playerArchive, /static bool canUndoRemove/); assert.match(main, /PlayerSetlistArchive::canUndoRemove/); assert.match(main, /Setlist is full; remove a song before undoing/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 9b15c4259..a96e928df 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -266,6 +266,66 @@ int main() { const auto largeReload=Store::load(target); assert(largeReload.document && largeReload.document->sets[0].files.size()==2000); assert(largeReload.document->sets[0].controls.size()==2000); + // N-MOD-16: durable-first metadata edit. An accepted write changes + // neither the caller's live model nor its deck until it explicitly adopts + // the returned candidate. The disk is the acceptance boundary. + using Edit=armix::player::PlayerSetlistEditTransaction; + const auto transactionFile=sandbox.getChildFile("transactional-setlists.json"); + auto originalSets=doc->sets; + const auto originalName=originalSets[0].name; + auto liveFiles=originalSets[0].files; + auto liveControls=originalSets[0].controls; + liveFiles.push_back(juce::File(tempRoot.getChildFile("nmod16-new-track.wav"))); + liveControls.push_back({}); + const auto created=Edit::apply(transactionFile,originalSets,0, + liveFiles,liveControls,true,250,Edit::Command::create); + assert(created.committed() && created.active==2); + assert(created.sets.size()==3 && created.sets[0].files.size()==3); + assert(originalSets.size()==2 && originalSets[0].files.size()==2); + const auto createdOnDisk=Store::load(transactionFile); + assert(createdOnDisk.document && createdOnDisk.document->active==2); + assert(createdOnDisk.document->sets[0].files.size()==3); + auto selected=Edit::apply(transactionFile,created.sets,created.active, + created.sets[2].files,created.sets[2].controls,true,250, + Edit::Command::select,0); + assert(selected.committed() && selected.active==0); + assert(Store::load(transactionFile).document->active==0); + const auto collisionBytes=transactionFile.loadFileAsString(); + const auto collision=Edit::apply(transactionFile,selected.sets,0, + selected.sets[0].files,selected.sets[0].controls,true,250, + Edit::Command::rename,-1,"live SHOW"); + assert(!collision.committed()); + assert(collision.error=="Setlist name already exists"); + assert(transactionFile.loadFileAsString()==collisionBytes); + auto renamed=Edit::apply(transactionFile,selected.sets,0, + selected.sets[0].files,selected.sets[0].controls,true,250, + Edit::Command::rename,-1," Main Gig "); + assert(renamed.committed() && renamed.sets[0].name=="Main Gig"); + assert(selected.sets[0].name==originalName); + assert(Store::load(transactionFile).document->sets[0].name=="Main Gig"); + const auto deleted=Edit::apply(transactionFile,renamed.sets,0, + renamed.sets[0].files,renamed.sets[0].controls,true,250, + Edit::Command::remove,0); + assert(deleted.committed() && deleted.active==0); + assert(deleted.sets.size()==2 && deleted.sets[0].name=="Live Show"); + assert(Store::load(transactionFile).document->sets.size()==2); + const auto written=transactionFile.loadFileAsString(); + const auto failed=Edit::apply(blocked,renamed.sets,0, + renamed.sets[0].files,renamed.sets[0].controls,true,250, + Edit::Command::remove,0); + assert(!failed.committed() && failed.status==Store::SaveStatus::ioError); + assert(renamed.sets.size()==3 && renamed.sets[0].name=="Main Gig"); + assert(transactionFile.loadFileAsString()==written); + assert(notDirectory.loadFileAsString()=="must not be replaced"); + const auto badCardinality=Edit::apply(transactionFile,renamed.sets,0, + renamed.sets[0].files,{},true,250,Edit::Command::rename,-1,"Good"); + assert(!badCardinality.committed()); + assert(transactionFile.loadFileAsString()==written); + const std::vector lastOne{{"One",{}, {}}}; + const auto deleteLast=Edit::apply(transactionFile,lastOne,0,{}, {}, + false,180,Edit::Command::remove,0); + assert(!deleteLast.committed()); + assert(transactionFile.loadFileAsString()==written); assert(sandbox.deleteRecursively()); // Legacy empty v3 content migrates to a non-destructive default setlist. From 632983e640e7a0056e4f2a57362e287dc7aa6072 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 10:19:08 +0700 Subject: [PATCH 18/24] refactor(native N-MOD-16): stage track edits and imports before atomic persistence --- src/Main.cpp | 153 ++++++++++++------ src/PlayerSetlistEditTransaction.h | 38 ++++- ...ve_caption_wire_geometry_contract.test.cjs | 3 + tests/player_setlist_archive_test.cpp | 24 +++ 4 files changed, 159 insertions(+), 59 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index c77f9af3c..7a04b6746 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -58,6 +58,8 @@ #include "../engine/device/WindowsFirstRunEndpointDiscovery.h" #endif #include +#include +#include #include #include #include @@ -3940,6 +3942,23 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else if(result==armix::player::PlayerSetlistRepository::SaveStatus::ioError) playerError_="Unable to save setlists; check folder permissions"; } + bool commitPlayerTrackEdit(std::vector nextFiles, + std::vector nextControls) { + using Edit=armix::player::PlayerSetlistEditTransaction; + auto outcome=Edit::replaceActiveTracks( + settingsDirectory().getChildFile("player-library.json"), + playerSets_,playerActiveSet_,nextFiles,nextControls, + playerAutoNext_,playerFadeMilliseconds_); + if(!outcome.committed()) { + playerError_=outcome.error; + return false; + } + // No accepted Player identity/queue/index change precedes disk commit. + playerSets_=std::move(outcome.sets); + playerLibrary_=std::move(nextFiles); + playerTrackSettings_=std::move(nextControls); + return true; + } bool playerShowMaySwitchSet() { const auto state=engine_.playerStatus().getProperty("state","").toString(); if(state=="PLAYING" || state=="PREPARING" || state=="PAUSED") { @@ -3993,7 +4012,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr items.erase(items.begin()+from); items.insert(items.begin()+to,std::move(item)); }; - move(playerLibrary_);move(playerTrackSettings_); + auto nextFiles=playerLibrary_; + auto nextControls=playerTrackSettings_; + move(nextFiles);move(nextControls); + if(!commitPlayerTrackEdit(std::move(nextFiles),std::move(nextControls))) { + emitPlayerState(true);return; + } const auto remap=[&](int index) { return armix::player::PlayerShowEditPolicy::afterMove( index,from,to,count); @@ -4001,7 +4025,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerSelected_=remap(playerSelected_); playerCurrent_=remap(playerCurrent_); playerPendingIndex_=remap(playerPendingIndex_); - persistPlayerLibrary();emitPlayerState(true); + playerError_.clear();emitPlayerState(true); return; } if(action=="playerRemoveSong") { @@ -4017,17 +4041,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerError_="Stop the playing song before removing it"; emitPlayerState();return; } - playerUndoRemove_={playerActiveSet_,index, - playerLibrary_[static_cast(index)], - playerTrackSettings_[static_cast(index)]}; + const auto removedFile=playerLibrary_[static_cast(index)]; + const auto removedControls=playerTrackSettings_[static_cast(index)]; + auto nextFiles=playerLibrary_; + auto nextControls=playerTrackSettings_; + nextFiles.erase(nextFiles.begin()+index); + nextControls.erase(nextControls.begin()+index); + if(!commitPlayerTrackEdit(std::move(nextFiles),std::move(nextControls))) { + emitPlayerState(true);return; + } + playerUndoRemove_={playerActiveSet_,index,removedFile,removedControls}; const auto queueCountBefore=playerQueue_.size(); playerQueue_.erase( std::remove(playerQueue_.begin(),playerQueue_.end(), playerUndoRemove_.file),playerQueue_.end()); if(queueCountBefore!=playerQueue_.size()) playerQueueEpoch_.changed(); - playerLibrary_.erase(playerLibrary_.begin()+index); - playerTrackSettings_.erase(playerTrackSettings_.begin()+index); const auto remap=[&](int old) { return armix::player::PlayerShowEditPolicy::afterRemove( old,index); @@ -4038,7 +4067,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(playerSelected_<0 && !playerLibrary_.empty()) playerSelected_=std::min(index, static_cast(playerLibrary_.size())-1); - playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + playerError_.clear();emitPlayerState(true); return; } if(action=="playerUndoRemove") { @@ -4056,9 +4085,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr removed.file)!=playerLibrary_.end())return; const int index=std::clamp(removed.index,0, static_cast(playerLibrary_.size())); - playerLibrary_.insert(playerLibrary_.begin()+index,removed.file); - playerTrackSettings_.insert( - playerTrackSettings_.begin()+index,removed.controls); + auto nextFiles=playerLibrary_; + auto nextControls=playerTrackSettings_; + nextFiles.insert(nextFiles.begin()+index,removed.file); + nextControls.insert(nextControls.begin()+index,removed.controls); + if(!commitPlayerTrackEdit(std::move(nextFiles),std::move(nextControls))) { + emitPlayerState(true);return; + } playerCurrent_=armix::player::PlayerShowEditPolicy::afterInsert( playerCurrent_,index); playerSelected_=armix::player::PlayerShowEditPolicy::afterInsert( @@ -4066,7 +4099,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerPendingIndex_=armix::player::PlayerShowEditPolicy::afterInsert( playerPendingIndex_,index); playerUndoRemove_={}; - playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + playerError_.clear();emitPlayerState(true); return; } if(action=="playerQueueNext" || action=="playerQueueAppend") { @@ -4205,29 +4238,37 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (const juce::FileChooser& picker) { if(!safe)return; const auto files=picker.getResults(); + auto nextFiles=safe->playerLibrary_; + auto nextControls=safe->playerTrackSettings_; + // JUCE File order matches the native archive path identity; + // a 2,000-song import never needs quadratic scans. + std::map positions; + for(std::size_t i=0;i(-1); for(const auto& file:files) { if(!file.existsAsFile() || !file.hasFileExtension("wav;mp3;flac;aif;aiff;ogg")) continue; - const auto found=std::find(safe->playerLibrary_.begin(), - safe->playerLibrary_.end(),file); - if(found!=safe->playerLibrary_.end()) { + const auto known=positions.find(file); + if(known!=positions.end()) { if(first==static_cast(-1)) - first=static_cast( - found-safe->playerLibrary_.begin()); + first=known->second; continue; } - if(safe->playerLibrary_.size()>=2000)break; + if(nextFiles.size()>=2000)break; if(first==static_cast(-1)) - first=safe->playerLibrary_.size(); - safe->playerLibrary_.push_back(file); - safe->playerTrackSettings_.push_back({}); + first=nextFiles.size(); + positions.emplace(file,nextFiles.size()); + nextFiles.push_back(file); + nextControls.push_back({}); + } + if(safe->commitPlayerTrackEdit( + std::move(nextFiles),std::move(nextControls))) { + if(safe->playerSelected_<0 && first!=static_cast(-1)) + safe->playerSelected_=static_cast(first); + safe->playerError_.clear(); } - if(safe->playerSelected_<0 && first!=static_cast(-1)) - safe->playerSelected_=static_cast(first); - safe->playerError_.clear(); - safe->persistPlayerLibrary(); safe->emitPlayerState(true); // Do not destroy FileChooser inside its own callback. juce::MessageManager::callAsync([safe] { @@ -4272,36 +4313,39 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr relinks=std::move(relinks),initialLibrary]() mutable { if(!safe)return; safe->playerFolderBusy_=false; + auto nextFiles=safe->playerLibrary_; + auto nextControls=safe->playerTrackSettings_; + std::set known(nextFiles.begin(),nextFiles.end()); int added=0,relinked=0; - // Update only the exact rows the worker saw. - // Edits made during the scan must remain intact. + // Reconcile by exact row identity against the + // worker snapshot, without losing later live edits. for(const auto& change:relinks) { if(change.index>=initialLibrary.size() || - change.index>=safe->playerLibrary_.size() || + change.index>=nextFiles.size() || static_cast(change.index)==safe->playerCurrent_ || - safe->playerLibrary_[change.index]!= - initialLibrary[change.index] || - std::find(safe->playerLibrary_.begin(), - safe->playerLibrary_.end(), - change.replacement)!=safe->playerLibrary_.end()) + nextFiles[change.index]!=initialLibrary[change.index] || + known.contains(change.replacement)) continue; - safe->playerLibrary_[change.index]=change.replacement; - ++relinked; // keep stable IDs + KEY/TEMPO + known.erase(nextFiles[change.index]); + known.insert(change.replacement); + nextFiles[change.index]=change.replacement; + ++relinked; } int first=-1; for(const auto& file:scan.files) { - const auto found=std::find( - safe->playerLibrary_.begin(), - safe->playerLibrary_.end(),file); - if(found!=safe->playerLibrary_.end())continue; - if(safe->playerLibrary_.size()>= - armix::player::PlayerLibraryPolicy::maxSongs)break; - if(first<0) - first=static_cast(safe->playerLibrary_.size()); - safe->playerLibrary_.push_back(file); - safe->playerTrackSettings_.push_back({}); + if(known.contains(file))continue; + if(nextFiles.size()>=armix::player::PlayerLibraryPolicy::maxSongs) + break; + if(first<0)first=static_cast(nextFiles.size()); + known.insert(file); + nextFiles.push_back(file); + nextControls.push_back({}); ++added; } + if(!safe->commitPlayerTrackEdit( + std::move(nextFiles),std::move(nextControls))) { + safe->emitPlayerState(true);return; + } if(safe->playerSelected_<0 && first>=0) safe->playerSelected_=first; safe->playerError_=scan.truncated? @@ -4309,7 +4353,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr added==0 && relinked==0? "No new supported songs or safe missing-file matches found": juce::String{}; - safe->persistPlayerLibrary(); safe->emitPlayerState(true); }); }).detach(); @@ -4353,14 +4396,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Preserve same logical song ID, order and per-song // KEY/TEMPO. Never start a song or switch the output // as a side effect of locating a file. - if(safe->playerCurrent_==index) { - safe->engine_.playerStop(); - safe->playerCurrent_=-1; + auto nextFiles=safe->playerLibrary_; + auto nextControls=safe->playerTrackSettings_; + nextFiles[static_cast(index)]=chosen; + if(safe->commitPlayerTrackEdit( + std::move(nextFiles),std::move(nextControls))) { + if(safe->playerCurrent_==index) { + safe->engine_.playerStop(); + safe->playerCurrent_=-1; + } + safe->playerOutputPendingIndex_=-1; + safe->playerError_.clear(); } - safe->playerLibrary_[static_cast(index)]=chosen; - safe->playerOutputPendingIndex_=-1; - safe->playerError_.clear(); - safe->persistPlayerLibrary(); } safe->emitPlayerState(true); }); diff --git a/src/PlayerSetlistEditTransaction.h b/src/PlayerSetlistEditTransaction.h index 250d9087b..a158387ce 100644 --- a/src/PlayerSetlistEditTransaction.h +++ b/src/PlayerSetlistEditTransaction.h @@ -79,15 +79,41 @@ class PlayerSetlistEditTransaction final { } } - const auto stored = PlayerSetlistRepository::save( - archive,candidate,destination,autoNext,fadeMs); - if(stored == SaveStatus::invalidState) + return persist(archive,std::move(candidate),destination,autoNext,fadeMs); + } + + // Any validated active-song edit uses the same durable-before-adopt gate. + // Callers stage MOVE/REMOVE/UNDO/import/relink and adjust the deck/queue + // indices only after this returns a successfully stored candidate. + static Result replaceActiveTracks( + const juce::File& archive, + const std::vector& original,int active, + const std::vector& files, + const std::vector& controls, + bool autoNext,int fadeMs) { + if(original.empty() || active < 0 || + active >= static_cast(original.size()) || + files.size() != controls.size()) + return reject(SaveStatus::invalidState, + "Unable to save setlists; invalid setlist state"); + auto candidate=original; + auto& set=candidate[static_cast(active)]; + set.files=files; + set.controls=controls; + return persist(archive,std::move(candidate),active,autoNext,fadeMs); + } +private: + static Result persist(const juce::File& archive, + std::vector candidate,int active, + bool autoNext,int fadeMs) { + const auto stored=PlayerSetlistRepository::save( + archive,candidate,active,autoNext,fadeMs); + if(stored==SaveStatus::invalidState) return reject(stored,"Unable to save setlists; invalid setlist state"); - if(stored == SaveStatus::ioError) + if(stored==SaveStatus::ioError) return reject(stored,"Unable to save setlists; check folder permissions"); - return {SaveStatus::saved,{},std::move(candidate),destination}; + return {SaveStatus::saved,{},std::move(candidate),active}; } -private: static Result reject(SaveStatus status,juce::String error) { return {status,std::move(error),{},-1}; } diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index a0d83c3a3..da4456212 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -136,6 +136,9 @@ const playerEditTransaction=read('src/PlayerSetlistEditTransaction.h'); assert.match(playerEditTransaction, /PlayerSetlistArchive::nextGeneratedName/); assert.match(playerEditTransaction, /PlayerSetlistRepository::save/); assert.match(main, /PlayerSetlistEditTransaction::apply/); +assert.match(playerEditTransaction, /replaceActiveTracks/); +assert.match(main, /commitPlayerTrackEdit/); +assert.match(main, /Edit::replaceActiveTracks/); assert.match(playerArchive, /static bool canUndoRemove/); assert.match(main, /PlayerSetlistArchive::canUndoRemove/); assert.match(main, /Setlist is full; remove a song before undoing/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index a96e928df..db88418c1 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -326,6 +326,30 @@ int main() { false,180,Edit::Command::remove,0); assert(!deleteLast.committed()); assert(transactionFile.loadFileAsString()==written); + // N-MOD-16 active-track replacement is a transaction too. Invalid + // media/control cardinality and occupied destinations never modify disk + // or require the caller to advance playback/queue indices. + auto revisedFiles=deleted.sets[0].files; + auto revisedControls=deleted.sets[0].controls; + revisedFiles.push_back(tempRoot.getChildFile("nmod16-import.mp3")); + revisedControls.push_back({}); + const auto committedTracks=Edit::replaceActiveTracks(transactionFile, + deleted.sets,deleted.active,revisedFiles,revisedControls,true,250); + assert(committedTracks.committed()); + assert(committedTracks.sets[0].files.size()==1); + assert(deleted.sets[0].files.empty()); + assert(Store::load(transactionFile).document->sets[0].files.size()==1); + const auto tracksBytes=transactionFile.loadFileAsString(); + const auto rejectedTracks=Edit::replaceActiveTracks(transactionFile, + committedTracks.sets,0,revisedFiles,{},true,250); + assert(!rejectedTracks.committed()); + assert(transactionFile.loadFileAsString()==tracksBytes); + const auto failedTracks=Edit::replaceActiveTracks(blocked, + committedTracks.sets,0,revisedFiles,revisedControls,true,250); + assert(!failedTracks.committed() && + failedTracks.status==Store::SaveStatus::ioError); + assert(committedTracks.sets[0].files.size()==1); + assert(transactionFile.loadFileAsString()==tracksBytes); assert(sandbox.deleteRecursively()); // Legacy empty v3 content migrates to a non-destructive default setlist. From c054ae3eff538f9f8d71ee8689d823d3e0610d07 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 10:20:27 +0700 Subject: [PATCH 19/24] test(native N-MOD-16): assert real transaction alias and invoke site --- tests/native_caption_wire_geometry_contract.test.cjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index da4456212..862d57ae5 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -135,7 +135,8 @@ assert.match(playerArchive, /nextGeneratedName/); const playerEditTransaction=read('src/PlayerSetlistEditTransaction.h'); assert.match(playerEditTransaction, /PlayerSetlistArchive::nextGeneratedName/); assert.match(playerEditTransaction, /PlayerSetlistRepository::save/); -assert.match(main, /PlayerSetlistEditTransaction::apply/); +assert.match(main, /using Edit=armix::player::PlayerSetlistEditTransaction/); +assert.match(main, /auto outcome=Edit::apply/); assert.match(playerEditTransaction, /replaceActiveTracks/); assert.match(main, /commitPlayerTrackEdit/); assert.match(main, /Edit::replaceActiveTracks/); From 658cbc2cca0b14eddc61b2f692765702d5059248 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 10:23:06 +0700 Subject: [PATCH 20/24] fix(native N-MOD-16): include transaction under standalone JUCE CTest --- tests/player_setlist_archive_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index db88418c1..e41daed12 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -7,6 +7,7 @@ #include #include "../src/PlayerSetlistArchive.h" #include "../src/PlayerSetlistRepository.h" +#include "../src/PlayerSetlistEditTransaction.h" using Archive=armix::player::PlayerSetlistArchive; using SavedSet=armix::player::PlayerSavedSet; From 2eba5e72b39382ad8762ea1bd0d5b010167ec5da Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 10:44:02 +0700 Subject: [PATCH 21/24] refactor(native N-MOD-17): compensate live metadata edits and persist Player preferences atomically --- .../player/PlayerLiveMetadataCommitPolicy.h | 29 ++++ src/Main.cpp | 125 +++++++++++------- ...ve_caption_wire_geometry_contract.test.cjs | 11 +- tests/player_setlist_archive_test.cpp | 35 +++++ 4 files changed, 152 insertions(+), 48 deletions(-) create mode 100644 engine/player/PlayerLiveMetadataCommitPolicy.h diff --git a/engine/player/PlayerLiveMetadataCommitPolicy.h b/engine/player/PlayerLiveMetadataCommitPolicy.h new file mode 100644 index 000000000..ccaa424a5 --- /dev/null +++ b/engine/player/PlayerLiveMetadataCommitPolicy.h @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +// N-MOD-17: compensation policy for durable Player metadata writes on the +// JUCE CONTROL thread. The existing LiveAudioEngine remains the sole deck +// owner. Native acceptance precedes disk I/O for responsive live KEY/TEMPO +// and Cue gestures; failed persistence attempts the exact previous values. +// An unrecoverable native rollback is handled by the caller's safe stop. +namespace armix::player { +struct PlayerLiveMetadataCommitPolicy final { + enum class Outcome { + accepted, + nativeRejected, + saveRejectedRecovered, + saveRejectedRollbackFailed + }; + template + static Outcome run(bool requiresNative,ApplyNative&& apply, + Save&& save,RestoreNative&& restore) { + // Editing NEXT is metadata only. No native/PCM DSP mutation happens. + if(!requiresNative) + return save()?Outcome::accepted:Outcome::saveRejectedRecovered; + if(!apply())return Outcome::nativeRejected; + if(save())return Outcome::accepted; + return restore()?Outcome::saveRejectedRecovered: + Outcome::saveRejectedRollbackFailed; + } +}; +} // namespace armix::player diff --git a/src/Main.cpp b/src/Main.cpp index 7a04b6746..482b822c7 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -71,6 +71,7 @@ #include "../engine/player/PlayerShowEditPolicy.h" #include "../engine/player/PlayerShowTransitionPolicy.h" #include "../engine/player/PlayerCueEditPolicy.h" +#include "../engine/player/PlayerLiveMetadataCommitPolicy.h" #include "../engine/player/PlayerLibraryPolicy.h" #include #include @@ -3885,15 +3886,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Versioned setlist v3. Song paths remain external and are NEVER moved, // deleted or copied by editing a show. v1/v2 migrate non-destructively. - void saveActivePlayerSet() { - if(playerSets_.empty())playerSets_.push_back({"My Setlist",{},{}}); - if(playerActiveSet_<0 || - playerActiveSet_>=static_cast(playerSets_.size())) - playerActiveSet_=0; - auto& active=playerSets_[static_cast(playerActiveSet_)]; - active.files=playerLibrary_; - active.controls=playerTrackSettings_; - } void activatePlayerSet(int index) { if(index<0 || index>=static_cast(playerSets_.size()))return; playerActiveSet_=index; @@ -3932,33 +3924,49 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerAutoNext_=parsed.autoNext; playerFadeMilliseconds_=parsed.fadeMs; } - void persistPlayerLibrary() { - saveActivePlayerSet(); - const auto result=armix::player::PlayerSetlistRepository::save( - settingsDirectory().getChildFile("player-library.json"), - playerSets_,playerActiveSet_,playerAutoNext_,playerFadeMilliseconds_); - if(result==armix::player::PlayerSetlistRepository::SaveStatus::invalidState) - playerError_="Unable to save setlists; invalid setlist state"; - else if(result==armix::player::PlayerSetlistRepository::SaveStatus::ioError) - playerError_="Unable to save setlists; check folder permissions"; - } - bool commitPlayerTrackEdit(std::vector nextFiles, - std::vector nextControls) { + bool commitPlayerMetadata(std::vector nextFiles, + std::vector nextControls, + bool nextAutoNext,int nextFadeMs) { using Edit=armix::player::PlayerSetlistEditTransaction; auto outcome=Edit::replaceActiveTracks( settingsDirectory().getChildFile("player-library.json"), playerSets_,playerActiveSet_,nextFiles,nextControls, - playerAutoNext_,playerFadeMilliseconds_); + nextAutoNext,nextFadeMs); if(!outcome.committed()) { playerError_=outcome.error; return false; } - // No accepted Player identity/queue/index change precedes disk commit. + // File acceptance comes before EVERY durable in-memory mutation. playerSets_=std::move(outcome.sets); playerLibrary_=std::move(nextFiles); playerTrackSettings_=std::move(nextControls); + playerAutoNext_=nextAutoNext; + playerFadeMilliseconds_=nextFadeMs; return true; } + bool commitPlayerTrackEdit(std::vector nextFiles, + std::vector nextControls) { + return commitPlayerMetadata(std::move(nextFiles), + std::move(nextControls),playerAutoNext_,playerFadeMilliseconds_); + } + bool commitPlayerPreferences(bool nextAutoNext,int nextFadeMs) { + return commitPlayerMetadata(playerLibrary_,playerTrackSettings_, + nextAutoNext,nextFadeMs); + } + void stopPlayerAfterUnrecoveredMetadata() { + // Persist rejected AND native restore rejected. Never leave an + // unrecorded live deck applying controls different from the setlist. + if(playerPendingIndex_>=0)playerQueueEpoch_.changed(); + engine_.playerStop(); + playerCurrent_=-1; + playerPendingIndex_=-1; + playerPendingQueueFile_={}; + playerOutputPendingIndex_=-1; + playerLoopCurrent_=false; + playerAutoAdvanceGate_.rearm(); + playerError_="Could not save song settings or restore native playback; " + "Player stopped to keep setlist safe"; + } bool playerShowMaySwitchSet() { const auto state=engine_.playerStatus().getProperty("state","").toString(); if(state=="PLAYING" || state=="PREPARING" || state=="PAUSED") { @@ -4584,17 +4592,25 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else if(direction==1 || direction==-1) next.tempo=std::clamp(next.tempo+direction*5,80,120); else return; // invalid native control intent cannot mutate DSP - // A performer must be able to tune NEXT while CURRENT is - // playing without changing CURRENT audio. Only send live DSP - // commands for the currently loaded song. - if(!target.updateLiveDeck || - engine_.setPlayerPitchTempo(next.key,next.tempo)) { - playerTrackSettings_[static_cast(i)]=next; + // NEXT changes persist without touching CURRENT audio. For a + // loaded CURRENT, use native-first acceptance, durable Save and + // compensation on failure; never publish unsaved track state. + using NativeMeta=armix::player::PlayerLiveMetadataCommitPolicy; + const auto previous=playerTrackSettings_[static_cast(i)]; + auto staged=playerTrackSettings_; + staged[static_cast(i)]=next; + const auto outcome=NativeMeta::run( + target.updateLiveDeck, + [&]{return engine_.setPlayerPitchTempo(next.key,next.tempo);}, + [&]{return commitPlayerTrackEdit(playerLibrary_,std::move(staged));}, + [&]{return engine_.setPlayerPitchTempo(previous.key,previous.tempo);}); + if(outcome==NativeMeta::Outcome::accepted) playerError_.clear(); - persistPlayerLibrary(); - emitPlayerState(true); - } - return; + else if(outcome==NativeMeta::Outcome::nativeRejected) + playerError_="Unable to apply native KEY or TEMPO"; + else if(outcome==NativeMeta::Outcome::saveRejectedRollbackFailed) + stopPlayerAfterUnrecoveredMetadata(); + emitPlayerState(true);return; } if(action=="playerLoopToggle") { const bool enable=value.isBool() && static_cast(value); @@ -4628,7 +4644,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerError_="Select the playing song to edit its cue"; emitPlayerState();return; } - auto& cues=playerTrackSettings_[static_cast( + const auto cues=playerTrackSettings_[static_cast( playerCurrent_)]; const auto transport=engine_.playerStatus(); const double now=static_cast( @@ -4658,20 +4674,32 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "OUT must be after IN":"Invalid song cue marker"; emitPlayerState();return; } - // Deck admission FIRST. Failed or invalid edits must never - // poison the persisted v3 archive or the WebView readback. - if(!engine_.setPlayerCueRange(nextCue->in,nextCue->out)) { + // Native admission FIRST (as before); stage the proposed + // archive edit, and restore the previous accepted cue if the + // durable Save rejects. Never mutate the live control vector + // until both native and disk accepted the candidate. + using NativeMeta=armix::player::PlayerLiveMetadataCommitPolicy; + auto staged=playerTrackSettings_; + staged[static_cast(playerCurrent_)].cueIn=nextCue->in; + staged[static_cast(playerCurrent_)].cueOut=nextCue->out; + const auto outcome=NativeMeta::run(true, + [&]{return engine_.setPlayerCueRange(nextCue->in,nextCue->out);}, + [&]{return commitPlayerTrackEdit(playerLibrary_,std::move(staged));}, + [&]{return engine_.setPlayerCueRange(cues.cueIn,cues.cueOut);}); + if(outcome==NativeMeta::Outcome::nativeRejected) { playerError_="Could not update native song markers"; emitPlayerState();return; } - cues.cueIn=nextCue->in; - cues.cueOut=nextCue->out; + if(outcome==NativeMeta::Outcome::saveRejectedRollbackFailed) + stopPlayerAfterUnrecoveredMetadata(); + if(outcome!=NativeMeta::Outcome::accepted) { + emitPlayerState(true);return; + } if(playerLoopCurrent_ && !armix::player::PlayerShowTransitionPolicy::validLoop( - cues.cueIn,cues.cueOut,playerFadeMilliseconds_)) + nextCue->in,nextCue->out,playerFadeMilliseconds_)) playerLoopCurrent_=false; - playerError_.clear();persistPlayerLibrary(); - emitPlayerState(true);return; + playerError_.clear();emitPlayerState(true);return; } if(action=="playerPlay")return playTransportMusic(); if(action=="playerSeek") { @@ -4704,14 +4732,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return playNextMusic(); } if(action=="playerAutoNext") { + const bool next=value.isBool() && static_cast(value); + if(!commitPlayerPreferences(next,playerFadeMilliseconds_)) { + emitPlayerState(true);return; + } playerAutoAdvanceGate_.rearm(); - playerAutoNext_=value.isBool() && static_cast(value); - persistPlayerLibrary();emitPlayerState(true);return; + playerError_.clear();emitPlayerState(true);return; } if(action=="playerFadeMs") { const int ms=static_cast(value); if(ms!=0 && ms!=180 && ms!=500 && ms!=1500)return; - playerFadeMilliseconds_=ms; + if(!commitPlayerPreferences(playerAutoNext_,ms)) { + emitPlayerState();return; + } if(playerLoopCurrent_ && playerCurrent_>=0 && playerCurrent_(playerTrackSettings_.size())) { const auto cue=playerTrackSettings_[ @@ -4720,7 +4753,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr cue.cueIn,cue.cueOut,ms)) playerLoopCurrent_=false; } - persistPlayerLibrary();emitPlayerState();return; + playerError_.clear();emitPlayerState();return; } if(action=="playerSelect" || action=="playerPlayNow") { const int i=static_cast(value); diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 862d57ae5..6cc940a77 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -150,7 +150,13 @@ assert.match(playerRepository, /class PlayerSetlistRepository final/); assert.match(playerRepository, /juce::TemporaryFile staging\(target\)/); assert.match(playerRepository, /overwriteTargetFileWithTemporary\(\)/); assert.match(main, /PlayerSetlistRepository::load/); -assert.match(main, /PlayerSetlistRepository::save/); +assert.doesNotMatch(main, /PlayerSetlistRepository::save/); +assert.doesNotMatch(main, /void persistPlayerLibrary\(\)/); +assert.match(main, /commitPlayerMetadata/); +const playerLiveCommit=read('engine/player/PlayerLiveMetadataCommitPolicy.h'); +assert.match(playerLiveCommit, /saveRejectedRollbackFailed/); +assert.match(main, /NativeMeta::run/); +assert.match(main, /stopPlayerAfterUnrecoveredMetadata/); const persistence=main.slice(main.indexOf('void restorePlayerLibrary()'), main.indexOf('bool playerShowMaySwitchSet()')); assert.doesNotMatch(persistence, @@ -162,8 +168,9 @@ assert.match(main, /CuePolicy::plan/); const cueAction=main.slice(main.indexOf('if(action=="playerCueIn"'), main.indexOf('if(action=="playerPlay")')); assert.ok(cueAction.indexOf('engine_.setPlayerCueRange(nextCue->in,nextCue->out)') >= 0); -assert.ok(cueAction.indexOf('cues.cueIn=nextCue->in') > +assert.ok(cueAction.indexOf('commitPlayerTrackEdit(playerLibrary_,std::move(staged))') > cueAction.indexOf('engine_.setPlayerCueRange(nextCue->in,nextCue->out)')); +assert.match(cueAction, /engine_\.setPlayerCueRange\(cues\.cueIn,cues\.cueOut\)/); assert.match(main, /action=="playerKeyStep" \|\| action=="playerTempoStep"/); assert.match(main, /setPlayerPitchTempo\(next\.key,next\.tempo\)/); assert.match(playerHtml, /id="playerKeyMinus"/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index e41daed12..1c8079a35 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -8,6 +8,7 @@ #include "../src/PlayerSetlistArchive.h" #include "../src/PlayerSetlistRepository.h" #include "../src/PlayerSetlistEditTransaction.h" +#include "../engine/player/PlayerLiveMetadataCommitPolicy.h" using Archive=armix::player::PlayerSetlistArchive; using SavedSet=armix::player::PlayerSavedSet; @@ -351,6 +352,40 @@ int main() { failedTracks.status==Store::SaveStatus::ioError); assert(committedTracks.sets[0].files.size()==1); assert(transactionFile.loadFileAsString()==tracksBytes); + // N-MOD-17: preferences are saved on the same durable-first boundary. + // A rejected disk write cannot enable Auto Next or alter future fades. + const auto prefs=Edit::replaceActiveTracks( + transactionFile,committedTracks.sets,0,revisedFiles,revisedControls, + false,500); + assert(prefs.committed()); + const auto acceptedPrefs=Store::load(transactionFile); + assert(acceptedPrefs.document && !acceptedPrefs.document->autoNext); + assert(acceptedPrefs.document->fadeMs==500); + const auto prefsBytes=transactionFile.loadFileAsString(); + const auto failedPrefs=Edit::replaceActiveTracks( + blocked,prefs.sets,0,revisedFiles,revisedControls,true,1500); + assert(!failedPrefs.committed() && + failedPrefs.status==Store::SaveStatus::ioError); + assert(transactionFile.loadFileAsString()==prefsBytes); + + // Pure native+disk compensation sequencing. No JUCE audio device needed. + using Meta=armix::player::PlayerLiveMetadataCommitPolicy; + auto verifyMeta=[&](bool live,bool nativeOk,bool saveOk,bool rollbackOk, + Meta::Outcome expected,const char* order) { + std::string sequence; + const auto outcome=Meta::run(live, + [&]{sequence+='A';return nativeOk;}, + [&]{sequence+='S';return saveOk;}, + [&]{sequence+='R';return rollbackOk;}); + assert(outcome==expected && sequence==order); + }; + verifyMeta(false,false,true,false,Meta::Outcome::accepted,"S"); + verifyMeta(false,false,false,false,Meta::Outcome::saveRejectedRecovered,"S"); + verifyMeta(true,false,true,true,Meta::Outcome::nativeRejected,"A"); + verifyMeta(true,true,true,false,Meta::Outcome::accepted,"AS"); + verifyMeta(true,true,false,true,Meta::Outcome::saveRejectedRecovered,"ASR"); + verifyMeta(true,true,false,false, + Meta::Outcome::saveRejectedRollbackFailed,"ASR"); assert(sandbox.deleteRecursively()); // Legacy empty v3 content migrates to a non-destructive default setlist. From 818ae6c60d84f7882c865dc8f341671a6fd92780 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 11:12:26 +0700 Subject: [PATCH 22/24] refactor(native N-MOD-18): isolate Player library edit/import/relink plans and regressions --- src/Main.cpp | 163 +++++++----------- src/PlayerLibraryEditPlan.h | 157 +++++++++++++++++ ...ve_caption_wire_geometry_contract.test.cjs | 9 + tests/player_setlist_archive_test.cpp | 68 ++++++++ 4 files changed, 294 insertions(+), 103 deletions(-) create mode 100644 src/PlayerLibraryEditPlan.h diff --git a/src/Main.cpp b/src/Main.cpp index 482b822c7..158e2fc91 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -48,6 +48,7 @@ #include "PlayerSetlistArchive.h" #include "PlayerSetlistRepository.h" #include "PlayerSetlistEditTransaction.h" +#include "PlayerLibraryEditPlan.h" #include "NativeHotkeyRegistry.h" #include "NativeHotkeyCommandPlan.h" #include "NativeFxParameterHotkey.h" @@ -4015,15 +4016,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const int to=static_cast(value.getProperty("to",-1)); const int count=static_cast(playerLibrary_.size()); if(from<0 || to<0 || from>=count || to>=count || from==to)return; - auto move=[&](auto& items) { - auto item=std::move(items[static_cast(from)]); - items.erase(items.begin()+from); - items.insert(items.begin()+to,std::move(item)); - }; - auto nextFiles=playerLibrary_; - auto nextControls=playerTrackSettings_; - move(nextFiles);move(nextControls); - if(!commitPlayerTrackEdit(std::move(nextFiles),std::move(nextControls))) { + auto plan=armix::player::PlayerLibraryEditPlan::move( + playerLibrary_,playerTrackSettings_,from,to); + if(!plan)return; + if(!commitPlayerTrackEdit( + std::move(plan->files),std::move(plan->controls))) { emitPlayerState(true);return; } const auto remap=[&](int index) { @@ -4051,11 +4048,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } const auto removedFile=playerLibrary_[static_cast(index)]; const auto removedControls=playerTrackSettings_[static_cast(index)]; - auto nextFiles=playerLibrary_; - auto nextControls=playerTrackSettings_; - nextFiles.erase(nextFiles.begin()+index); - nextControls.erase(nextControls.begin()+index); - if(!commitPlayerTrackEdit(std::move(nextFiles),std::move(nextControls))) { + auto plan=armix::player::PlayerLibraryEditPlan::remove( + playerLibrary_,playerTrackSettings_,index); + if(!plan)return; + if(!commitPlayerTrackEdit( + std::move(plan->files),std::move(plan->controls))) { emitPlayerState(true);return; } playerUndoRemove_={playerActiveSet_,index,removedFile,removedControls}; @@ -4091,13 +4088,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } if(std::find(playerLibrary_.begin(),playerLibrary_.end(), removed.file)!=playerLibrary_.end())return; - const int index=std::clamp(removed.index,0, - static_cast(playerLibrary_.size())); - auto nextFiles=playerLibrary_; - auto nextControls=playerTrackSettings_; - nextFiles.insert(nextFiles.begin()+index,removed.file); - nextControls.insert(nextControls.begin()+index,removed.controls); - if(!commitPlayerTrackEdit(std::move(nextFiles),std::move(nextControls))) { + auto plan=armix::player::PlayerLibraryEditPlan::undo( + playerLibrary_,playerTrackSettings_,removed.index, + removed.file,removed.controls); + if(!plan)return; + const int index=plan->first; + if(!commitPlayerTrackEdit( + std::move(plan->files),std::move(plan->controls))) { emitPlayerState(true);return; } playerCurrent_=armix::player::PlayerShowEditPolicy::afterInsert( @@ -4245,39 +4242,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr [safe=juce::Component::SafePointer(this)] (const juce::FileChooser& picker) { if(!safe)return; - const auto files=picker.getResults(); - auto nextFiles=safe->playerLibrary_; - auto nextControls=safe->playerTrackSettings_; - // JUCE File order matches the native archive path identity; - // a 2,000-song import never needs quadratic scans. - std::map positions; - for(std::size_t i=0;i(-1); - for(const auto& file:files) { - if(!file.existsAsFile() || - !file.hasFileExtension("wav;mp3;flac;aif;aiff;ogg")) - continue; - const auto known=positions.find(file); - if(known!=positions.end()) { - if(first==static_cast(-1)) - first=known->second; - continue; + const auto plan=armix::player::PlayerLibraryEditPlan::append( + safe->playerLibrary_,safe->playerTrackSettings_, + picker.getResults()); + if(!plan) { + safe->playerError_="Unable to import music; invalid library state"; + safe->emitPlayerState(true); + } else { + const int first=plan->first; + if(safe->commitPlayerTrackEdit( + std::move(plan->files),std::move(plan->controls))) { + if(safe->playerSelected_<0 && first>=0) + safe->playerSelected_=first; + safe->playerError_.clear(); } - if(nextFiles.size()>=2000)break; - if(first==static_cast(-1)) - first=nextFiles.size(); - positions.emplace(file,nextFiles.size()); - nextFiles.push_back(file); - nextControls.push_back({}); - } - if(safe->commitPlayerTrackEdit( - std::move(nextFiles),std::move(nextControls))) { - if(safe->playerSelected_<0 && first!=static_cast(-1)) - safe->playerSelected_=static_cast(first); - safe->playerError_.clear(); + safe->emitPlayerState(true); } - safe->emitPlayerState(true); // Do not destroy FileChooser inside its own callback. juce::MessageManager::callAsync([safe] { if(safe)safe->playerFileChooser_.reset(); @@ -4321,37 +4301,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr relinks=std::move(relinks),initialLibrary]() mutable { if(!safe)return; safe->playerFolderBusy_=false; - auto nextFiles=safe->playerLibrary_; - auto nextControls=safe->playerTrackSettings_; - std::set known(nextFiles.begin(),nextFiles.end()); - int added=0,relinked=0; - // Reconcile by exact row identity against the - // worker snapshot, without losing later live edits. - for(const auto& change:relinks) { - if(change.index>=initialLibrary.size() || - change.index>=nextFiles.size() || - static_cast(change.index)==safe->playerCurrent_ || - nextFiles[change.index]!=initialLibrary[change.index] || - known.contains(change.replacement)) - continue; - known.erase(nextFiles[change.index]); - known.insert(change.replacement); - nextFiles[change.index]=change.replacement; - ++relinked; - } - int first=-1; - for(const auto& file:scan.files) { - if(known.contains(file))continue; - if(nextFiles.size()>=armix::player::PlayerLibraryPolicy::maxSongs) - break; - if(first<0)first=static_cast(nextFiles.size()); - known.insert(file); - nextFiles.push_back(file); - nextControls.push_back({}); - ++added; + auto plan=armix::player::PlayerLibraryEditPlan::folder( + initialLibrary,safe->playerLibrary_, + safe->playerTrackSettings_,scan,relinks, + safe->playerCurrent_); + if(!plan) { + safe->playerError_="Unable to import folder; invalid library state"; + safe->emitPlayerState(true);return; } + const int added=plan->added,relinked=plan->relinked; + const int first=plan->first; if(!safe->commitPlayerTrackEdit( - std::move(nextFiles),std::move(nextControls))) { + std::move(plan->files),std::move(plan->controls))) { safe->emitPlayerState(true);return; } if(safe->playerSelected_<0 && first>=0) @@ -4390,32 +4351,28 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(safe)safe->playerFileChooser_.reset(); }); if(chosen==juce::File{})return; - if(index>=static_cast(safe->playerLibrary_.size()) || - safe->playerLibrary_[static_cast(index)]!=old) { + auto planned=armix::player::PlayerLibraryEditPlan::manualRelink( + safe->playerLibrary_,safe->playerTrackSettings_, + index,old,chosen); + using RelinkError=armix::player::PlayerLibraryEditPlan::RelinkError; + if(planned.error==RelinkError::staleRow) safe->playerError_="Setlist changed; locate the song again"; - } else if(!armix::player::PlayerLibraryPolicy::sameSongName( - old,chosen)) { + else if(planned.error==RelinkError::wrongSong) safe->playerError_="Choose the same song filename to avoid relinking the wrong music"; - } else if(std::find(safe->playerLibrary_.begin(), - safe->playerLibrary_.end(),chosen)!= - safe->playerLibrary_.end()) { + else if(planned.error==RelinkError::alreadyPresent) safe->playerError_="This music file is already in your setlist"; - } else { - // Preserve same logical song ID, order and per-song - // KEY/TEMPO. Never start a song or switch the output - // as a side effect of locating a file. - auto nextFiles=safe->playerLibrary_; - auto nextControls=safe->playerTrackSettings_; - nextFiles[static_cast(index)]=chosen; - if(safe->commitPlayerTrackEdit( - std::move(nextFiles),std::move(nextControls))) { - if(safe->playerCurrent_==index) { - safe->engine_.playerStop(); - safe->playerCurrent_=-1; - } - safe->playerOutputPendingIndex_=-1; - safe->playerError_.clear(); + else if(planned.candidate && + safe->commitPlayerTrackEdit( + std::move(planned.candidate->files), + std::move(planned.candidate->controls))) { + // File path identity and KEY/TEMPO/Cue remain stable. + // No transport changes before durable acceptance. + if(safe->playerCurrent_==index) { + safe->engine_.playerStop(); + safe->playerCurrent_=-1; } + safe->playerOutputPendingIndex_=-1; + safe->playerError_.clear(); } safe->emitPlayerState(true); }); diff --git a/src/PlayerLibraryEditPlan.h b/src/PlayerLibraryEditPlan.h new file mode 100644 index 000000000..0346d8bc5 --- /dev/null +++ b/src/PlayerLibraryEditPlan.h @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "PlayerSetlistArchive.h" +#include "../engine/player/PlayerLibraryPolicy.h" +#include +#include +#include +#include +#include +#include + +// N-MOD-18: immutable candidate editing on JUCE CONTROL. No disk writes, +// UI, transport, or PCM changes. ConsoleWindow commits a candidate only +// after the ONE PlayerSetlistEditTransaction repository save succeeds. +namespace armix::player { +class PlayerLibraryEditPlan final { +public: + struct Candidate { + std::vector files; + std::vector controls; + int first = -1; // first newly inserted OR already-selected file + int added = 0; + int relinked = 0; + }; + enum class RelinkError { none, staleRow, wrongSong, alreadyPresent }; + struct RelinkResult { + RelinkError error=RelinkError::none; + std::optional candidate; + }; + static std::optional base( + const std::vector& live, + const std::vector& controls) { + if(live.size()!=controls.size() || + live.size()>PlayerLibraryPolicy::maxSongs)return std::nullopt; + return Candidate{live,controls}; + } + static std::optional append( + const std::vector& live, + const std::vector& controls, + const juce::Array& selected) { + auto result=base(live,controls); + if(!result)return std::nullopt; + std::map positions; + for(int i=0;i(result->files.size());++i) + positions.emplace(result->files[static_cast(i)],i); + for(const auto& file:selected) { + if(!file.existsAsFile() || !PlayerLibraryPolicy::supported(file)) + continue; + const auto it=positions.find(file); + if(it!=positions.end()) { + if(result->first<0)result->first=it->second; + continue; + } + if(result->files.size()>=PlayerLibraryPolicy::maxSongs)break; + const auto index=static_cast(result->files.size()); + if(result->first<0)result->first=index; + positions.emplace(file,index); + result->files.push_back(file); + result->controls.emplace_back(); + ++result->added; + } + return result; + } + // Apply worker findings only to exact rows seen when that scan began. + // Later performer edits are preserved; no worker may accept a native + // model, stop a deck, or publish a WebView snapshot. + static std::optional folder( + const std::vector& snapshot, + const std::vector& live, + const std::vector& controls, + const PlayerLibraryPolicy::Scan& scan, + const std::vector& relinks, + int protectedCurrent) { + auto result=base(live,controls); + if(!result)return std::nullopt; + std::set seen(result->files.begin(),result->files.end()); + for(const auto& change:relinks) { + const auto index=change.index; + if(index>=snapshot.size() || index>=result->files.size() || + static_cast(index)==protectedCurrent || + result->files[index]!=snapshot[index] || + seen.contains(change.replacement))continue; + seen.erase(result->files[index]); + seen.insert(change.replacement); + result->files[index]=change.replacement; + ++result->relinked; + } + for(const auto& file:scan.files) { + if(seen.contains(file))continue; + if(result->files.size()>=PlayerLibraryPolicy::maxSongs)break; + if(result->first<0) + result->first=static_cast(result->files.size()); + seen.insert(file); + result->files.push_back(file); + result->controls.emplace_back(); + ++result->added; + } + return result; + } + static RelinkResult manualRelink( + const std::vector& live, + const std::vector& controls, + int index,const juce::File& expected,const juce::File& chosen) { + auto result=base(live,controls); + if(!result||index<0||index>=static_cast(live.size())|| + live[static_cast(index)]!=expected) + return {RelinkError::staleRow,{}}; + if(!PlayerLibraryPolicy::sameSongName(expected,chosen)) + return {RelinkError::wrongSong,{}}; + if(std::find(live.begin(),live.end(),chosen)!=live.end()) + return {RelinkError::alreadyPresent,{}}; + result->files[static_cast(index)]=chosen; + return {RelinkError::none,std::move(result)}; + } + static std::optional move( + const std::vector& live, + const std::vector& controls, + int from,int to) { + auto result=base(live,controls); + if(!result||from<0||to<0|| + from>=static_cast(live.size())|| + to>=static_cast(live.size())||from==to)return std::nullopt; + auto reorder=[&](auto& values) { + auto entry=std::move(values[static_cast(from)]); + values.erase(values.begin()+from); + values.insert(values.begin()+to,std::move(entry)); + }; + reorder(result->files); + reorder(result->controls); + return result; + } + static std::optional remove( + const std::vector& live, + const std::vector& controls,int index) { + auto result=base(live,controls); + if(!result||index<0||index>=static_cast(live.size())) + return std::nullopt; + result->files.erase(result->files.begin()+index); + result->controls.erase(result->controls.begin()+index); + return result; + } + static std::optional undo( + const std::vector& live, + const std::vector& controls, + int index,const juce::File& song,PlayerTrackSettings settings) { + auto result=base(live,controls); + if(!result||live.size()>=PlayerLibraryPolicy::maxSongs|| + index<0||std::find(live.begin(),live.end(),song)!=live.end()) + return std::nullopt; + const auto at=std::min(index,static_cast(live.size())); + result->files.insert(result->files.begin()+at,song); + result->controls.insert(result->controls.begin()+at,settings); + result->first=at; + return result; + } +}; +} // namespace armix::player diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 6cc940a77..4ae3a5e18 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -139,6 +139,15 @@ assert.match(main, /using Edit=armix::player::PlayerSetlistEditTransaction/); assert.match(main, /auto outcome=Edit::apply/); assert.match(playerEditTransaction, /replaceActiveTracks/); assert.match(main, /commitPlayerTrackEdit/); +const libraryPlan=read('src/PlayerLibraryEditPlan.h'); +assert.match(libraryPlan, /class PlayerLibraryEditPlan final/); +assert.match(libraryPlan, /static std::optional folder/); +assert.match(main, /PlayerLibraryEditPlan::append/); +assert.match(main, /PlayerLibraryEditPlan::folder/); +assert.match(main, /PlayerLibraryEditPlan::manualRelink/); +assert.match(main, /PlayerLibraryEditPlan::move/); +assert.match(main, /PlayerLibraryEditPlan::remove/); +assert.match(main, /PlayerLibraryEditPlan::undo/); assert.match(main, /Edit::replaceActiveTracks/); assert.match(playerArchive, /static bool canUndoRemove/); assert.match(main, /PlayerSetlistArchive::canUndoRemove/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 1c8079a35..689c084a8 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -8,6 +8,7 @@ #include "../src/PlayerSetlistArchive.h" #include "../src/PlayerSetlistRepository.h" #include "../src/PlayerSetlistEditTransaction.h" +#include "../src/PlayerLibraryEditPlan.h" #include "../engine/player/PlayerLiveMetadataCommitPolicy.h" using Archive=armix::player::PlayerSetlistArchive; @@ -388,6 +389,73 @@ int main() { Meta::Outcome::saveRejectedRollbackFailed,"ASR"); assert(sandbox.deleteRecursively()); + // N-MOD-18: real JUCE File plan with in-memory candidate immutability. + using LibraryPlan=armix::player::PlayerLibraryEditPlan; + const auto physical=sandbox.getChildFile("music"); + assert(physical.createDirectory().wasOk()); + const auto songA=physical.getChildFile("song-a.wav"); + const auto songB=physical.getChildFile("song-b.flac"); + const auto bad=physical.getChildFile("song-c.txt"); + assert(songA.replaceWithText("audio-fixture")); + assert(songB.replaceWithText("audio-fixture")); + assert(bad.replaceWithText("not music")); + juce::Array selectedFiles; + selectedFiles.add(songA);selectedFiles.add(songA); + selectedFiles.add(bad);selectedFiles.add(songB); + auto imported=LibraryPlan::append({}, {},selectedFiles); + assert(imported && imported->added==2 && imported->first==0); + assert(imported->files[0]==songA && imported->files[1]==songB); + assert(imported->controls.size()==2); + auto importedAgain=LibraryPlan::append( + imported->files,imported->controls,selectedFiles); + assert(importedAgain && importedAgain->added==0 && importedAgain->first==0); + auto pairControls=imported->controls; + pairControls[0].key=4;pairControls[1].tempo=115; + const auto moved=LibraryPlan::move(imported->files,pairControls,0,1); + assert(moved && moved->files[1]==songA); + assert(moved->controls[1].key==4 && moved->controls[0].tempo==115); + assert(imported->files[0]==songA && pairControls[0].key==4); + const auto removed=LibraryPlan::remove(moved->files,moved->controls,1); + assert(removed && removed->files.size()==1 && removed->files[0]==songB); + const auto undone=LibraryPlan::undo( + removed->files,removed->controls,1,songA,pairControls[0]); + assert(undone && undone->first==1 && undone->controls[1].key==4); + assert(!LibraryPlan::undo( + undone->files,undone->controls,0,songA,pairControls[0])); + assert(!LibraryPlan::move(imported->files,pairControls,-1,1)); + assert(!LibraryPlan::append(imported->files,{},selectedFiles)); + + const auto missing=sandbox.getChildFile("lost/song-b.flac"); + const auto staleReplaced=LibraryPlan::manualRelink( + {missing},{Track{}},0,missing,songB); + assert(staleReplaced.candidate && staleReplaced.candidate->files[0]==songB); + assert(LibraryPlan::manualRelink({songA},{Track{}},0,missing,songB).error== + LibraryPlan::RelinkError::staleRow); + assert(LibraryPlan::manualRelink({missing},{Track{}},0,missing,songA).error== + LibraryPlan::RelinkError::wrongSong); + assert(LibraryPlan::manualRelink( + {missing,songB},{Track{},Track{}},0,missing,songB).error== + LibraryPlan::RelinkError::alreadyPresent); + armix::player::PlayerLibraryPolicy::Scan foundMusic; + foundMusic.files={songA,songB}; + const auto folderResult=LibraryPlan::folder( + {missing},{missing},{Track{}},foundMusic, + {{0,songB}},-1); + assert(folderResult && folderResult->relinked==1); + assert(folderResult->added==1 && folderResult->files[0]==songB); + assert(folderResult->files[1]==songA); + // A concurrent UI replacement invalidates the scan's row identity. + const auto staleFolder=LibraryPlan::folder( + {missing},{songA},{Track{}},foundMusic, + {{0,songB}},-1); + assert(staleFolder && staleFolder->relinked==0); + assert(staleFolder->files[0]==songA); + const auto noLiveRelink=LibraryPlan::folder( + {missing},{missing},{Track{}},foundMusic, + {{0,songB}},0); + assert(noLiveRelink && noLiveRelink->relinked==0); + assert(physical.deleteRecursively()); + // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); assert(empty && empty->sets.size()==1); From 87503bf189c40bd95ee42250f3cd7794d5c6dd4e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 11:14:05 +0700 Subject: [PATCH 23/24] refactor(native N-MOD-18): extract authoritative Player snapshot projection with independent JUCE regression --- src/Main.cpp | 74 +++----------- src/PlayerStateProjection.h | 97 +++++++++++++++++++ ...ve_caption_wire_geometry_contract.test.cjs | 8 ++ tests/player_setlist_archive_test.cpp | 38 +++++++- 4 files changed, 156 insertions(+), 61 deletions(-) create mode 100644 src/PlayerStateProjection.h diff --git a/src/Main.cpp b/src/Main.cpp index 158e2fc91..2acda0e6a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -49,6 +49,7 @@ #include "PlayerSetlistRepository.h" #include "PlayerSetlistEditTransaction.h" #include "PlayerLibraryEditPlan.h" +#include "PlayerStateProjection.h" #include "NativeHotkeyRegistry.h" #include "NativeHotkeyCommandPlan.h" #include "NativeFxParameterHotkey.h" @@ -4167,67 +4168,20 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void emitPlayerState(bool includeLibrary=false, bool includeTracks=true) { if(!browser_.loaded)return; - auto obj=std::make_unique(); - obj->setProperty("schema","arsonmix.player.v1"); - obj->setProperty("transport",engine_.playerStatus()); - obj->setProperty("selected",playerSelected_); - obj->setProperty("current",playerCurrent_); - obj->setProperty("autoNext",playerAutoNext_); - obj->setProperty("loopAB",playerLoopCurrent_); - obj->setProperty("activeSetlist",playerActiveSet_); - obj->setProperty("pending",playerPendingIndex_); - obj->setProperty("queueRevision",playerQueueEpoch_.revision()); - obj->setProperty("crossfadeMs",playerFadeMilliseconds_); - obj->setProperty("canUndoRemove", - armix::player::PlayerSetlistArchive::canUndoRemove( - playerActiveSet_,playerUndoRemove_.set, - playerUndoRemove_.index,playerLibrary_.size(), - playerTrackSettings_.size())); - obj->setProperty("libraryBusy",playerFolderBusy_); - obj->setProperty("error",playerError_); - obj->setProperty("chooseOutput", - playerError_.containsIgnoreCase("Choose a verified MAIN output") || - playerError_.containsIgnoreCase("native mixer is preparing")); - if(includeLibrary) { - juce::Array sets; - for(std::size_t i=0;i(); - row->setProperty("id",static_cast(i)); - row->setProperty("name",playerSets_[i].name); - row->setProperty("count",static_cast( - static_cast(i)==playerActiveSet_? - playerLibrary_.size():playerSets_[i].files.size())); - sets.add(juce::var(row.release())); - } - obj->setProperty("setlists",juce::var(sets)); - juce::Array queue; - for(std::size_t i=0;i(); - item->setProperty("id",static_cast(i)); - item->setProperty("title", - playerQueue_[i].getFileNameWithoutExtension()); - queue.add(juce::var(item.release())); - } - obj->setProperty("queue",juce::var(queue)); - if(includeTracks) { - juce::Array rows; - for(std::size_t i=0;i(); - song->setProperty("id",static_cast(i)); - song->setProperty("title", - playerLibrary_[i].getFileNameWithoutExtension()); - song->setProperty("missing",!playerLibrary_[i].existsAsFile()); - song->setProperty("keySemitones",playerTrackSettings_[i].key); - song->setProperty("tempoPercent",playerTrackSettings_[i].tempo); - song->setProperty("cueIn",playerTrackSettings_[i].cueIn); - song->setProperty("cueOut",playerTrackSettings_[i].cueOut); - rows.add(juce::var(song.release())); - } - obj->setProperty("tracks",juce::var(rows)); - } + using Projection=armix::player::PlayerStateProjection; + const auto snapshot=Projection::build({ + playerLibrary_,playerTrackSettings_,playerSets_,playerQueue_, + engine_.playerStatus(),playerError_, + playerSelected_,playerCurrent_,playerActiveSet_,playerPendingIndex_, + playerQueueEpoch_.revision(),playerFadeMilliseconds_, + playerUndoRemove_.set,playerUndoRemove_.index, + playerAutoNext_,playerLoopCurrent_,playerFolderBusy_ + },includeLibrary,includeTracks); + if(!snapshot.isObject()) { + playerError_="Player library state is inconsistent; no snapshot published"; + return; } - browser_.emitEventIfBrowserIsVisible("arMixPlayerState", - juce::var(obj.release())); + browser_.emitEventIfBrowserIsVisible("arMixPlayerState",snapshot); } void choosePlayerFiles() { if(playerFileChooser_)return; // one native dialog only diff --git a/src/PlayerStateProjection.h b/src/PlayerStateProjection.h new file mode 100644 index 000000000..b0ea8e5ef --- /dev/null +++ b/src/PlayerStateProjection.h @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "PlayerSetlistArchive.h" +#include +#include +#include + +// N-MOD-18: one read-only Player projection, CONTROL/UI thread only. +// Not an accepted PCM/deck model, transport, or another persistence owner. +// The one ConsoleWindow emits the returned v1 event to the approved GUI. +namespace armix::player { +class PlayerStateProjection final { +public: + struct Source { + const std::vector& files; + const std::vector& controls; + const std::vector& sets; + const std::vector& queue; + juce::var transport; + juce::String error; + int selected=-1; + int current=-1; + int active=0; + int pending=-1; + int queueRevision=0; + int crossfadeMs=180; + int undoSet=-1; + int undoIndex=-1; + bool autoNext=false; + bool loopAB=false; + bool libraryBusy=false; + }; + static juce::var build(const Source& s,bool includeLibrary, + bool includeTracks) { + // Refuse to project a corrupt song/control pair as an accepted + // snapshot. The durable repository rejects it for the same reason. + if(s.files.size()!=s.controls.size())return {}; + auto obj=std::make_unique(); + obj->setProperty("schema","arsonmix.player.v1"); + obj->setProperty("transport",s.transport); + obj->setProperty("selected",s.selected); + obj->setProperty("current",s.current); + obj->setProperty("autoNext",s.autoNext); + obj->setProperty("loopAB",s.loopAB); + obj->setProperty("activeSetlist",s.active); + obj->setProperty("pending",s.pending); + obj->setProperty("queueRevision",s.queueRevision); + obj->setProperty("crossfadeMs",s.crossfadeMs); + obj->setProperty("canUndoRemove", + PlayerSetlistArchive::canUndoRemove( + s.active,s.undoSet,s.undoIndex,s.files.size(),s.controls.size())); + obj->setProperty("libraryBusy",s.libraryBusy); + obj->setProperty("error",s.error); + obj->setProperty("chooseOutput", + s.error.containsIgnoreCase("Choose a verified MAIN output") || + s.error.containsIgnoreCase("native mixer is preparing")); + if(includeLibrary) { + juce::Array sets; + for(std::size_t i=0;i(); + item->setProperty("id",static_cast(i)); + item->setProperty("name",s.sets[i].name); + item->setProperty("count",static_cast( + static_cast(i)==s.active?s.files.size(): + s.sets[i].files.size())); + sets.add(juce::var(item.release())); + } + obj->setProperty("setlists",juce::var(sets)); + juce::Array queue; + for(std::size_t i=0;i(); + item->setProperty("id",static_cast(i)); + item->setProperty("title",s.queue[i].getFileNameWithoutExtension()); + queue.add(juce::var(item.release())); + } + obj->setProperty("queue",juce::var(queue)); + if(includeTracks) { + juce::Array rows; + for(std::size_t i=0;i(); + item->setProperty("id",static_cast(i)); + item->setProperty("title", + s.files[i].getFileNameWithoutExtension()); + item->setProperty("missing",!s.files[i].existsAsFile()); + item->setProperty("keySemitones",s.controls[i].key); + item->setProperty("tempoPercent",s.controls[i].tempo); + item->setProperty("cueIn",s.controls[i].cueIn); + item->setProperty("cueOut",s.controls[i].cueOut); + rows.add(juce::var(item.release())); + } + obj->setProperty("tracks",juce::var(rows)); + } + } + return juce::var(obj.release()); + } +}; +} // namespace armix::player diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 4ae3a5e18..6d66c3955 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -148,6 +148,14 @@ assert.match(main, /PlayerLibraryEditPlan::manualRelink/); assert.match(main, /PlayerLibraryEditPlan::move/); assert.match(main, /PlayerLibraryEditPlan::remove/); assert.match(main, /PlayerLibraryEditPlan::undo/); +const playerProjection=read('src/PlayerStateProjection.h'); +assert.match(playerProjection, /class PlayerStateProjection final/); +assert.match(playerProjection, /queueRevision/); +assert.match(playerProjection, /canUndoRemove/); +assert.match(main, /PlayerStateProjection/); +const playerProjectionHost=main.slice(main.indexOf('void emitPlayerState('), + main.indexOf('void choosePlayerFiles()')); +assert.doesNotMatch(playerProjectionHost, /setProperty\\(/); assert.match(main, /Edit::replaceActiveTracks/); assert.match(playerArchive, /static bool canUndoRemove/); assert.match(main, /PlayerSetlistArchive::canUndoRemove/); diff --git a/tests/player_setlist_archive_test.cpp b/tests/player_setlist_archive_test.cpp index 689c084a8..b6a81af6c 100644 --- a/tests/player_setlist_archive_test.cpp +++ b/tests/player_setlist_archive_test.cpp @@ -9,6 +9,7 @@ #include "../src/PlayerSetlistRepository.h" #include "../src/PlayerSetlistEditTransaction.h" #include "../src/PlayerLibraryEditPlan.h" +#include "../src/PlayerStateProjection.h" #include "../engine/player/PlayerLiveMetadataCommitPolicy.h" using Archive=armix::player::PlayerSetlistArchive; @@ -387,7 +388,6 @@ int main() { verifyMeta(true,true,false,true,Meta::Outcome::saveRejectedRecovered,"ASR"); verifyMeta(true,true,false,false, Meta::Outcome::saveRejectedRollbackFailed,"ASR"); - assert(sandbox.deleteRecursively()); // N-MOD-18: real JUCE File plan with in-memory candidate immutability. using LibraryPlan=armix::player::PlayerLibraryEditPlan; @@ -454,7 +454,43 @@ int main() { {missing},{missing},{Track{}},foundMusic, {{0,songB}},0); assert(noLiveRelink && noLiveRelink->relinked==0); + // One native Player v1 projection: queue revision, metadata, undo + // admission and optional fields are inspectable without ConsoleWindow. + using Project=armix::player::PlayerStateProjection; + const auto projection=Project::build({ + imported->files,pairControls,doc->sets,imported->files, + juce::var(new juce::DynamicObject()),"Choose a verified MAIN output", + 1,0,0,-1,23,500,0,0,true,false,false + },true,true); + assert(projection.isObject()); + assert(projection.getProperty("schema","")=="arsonmix.player.v1"); + assert(static_cast(projection.getProperty("queueRevision",-1))==23); + assert(static_cast(projection.getProperty("crossfadeMs",-1))==500); + assert(static_cast(projection.getProperty("chooseOutput",false))); + assert(static_cast(projection.getProperty("canUndoRemove",false))); + assert(projection.getProperty("setlists",juce::var{}).isArray()); + const auto displayed=projection.getProperty("tracks",juce::var{}); + assert(displayed.isArray() && displayed.getArray()->size()==2); + assert(static_cast((*displayed.getArray())[0].getProperty( + "keySemitones",-1))==4); + assert(static_cast((*displayed.getArray())[1].getProperty( + "tempoPercent",-1))==115); + const auto lean=Project::build({ + imported->files,pairControls,doc->sets,imported->files, + juce::var(new juce::DynamicObject()),"",1,0,0,-1, + 24,180,-1,-1,false,false,false + },false,true); + assert(lean.isObject()); + assert(lean.getProperty("setlists",juce::var{}).isVoid()); + assert(lean.getProperty("tracks",juce::var{}).isVoid()); + assert(lean.getProperty("queue",juce::var{}).isVoid()); + assert(!Project::build({ + imported->files,std::vector{},doc->sets,imported->files, + juce::var(new juce::DynamicObject()),"",0,0,0,-1, + 24,180,-1,-1,false,false,false + },true,true).isObject()); assert(physical.deleteRecursively()); + assert(sandbox.deleteRecursively()); // Legacy empty v3 content migrates to a non-destructive default setlist. const auto empty=Archive::parse(juce::JSON::parse("{\"version\":3}")); From 258ea2bb2da95f23597694b121f9a378106da517 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 19 Nov 2026 11:14:50 +0700 Subject: [PATCH 24/24] test(native N-MOD-18): fix Player projection source-contract regex --- tests/native_caption_wire_geometry_contract.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index 6d66c3955..661b548dd 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -155,7 +155,7 @@ assert.match(playerProjection, /canUndoRemove/); assert.match(main, /PlayerStateProjection/); const playerProjectionHost=main.slice(main.indexOf('void emitPlayerState('), main.indexOf('void choosePlayerFiles()')); -assert.doesNotMatch(playerProjectionHost, /setProperty\\(/); +assert.doesNotMatch(playerProjectionHost, /setProperty/); assert.match(main, /Edit::replaceActiveTracks/); assert.match(playerArchive, /static bool canUndoRemove/); assert.match(main, /PlayerSetlistArchive::canUndoRemove/);