diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a6982611..7010feee1 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/engine/player/PlayerCueEditPolicy.h b/engine/player/PlayerCueEditPolicy.h new file mode 100644 index 000000000..95d7a6cc6 --- /dev/null +++ b/engine/player/PlayerCueEditPolicy.h @@ -0,0 +1,47 @@ +// 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 { + // 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; + return candidate; + } +}; +} // namespace armix::player 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 73d9369f3..2acda0e6a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -45,6 +45,11 @@ #include "NativeChannelAppearanceStore.h" #include "NativeMixerSessionSaveWorker.h" #include "NativeLogicalMixerControl.h" +#include "PlayerSetlistArchive.h" +#include "PlayerSetlistRepository.h" +#include "PlayerSetlistEditTransaction.h" +#include "PlayerLibraryEditPlan.h" +#include "PlayerStateProjection.h" #include "NativeHotkeyRegistry.h" #include "NativeHotkeyCommandPlan.h" #include "NativeFxParameterHotkey.h" @@ -55,6 +60,8 @@ #include "../engine/device/WindowsFirstRunEndpointDiscovery.h" #endif #include +#include +#include #include #include #include @@ -65,6 +72,8 @@ #include "../engine/player/PlayerSetlistPolicy.h" #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 @@ -542,16 +551,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 @@ -3886,15 +3888,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; @@ -3912,125 +3905,69 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr playerOutputPendingIndex_=-1; playerUndoRemove_={}; } + // 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; } - 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)) { + if(!result.document) { 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; + auto& parsed=*result.document; + playerSets_=std::move(parsed.sets); + activatePlayerSet(parsed.active); + playerAutoNext_=parsed.autoNext; + playerFadeMilliseconds_=parsed.fadeMs; + } + 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, + nextAutoNext,nextFadeMs); + if(!outcome.committed()) { + playerError_=outcome.error; + return false; + } + // 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; } - 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 target=settingsDirectory().getChildFile("player-library.json"); - juce::TemporaryFile staging(target); - if(!staging.getFile().replaceWithText( - juce::JSON::toString(juce::var(document.release()),false)) || - !staging.overwriteTargetFileWithTemporary()) - playerError_="Unable to save setlists; check folder permissions"; + 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(); @@ -4041,56 +3978,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 int next=static_cast(playerSets_.size())+1; - playerSets_.push_back({"Setlist "+juce::String(next),{},{}}); + 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; + } + playerSets_=std::move(outcome.sets); + if(!rename) { 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; - } - } - 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; + activatePlayerSet(outcome.active); } - playerSets_[static_cast(playerActiveSet_)].name=name; - playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + playerError_.clear(); + emitPlayerState(true); return; } if(action=="playerMoveSong") { @@ -4098,12 +4017,13 @@ 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)); - }; - move(playerLibrary_);move(playerTrackSettings_); + 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) { return armix::player::PlayerShowEditPolicy::afterMove( index,from,to,count); @@ -4111,7 +4031,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") { @@ -4127,17 +4047,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 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}; 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); @@ -4148,19 +4073,31 @@ 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") { 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, - static_cast(playerLibrary_.size())); - playerLibrary_.insert(playerLibrary_.begin()+index,removed.file); - playerTrackSettings_.insert( - playerTrackSettings_.begin()+index,removed.controls); + 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( playerCurrent_,index); playerSelected_=armix::player::PlayerShowEditPolicy::afterInsert( @@ -4168,7 +4105,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") { @@ -4231,65 +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", - playerUndoRemove_.set==playerActiveSet_ && - playerUndoRemove_.index>=0); - 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 @@ -4304,31 +4196,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(); - std::size_t first=static_cast(-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()) { - if(first==static_cast(-1)) - first=static_cast( - found-safe->playerLibrary_.begin()); - 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(safe->playerLibrary_.size()>=2000)break; - if(first==static_cast(-1)) - first=safe->playerLibrary_.size(); - safe->playerLibrary_.push_back(file); - safe->playerTrackSettings_.push_back({}); + safe->emitPlayerState(true); } - 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] { if(safe)safe->playerFileChooser_.reset(); @@ -4372,35 +4255,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr relinks=std::move(relinks),initialLibrary]() mutable { if(!safe)return; safe->playerFolderBusy_=false; - int added=0,relinked=0; - // Update only the exact rows the worker saw. - // Edits made during the scan must remain intact. - for(const auto& change:relinks) { - if(change.index>=initialLibrary.size() || - change.index>=safe->playerLibrary_.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()) - continue; - safe->playerLibrary_[change.index]=change.replacement; - ++relinked; // keep stable IDs + KEY/TEMPO + 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; } - 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({}); - ++added; + const int added=plan->added,relinked=plan->relinked; + const int first=plan->first; + if(!safe->commitPlayerTrackEdit( + std::move(plan->files),std::move(plan->controls))) { + safe->emitPlayerState(true);return; } if(safe->playerSelected_<0 && first>=0) safe->playerSelected_=first; @@ -4409,7 +4276,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(); @@ -4439,28 +4305,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. + 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->playerLibrary_[static_cast(index)]=chosen; safe->playerOutputPendingIndex_=-1; safe->playerError_.clear(); - safe->persistPlayerLibrary(); } safe->emitPlayerState(true); }); @@ -4637,17 +4503,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); @@ -4681,7 +4555,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( @@ -4694,33 +4568,49 @@ 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; + } + // 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; } + 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") { @@ -4753,14 +4643,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_[ @@ -4769,7 +4664,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/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/src/PlayerSetlistArchive.h b/src/PlayerSetlistArchive.h new file mode 100644 index 000000000..9b69608e2 --- /dev/null +++ b/src/PlayerSetlistArchive.h @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "../engine/player/PlayerCueEditPolicy.h" +#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; + // 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()) || + (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") || + !knownPaths.insert(source).second)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(PlayerCueEditPolicy::validArchive({cueIn,cueOut})) { + settings.cueIn=cueIn; + settings.cueOut=cueOut; + } + } + destination.files.push_back(source); + destination.controls.push_back(settings); + } + } +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. + // 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) { + 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)); + 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(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;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(!uniquePaths.insert(s.files[i]).second) + return {}; + const auto& settings=s.controls[i]; + if(settings.key< -6||settings.key>6|| + settings.tempo<80||settings.tempo>120|| + !PlayerCueEditPolicy::validArchive( + {settings.cueIn,settings.cueOut})) + 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/src/PlayerSetlistEditTransaction.h b/src/PlayerSetlistEditTransaction.h new file mode 100644 index 000000000..a158387ce --- /dev/null +++ b/src/PlayerSetlistEditTransaction.h @@ -0,0 +1,121 @@ +// 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; + } + } + + 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) + return reject(stored,"Unable to save setlists; check folder permissions"); + return {SaveStatus::saved,{},std::move(candidate),active}; + } + static Result reject(SaveStatus status,juce::String error) { + return {status,std::move(error),{},-1}; + } +}; +} // namespace armix::player 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/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 c0c985b41..661b548dd 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -128,7 +128,66 @@ 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(playerArchive, /nextGeneratedName/); +const playerEditTransaction=read('src/PlayerSetlistEditTransaction.h'); +assert.match(playerEditTransaction, /PlayerSetlistArchive::nextGeneratedName/); +assert.match(playerEditTransaction, /PlayerSetlistRepository::save/); +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/); +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/); +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.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, + /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/); +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('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 new file mode 100644 index 000000000..b6a81af6c --- /dev/null +++ b/tests/player_setlist_archive_test.cpp @@ -0,0 +1,504 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +#include "../src/PlayerSetlistArchive.h" +#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; +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()); + + // 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()); + // 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()); + 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()); + + // 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.)); + // 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; + 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",{},{}}, + {"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 3"; // case-folded name remains occupied + assert(Archive::nextGeneratedName(names)=="Setlist 4"); + + // 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)); + assert(!Archive::canUndoRemove(0,1,1999,1999,1999)); + 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(); + } + 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); + 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()); + + // 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); + // 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); + // 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); + // 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"); + + // 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); + // 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}")); + 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; +}