diff --git a/.github/workflows/player-native-deck-windows.yml b/.github/workflows/player-native-deck-windows.yml new file mode 100644 index 000000000..21b6e87dd --- /dev/null +++ b/.github/workflows/player-native-deck-windows.yml @@ -0,0 +1,73 @@ +name: ArSon Player native dual-deck (focused Windows JUCE) +# Windows source verification only when native player decoder/deck changes. +# Never runs installer, full CTest, Harmony DSP, or hardware-dependent FAT. +on: + pull_request: + types: [opened, reopened, synchronize] + paths: + - 'engine/player/NativePlayerDeck.h' + - 'engine/player/NativePlayerShowDeck.h' + - 'tests/player_native_decode_test.cpp' + - '.github/workflows/player-native-deck-windows.yml' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: player-deck-windows-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + native-deck: + name: Real WAV/JUCE seek, loop, STOP and single-PCM dual deck (MSVC) + runs-on: windows-2022 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - name: Verify exact source SHA + shell: pwsh + env: + EXPECTED_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + $actual = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $actual -ne $env:EXPECTED_SHA) { + throw "PLAYER_DECK_SOURCE_SHA_MISMATCH expected=$env:EXPECTED_SHA actual=$actual" + } + Write-Host "PLAYER_DECK_SOURCE_SHA=$actual" + - name: Checkout pinned JUCE 8 + uses: actions/checkout@v4 + with: + repository: juce-framework/JUCE + ref: 8.0.15 + path: third_party/JUCE + - name: Install WebView2 SDK required by common CMake configure + shell: pwsh + run: | + nuget install Microsoft.Web.WebView2 -Version 1.0.3485.44 -OutputDirectory .deps -NonInteractive + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Configure CMake, assertions enabled by source test + shell: pwsh + run: | + cmake -S . -B build -G "Visual Studio 17 2022" -A x64 ` + -DJUCE_ROOT="${{ github.workspace }}/third_party/JUCE" ` + -DBUILD_TESTING=ON ` + -DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $catalogText = & ctest --test-dir build -C Release --show-only=json-v1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $catalog = ($catalogText | Out-String | ConvertFrom-Json) + if ('ArSonPlayerRealWavDecodeResampleAndTransport' -notin @($catalog.tests | ForEach-Object { $_.name })) { + throw 'PLAYER_DECK_CTEST_MISSING' + } + - name: Compile ONLY real native player decoder test target + shell: pwsh + run: | + cmake --build build --config Release --parallel 2 --target ARMixPlayerDecodeTests + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Run ONLY real WAV player/loop/seek/crossfade regression + shell: pwsh + run: | + ctest --test-dir build -C Release --output-on-failure ` + -R '^ArSonPlayerRealWavDecodeResampleAndTransport$' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Write-Host 'PLAYER_DECK_REAL_JUCE_WAV_CTEST=PASS (physical ASIO NOT qualified)' diff --git a/.github/workflows/player-show-fast.yml b/.github/workflows/player-show-fast.yml new file mode 100644 index 000000000..79646ab55 --- /dev/null +++ b/.github/workflows/player-show-fast.yml @@ -0,0 +1,52 @@ +name: ArSon Player Show M1-M3 (fast source contracts) +on: + pull_request: + paths: + - 'engine/player/**' + - 'src/Main.cpp' + - 'src/LiveAudioEngine.h' + - 'site/preview-v2/assets/arson-player.js' + - 'site/preview-v2/assets/mixer-contextual-buttons.js' + - 'site/preview-v2/assets/mixer-contextual-buttons.css' + - 'tests/player_show_edit_policy_test.cpp' + - 'tests/player_waveform_index_test.cpp' + - 'tests/player_crossfade_curve_test.cpp' + - 'tests/player_show_transition_policy_test.cpp' + - 'tests/player_transport_lifecycle_contract.test.mjs' + - '.github/workflows/player-show-fast.yml' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: player-show-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + portable: + name: M1-M2 edit+waveform native C++ and player JS parse + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - name: Run pure C++20 show policy and progressive waveform tests + run: | + g++ -std=c++20 -O2 -Wall -Wextra -Werror -pthread \ + tests/player_show_edit_policy_test.cpp \ + -o "$RUNNER_TEMP/player-show-edit-test" + "$RUNNER_TEMP/player-show-edit-test" + g++ -std=c++20 -O2 -Wall -Wextra -Werror -pthread \ + tests/player_waveform_index_test.cpp \ + -o "$RUNNER_TEMP/player-waveform-test" + "$RUNNER_TEMP/player-waveform-test" + g++ -std=c++20 -O2 -Wall -Wextra -Werror \ + tests/player_crossfade_curve_test.cpp \ + -o "$RUNNER_TEMP/player-crossfade-test" + "$RUNNER_TEMP/player-crossfade-test" + g++ -std=c++20 -O2 -Wall -Wextra -Werror \ + tests/player_show_transition_policy_test.cpp \ + -o "$RUNNER_TEMP/player-transition-test" + "$RUNNER_TEMP/player-transition-test" + - name: Parse the actual approved player UI and dynamic assembly + run: | + node --check site/preview-v2/assets/arson-player.js + node --check site/preview-v2/assets/mixer-contextual-buttons.js + node tests/player_transport_lifecycle_contract.test.mjs diff --git a/CMakeLists.txt b/CMakeLists.txt index e2f1cb58d..601c93473 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -344,6 +344,29 @@ if(BUILD_TESTING) target_link_libraries(ARMixPlayerPcmRingTests PRIVATE Threads::Threads) add_test(NAME ArSonPlayerWorkerToRealtimeStereoRing COMMAND ARMixPlayerPcmRingTests) add_dependencies(ARMixMixerRoutingTests ARMixPlayerPcmRingTests) + # M1/M2 portable show editor + progressive wave index: actual native + # executables, no mock browser or hardware runner needed. + add_executable(ARMixPlayerShowEditTests tests/player_show_edit_policy_test.cpp) + target_compile_features(ARMixPlayerShowEditTests PRIVATE cxx_std_20) + add_test(NAME ArSonPlayerM1StableSetlistCurrentAndQueueIndexes + COMMAND ARMixPlayerShowEditTests) + add_executable(ARMixPlayerWaveformTests tests/player_waveform_index_test.cpp) + target_compile_features(ARMixPlayerWaveformTests PRIVATE cxx_std_20) + target_link_libraries(ARMixPlayerWaveformTests PRIVATE Threads::Threads) + add_test(NAME ArSonPlayerM2ProgressiveRealtimeSafeWaveform + COMMAND ARMixPlayerWaveformTests) + add_executable(ARMixPlayerCrossfadeTests tests/player_crossfade_curve_test.cpp) + target_compile_features(ARMixPlayerCrossfadeTests PRIVATE cxx_std_20) + add_test(NAME ArSonPlayerM3FiniteEqualPowerCrossfade + COMMAND ARMixPlayerCrossfadeTests) + add_executable(ARMixPlayerShowTransitionTests + tests/player_show_transition_policy_test.cpp) + target_compile_features(ARMixPlayerShowTransitionTests PRIVATE cxx_std_20) + add_test(NAME ArSonPlayerM3TransactionalQueueAndAutoNextDeadline + COMMAND ARMixPlayerShowTransitionTests) + add_dependencies(ARMixMixerRoutingTests + ARMixPlayerShowEditTests ARMixPlayerWaveformTests + ARMixPlayerCrossfadeTests ARMixPlayerShowTransitionTests) 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/NativePlayerDeck.h b/engine/player/NativePlayerDeck.h index ea2c796b6..3270a8b97 100644 --- a/engine/player/NativePlayerDeck.h +++ b/engine/player/NativePlayerDeck.h @@ -2,6 +2,7 @@ #pragma once #include "PreparedStereoPcmRing.h" #include "PlayerPitchTempoProcessor.h" +#include "PlayerWaveformIndex.h" #include "../core/RealtimeSlew64.h" #include #include @@ -26,12 +27,14 @@ class NativePlayerDeck final { struct Status { State state=State::empty; std::uint64_t played=0,duration=0,underruns=0,generation=0; + std::uint64_t mediaPlayed=0,mediaDuration=0; bool outputReady=false; juce::String title,error; double deviceRate=0; int keySemitones=0,tempoPercent=100; int requestedKey=0,requestedTempo=100; bool processingChangePending=false; + std::array waveform{}; }; NativePlayerDeck() { // 2.7 seconds at 48k, bounded independent of song length. @@ -58,6 +61,10 @@ class NativePlayerDeck final { rate_.store(rounded>0?rounded:0,std::memory_order_release); const bool selected=hasFile_.load(std::memory_order_acquire); played_.store(0,std::memory_order_release); + mediaPlayed_.store(0,std::memory_order_release); + mediaDuration_.store(0,std::memory_order_release); + requestedSeekSeconds_.store(cueInSeconds_.load( + std::memory_order_acquire),std::memory_order_release); error_.store(0,std::memory_order_release); generation_.fetch_add(1,std::memory_order_acq_rel); state_.store(rounded<=0?State::stopped: @@ -65,6 +72,14 @@ class NativePlayerDeck final { std::memory_order_release); wake_.notify_one(); } + bool setCueRange(double in,double out) noexcept { + if(!std::isfinite(in) || !std::isfinite(out) || + in<0. || out<0. || in>86400. || out>86400. || + (out>0. && out<=in+0.05))return false; + cueInSeconds_.store(in,std::memory_order_release); + cueOutSeconds_.store(out,std::memory_order_release); + return true; + } bool setPitchTempo(int keySemitones,int tempoPercent) noexcept { const PlayerPitchTempoProcessor::Controls c{keySemitones,tempoPercent}; if(!PlayerPitchTempoProcessor::valid(c))return false; @@ -80,11 +95,29 @@ class NativePlayerDeck final { } hasFile_.store(file!=juce::File{},std::memory_order_release); played_.store(0,std::memory_order_release); + mediaPlayed_.store(0,std::memory_order_release); + mediaDuration_.store(0,std::memory_order_release); + requestedSeekSeconds_.store(cueInSeconds_.load( + std::memory_order_acquire),std::memory_order_release); error_.store(0,std::memory_order_release); state_.store(State::loading,std::memory_order_release); generation_.fetch_add(1,std::memory_order_acq_rel); wake_.notify_one(); } + // GUI/CONTROL only. The decoder worker owns opening/repositioning the + // reader and resampler. Every seek supersedes prior queued PCM via the + // existing generation + quiescence fence; ASIO never calls seek/file IO. + bool seekSeconds(double seconds) noexcept { + if(!std::isfinite(seconds) || seconds<0. || + !hasFile_.load(std::memory_order_acquire) || + rate_.load(std::memory_order_acquire)<=0)return false; + requestedSeekSeconds_.store(seconds,std::memory_order_release); + ready_.store(false,std::memory_order_release); + state_.store(State::loading,std::memory_order_release); + generation_.fetch_add(1,std::memory_order_acq_rel); + wake_.notify_one(); + return true; + } bool isPlayingRequested() const noexcept { return ready_.load(std::memory_order_acquire) && wantedPlay_.load(std::memory_order_acquire); @@ -106,9 +139,12 @@ class NativePlayerDeck final { // the next seek-to-start; never reset/reallocate a ring from RT. ready_.store(false,std::memory_order_release); wantedPlay_.store(false,std::memory_order_release); + requestedSeekSeconds_.store(cueInSeconds_.load( + std::memory_order_acquire),std::memory_order_release); state_.store(State::stopped,std::memory_order_release); generation_.fetch_add(1,std::memory_order_acq_rel); played_.store(0,std::memory_order_relaxed); + mediaPlayed_.store(0,std::memory_order_relaxed); wake_.notify_one(); } Status snapshot() const { @@ -116,6 +152,8 @@ class NativePlayerDeck final { s.state=state_.load(std::memory_order_acquire); s.played=played_.load(std::memory_order_relaxed); s.duration=length_.load(std::memory_order_relaxed); + s.mediaPlayed=mediaPlayed_.load(std::memory_order_relaxed); + s.mediaDuration=mediaDuration_.load(std::memory_order_relaxed); s.underruns=ring_.underrunFrames(); s.generation=generation_.load(std::memory_order_acquire); s.deviceRate=rate_.load(std::memory_order_acquire); @@ -130,11 +168,13 @@ class NativePlayerDeck final { s.requestedTempo=requested.tempoPercent; s.processingChangePending=(s.keySemitones!=s.requestedKey || s.tempoPercent!=s.requestedTempo); + s.waveform=waveform_.snapshot(); switch(error_.load(std::memory_order_relaxed)) { case 1:s.error="File missing or unreadable";break; case 2:s.error="Unsupported or corrupt music format";break; case 3:s.error="Audio output not configured";break; case 4:s.error="Music pitch/tempo processing failed";break; + case 5:s.error="Song IN marker exceeds file duration";break; default:break; } {std::lock_guard lock(commandMutex_); @@ -166,11 +206,26 @@ class NativePlayerDeck final { const auto generation=generation_.load(std::memory_order_acquire); if(generation!=audioGeneration_) { audioGeneration_=generation; + mediaFraction_=0.; gain_.reset(0.f); } const auto n=ring_.read(left,right,static_cast(frames)); if(n>0) { played_.fetch_add(n,std::memory_order_relaxed); + // Original media clock is independent of DSP-stretched PCM. + // The bounded producer lookahead can make this a small estimate, + // but never treats 80% tempo as a 25%-longer source song. + const auto control=unpackControls(appliedControls_.load( + std::memory_order_relaxed)); + const double advance=static_cast(n)* + control.tempoPercent/100.0+mediaFraction_; + const auto mediaFrames=static_cast( + std::floor(advance)); + mediaFraction_=advance-mediaFrames; + const auto length=mediaDuration_.load(std::memory_order_relaxed); + const auto present=mediaPlayed_.load(std::memory_order_relaxed); + mediaPlayed_.store(std::min(length,present+mediaFrames), + std::memory_order_relaxed); state_.store(State::playing,std::memory_order_relaxed); } // A short ramp makes decoder/prebuffer start click-free. RT-owned @@ -201,6 +256,8 @@ class NativePlayerDeck final { static_cast((bits>>8)&255u)}; } void restart() noexcept { + requestedSeekSeconds_.store(cueInSeconds_.load( + std::memory_order_acquire),std::memory_order_release); ready_.store(false,std::memory_order_release); played_.store(0,std::memory_order_relaxed); state_.store(State::loading,std::memory_order_release); @@ -260,14 +317,36 @@ class NativePlayerDeck final { state_.store(State::error,std::memory_order_release); continue; } + // A saved cue may belong to an older version of a relinked + // file. Never silently clamp IN to the last audio sample and + // report a successful (almost silent) playback. + const double cueIn=cueInSeconds_.load(std::memory_order_acquire); + const double mediaSeconds=static_cast( + reader->lengthInSamples)/reader->sampleRate; + if(!std::isfinite(cueIn) || cueIn>=mediaSeconds) { + error_.store(5,std::memory_order_release); + state_.store(State::error,std::memory_order_release); + continue; + } const bool mono=reader->numChannels==1; - const double ratio=reader->sampleRate/static_cast(deviceHz); + const double sourceRate=reader->sampleRate; + const auto sourceLength=reader->lengthInSamples; + const double ratio=sourceRate/static_cast(deviceHz); const auto sourceTotal=static_cast(std::ceil( static_cast(reader->lengthInSamples)/ratio)); if(!sourceTotal) { state_.store(State::error,std::memory_order_release); continue; } + if(file!=waveformFile_) { + waveformFile_=file; // worker owns identity + waveform_.reset(sourceTotal); + } + const double positionSeconds=requestedSeekSeconds_.load( + std::memory_order_acquire); + const juce::int64 readerPosition=static_cast( + std::clamp(std::floor(positionSeconds*sourceRate),0.0, + static_cast(sourceLength-1))); using Controls=PlayerPitchTempoProcessor::Controls; Controls controls=unpackControls( requestedControls_.load(std::memory_order_acquire)); @@ -280,16 +359,34 @@ class NativePlayerDeck final { appliedControls_.store(packControls(controls), std::memory_order_release); juce::AudioFormatReaderSource source(reader.release(),true); + source.setNextReadPosition(readerPosition); // worker-only seek juce::ResamplingAudioSource resampled(&source,false,2); resampled.setResamplingRatio(ratio); resampled.prepareToPlay(1536,static_cast(deviceHz)); // Source is device-rate stereo, but independent KEY/TEMPO DSP is // computed ONLY here on the decoder worker; not in JUCE/ASIO RT. juce::AudioBuffer input(2,1536),output(2,1024); - std::uint64_t consumed=0,written=0; + std::uint64_t consumed=static_cast( + std::floor(static_cast(readerPosition)/ratio)); + const auto startPlayed=static_cast( + std::floor(consumed*100.0/controls.tempoPercent)); + std::uint64_t written=startPlayed; + played_.store(startPlayed,std::memory_order_release); + mediaPlayed_.store(consumed,std::memory_order_release); + mediaDuration_.store(sourceTotal,std::memory_order_release); + // OUT=0 means physical media end. Reader/decoder owns this + // bound; the audio callback never edits an I/O source. + const auto readEnd=[&]() -> std::uint64_t { + const double out=cueOutSeconds_.load( + std::memory_order_acquire); + if(out<=0.)return sourceTotal; + return std::min(sourceTotal,static_cast( + std::ceil(out*deviceHz))); + }; const auto estimateTotal=[&]() -> std::uint64_t { return written+static_cast(std::ceil( - (sourceTotal-consumed)*100.0/controls.tempoPercent)) + (readEnd()>consumed?readEnd()-consumed:0)* + 100.0/controls.tempoPercent)) +static_cast(pitch.outputLatency()); }; length_.store(estimateTotal(),std::memory_order_release); @@ -303,9 +400,14 @@ class NativePlayerDeck final { const auto highWater=std::min( ring_.capacityFrames()-2048, std::max(8192,static_cast(deviceHz/4))); - while(!obsolete(version) && consumedhighWater) { - std::this_thread::sleep_for(std::chrono::milliseconds(3)); + // A parked/preloaded NEXT has no callback consumer yet. + // Yield longer while standby so a singer browsing the + // setlist does not spin a 333Hz decoder polling loop; + // the 250ms PCM cushion still covers normal Play start. + std::this_thread::sleep_for(std::chrono::milliseconds( + wantedPlay_.load(std::memory_order_acquire)?3:20)); continue; } Controls requested=unpackControls( @@ -318,7 +420,7 @@ class NativePlayerDeck final { } int nOutput=1024; int nInput=pitch.nextInputFrames(nOutput); - const auto remaining=sourceTotal-consumed; + const auto remaining=readEnd()-consumed; if(remaining(nInput)) { nOutput=std::max(1,static_cast(std::ceil( remaining*100.0/controls.tempoPercent))); @@ -332,6 +434,10 @@ class NativePlayerDeck final { resampled.getNextAudioBlock({&input,0,nInput}); if(mono)input.copyFrom(1,0,input,0,0,nInput); if(obsolete(version))break; + // Construct waveform on the SAME decode pass. No second + // filesystem scan, peak generation in RT, or UI-heap work. + waveform_.observe(input.getReadPointer(0), + input.getReadPointer(1),nInput,consumed); const float* const sourcePcm[]={input.getReadPointer(0), input.getReadPointer(1)}; float* const outputPcm[]={output.getWritePointer(0), @@ -346,6 +452,7 @@ class NativePlayerDeck final { } consumed+=static_cast(nInput); written+=transferred; + mediaDuration_.store(readEnd(),std::memory_order_release); length_.store(estimateTotal(),std::memory_order_release); if(!ready_.load(std::memory_order_relaxed) && (ring_.bufferedFrames()>=4096 || consumed==sourceTotal)) { @@ -357,7 +464,7 @@ class NativePlayerDeck final { } // Drain the final spectral overlap OFF realtime. Without this, // transposed music loses its last FFT window at EOF. - if(!failed && !obsolete(version) && consumed==sourceTotal && + if(!failed && !obsolete(version) && consumed>=readEnd() && pitch.active()) { const int tail=pitch.outputLatency(); if(tail>0 && tail=readEnd()) { length_.store(written,std::memory_order_release); eof_.store(true,std::memory_order_release); ready_.store(true,std::memory_order_release); @@ -396,11 +503,16 @@ class NativePlayerDeck final { } } PreparedStereoPcmRing ring_; + PlayerWaveformIndex waveform_; + juce::File waveformFile_; // worker thread only, across seek epochs + std::atomic requestedSeekSeconds_{0.0}; + std::atomic cueInSeconds_{0.0},cueOutSeconds_{0.0}; mutable std::mutex commandMutex_; // CONTROL/worker only, NEVER RT juce::File selectedFile_; std::atomic exit_{false},ready_{false},wantedPlay_{false},eof_{false}; std::atomic hasFile_{false}; // lifecycle read: no control mutex std::atomic generation_{0},played_{0},length_{0}; + std::atomic mediaPlayed_{0},mediaDuration_{0}; std::atomic readers_{0}; std::atomic rate_{0},error_{0}; // Packed atomic makes KEY+TEMPO a single coherent command, avoiding @@ -410,6 +522,7 @@ class NativePlayerDeck final { std::atomic state_{State::empty}; armix::dsp::RealtimeSlew64 gain_; // AUDIO only std::uint64_t audioGeneration_=0; // AUDIO only, no race with file thread + double mediaFraction_=0.; // AUDIO only, fractional original-media frame std::mutex wakeMutex_; // only decoding worker std::condition_variable wake_; // never accessed by audio callback // Construct LAST: workerLoop must never observe unconstructed atomics/ diff --git a/engine/player/NativePlayerShowDeck.h b/engine/player/NativePlayerShowDeck.h new file mode 100644 index 000000000..237977d3a --- /dev/null +++ b/engine/player/NativePlayerShowDeck.h @@ -0,0 +1,242 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativePlayerDeck.h" +#include "PlayerCrossfadeCurve.h" +#include +#include +#include +#include +#include + +// Two independent decoder workers, ONE native PLAYER A PCM mixer source. +// Only this wrapper blends the two preprepared streams; neither worker owns +// audio hardware, channels, FX or the JUCE callback. Neither seek/reload nor +// disk reads happen inside pull(). The retired deck is stopped by service() +// on CONTROL, never by the realtime thread. +namespace armix::player { +class NativePlayerShowDeck final { +public: + using Status=NativePlayerDeck::Status; + using Controls=PlayerPitchTempoProcessor::Controls; + static constexpr int maxRenderFrames=8192; + NativePlayerShowDeck()=default; + NativePlayerShowDeck(const NativePlayerShowDeck&)=delete; + NativePlayerShowDeck& operator=(const NativePlayerShowDeck&)=delete; + + void deviceRate(double hz) noexcept { + // Device generations invalidate BOTH cached PCM rings. This is + // not permission to switch outputs or restart playback. + fading_.store(false,std::memory_order_release); + retired_.store(-1,std::memory_order_release); + rateHz_.store(static_cast(std::lround(hz)), + std::memory_order_release); + deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); + pending_.store(false,std::memory_order_release); + failed_.store(false,std::memory_order_release); + for(auto& deck:decks_)deck.deviceRate(hz); + } + void load(const juce::File& file,bool autoPlay=true) { + // Explicit new-song load for idle transport, not live NEXT: + // live transitions always go through queueTransition(). + fading_.store(false,std::memory_order_release); + pending_.store(false,std::memory_order_release); + failed_.store(false,std::memory_order_release); + preloadedFile_={}; + const int index=active_.load(std::memory_order_acquire); + decks_[static_cast(1-index)].stop(); + decks_[static_cast(index)].load(file,autoPlay); + retired_.store(-1,std::memory_order_release); + } + bool setCueRange(double in,double out) noexcept { + return decks_[static_cast( + active_.load(std::memory_order_acquire))] + .setCueRange(in,out); + } + bool setPitchTempo(int key,int tempo) noexcept { + return decks_[static_cast( + active_.load(std::memory_order_acquire))] + .setPitchTempo(key,tempo); + } + bool seekSeconds(double seconds) noexcept { + if(fading_.load(std::memory_order_acquire) || + pending_.load(std::memory_order_acquire))return false; + return decks_[static_cast( + active_.load(std::memory_order_acquire))].seekSeconds(seconds); + } + bool isPlayingRequested() const noexcept { + if(fading_.load(std::memory_order_acquire))return true; + return decks_[static_cast( + active_.load(std::memory_order_acquire))].isPlayingRequested(); + } + void play() noexcept { + decks_[static_cast( + active_.load(std::memory_order_acquire))].play(); + } + void pause() noexcept { + pending_.store(false,std::memory_order_release); + failed_.store(false,std::memory_order_release); + for(auto& deck:decks_)deck.pause(); + } + void stop() noexcept { + // STOP supersedes all queued transitions and no stale PCM may play + // after an output/device restart. + pending_.store(false,std::memory_order_release); + preloadedFile_={}; + failed_.store(false,std::memory_order_release); + fading_.store(false,std::memory_order_release); + for(auto& deck:decks_)deck.stop(); + } + Status snapshot() const { + return decks_[static_cast( + active_.load(std::memory_order_acquire))].snapshot(); + } + bool transitionPending() const noexcept { + return pending_.load(std::memory_order_acquire); + } + bool transitionFailed() const noexcept { + return failed_.load(std::memory_order_acquire); + } + bool transitionActive() const noexcept { + return fading_.load(std::memory_order_acquire); + } + bool preload(const juce::File& file,int key,int tempo, + double cueIn=0.,double cueOut=0.) { + if(file==juce::File{} || !file.existsAsFile() || + !PlayerPitchTempoProcessor::valid({key,tempo}) || + !std::isfinite(cueIn) || !std::isfinite(cueOut) || + cueIn<0. || cueOut<0. || cueIn>86400. || cueOut>86400. || + (cueOut>0. && cueOut<=cueIn+0.05) || + rateHz_.load(std::memory_order_acquire)<=0 || + fading_.load(std::memory_order_acquire))return false; + // A previous fade may have ended BETWEEN control ticks. Reclaim + // the old decoder before reusing it for NEXT: otherwise service() + // can later STOP a freshly preloaded standby and strand the queue. + retireCompleted(); + const int inactive=1-active_.load(std::memory_order_acquire); + const auto epoch=deviceEpoch_.load(std::memory_order_acquire); + if(preloadedFile_==file && preloadedEpoch_==epoch && + preloadedControls_==Controls{key,tempo} && + preloadedIn_==cueIn && preloadedOut_==cueOut && + decks_[static_cast(inactive)].snapshot().state + !=NativePlayerDeck::State::error)return true; + // Reuse a bounded standby decoder and SPSC FIFO. Repeated NEXT + // changes supersede old read work through NativePlayerDeck generation. + auto& standby=decks_[static_cast(inactive)]; + if(!standby.setPitchTempo(key,tempo) || + !standby.setCueRange(cueIn,cueOut))return false; + preloadedFile_=file;preloadedControls_={key,tempo}; + preloadedIn_=cueIn;preloadedOut_=cueOut; + preloadedEpoch_=epoch; + standby.load(file,false); + return true; + } + bool queueTransition(const juce::File& file,int key,int tempo, + int fadeMilliseconds=180, + double cueIn=0.,double cueOut=0.) { + if(fading_.load(std::memory_order_acquire))return false; + if(!preload(file,key,tempo,cueIn,cueOut))return false; + fadeMilliseconds_=std::clamp(fadeMilliseconds,0,3000); + failed_.store(false,std::memory_order_release); + // The caller's CONTROL timer owns the one authoritative ACK for + // beginning the fade. Never start it here before Main.cpp records + // which logical setlist row is becoming CURRENT. + pending_.store(true,std::memory_order_release); + return true; + } + // CONTROL/TIMER only. Returns true only when a NEW crossfade is + // atomically armed after genuine standby PCM is buffered. + bool service() { + retireCompleted(); + if(!pending_.load(std::memory_order_acquire) || + fading_.load(std::memory_order_acquire))return false; + const int from=active_.load(std::memory_order_acquire); + const int to=1-from; + const auto epoch=deviceEpoch_.load(std::memory_order_acquire); + const auto standby=decks_[static_cast(to)].snapshot(); + if(epoch!=preloadedEpoch_ || + !pending_.load(std::memory_order_acquire) || + rateHz_.load(std::memory_order_acquire)<=0)return false; + if(standby.state==NativePlayerDeck::State::error) { + pending_.store(false,std::memory_order_release); + failed_.store(true,std::memory_order_release); + preloadedFile_={}; + return false; + } + if(!standby.outputReady)return false; + // All transport control remains outside the realtime callback. + decks_[static_cast(to)].play(); + fadeFrom_.store(from,std::memory_order_relaxed); + fadeTo_.store(to,std::memory_order_relaxed); + fadePosition_.store(0,std::memory_order_relaxed); + fadeFrames_.store(std::max(1,static_cast( + std::lround(rateHz_.load(std::memory_order_acquire)* + fadeMilliseconds_/1000.))), + std::memory_order_relaxed); + fading_.store(true,std::memory_order_release); + active_.store(to,std::memory_order_release); + pending_.store(false,std::memory_order_release); + preloadedFile_={}; + return true; + } + void pull(float* left,float* right,int frames) noexcept { + if(!left||!right||left==right||frames<=0)return; + if(frames>maxRenderFrames) { + std::fill_n(left,frames,0.f);std::fill_n(right,frames,0.f); + return; + } + if(!fading_.load(std::memory_order_acquire)) { + decks_[static_cast( + active_.load(std::memory_order_acquire))] + .pull(left,right,frames); + return; + } + const int from=fadeFrom_.load(std::memory_order_relaxed); + const int to=fadeTo_.load(std::memory_order_relaxed); + decks_[static_cast(to)].pull(left,right,frames); + decks_[static_cast(from)].pull( + scratch_[0].data(),scratch_[1].data(),frames); + const int total=fadeFrames_.load(std::memory_order_relaxed); + const int start=fadePosition_.load(std::memory_order_relaxed); + for(int i=0;i(i)]*gains.oldGain + +left[i]*gains.newGain; + right[i]=scratch_[1][static_cast(i)]*gains.oldGain + +right[i]*gains.newGain; + } + const int advanced=start+frames; + if(advanced>=total) { + fadePosition_.store(total,std::memory_order_relaxed); + // Publish retirement BEFORE releasing the active fade flag; + // control cannot begin another transition while an old deck + // is still being used in a previous hardware callback. + retired_.store(from,std::memory_order_release); + fading_.store(false,std::memory_order_release); + } else fadePosition_.store(advanced,std::memory_order_relaxed); + } +private: + // CONTROL ONLY. The callback finishes all old-deck reads BEFORE it + // publishes retired_; it never blocks on this reset. Calling this at + // both the start of service() and preload() prevents stale retirement + // from invalidating newly prepared PCM during rapid song changes. + void retireCompleted() { + const int old=retired_.exchange(-1,std::memory_order_acq_rel); + if(old>=0)decks_[static_cast(old)].stop(); + } + std::array decks_; + std::array,2> scratch_{}; + const PlayerCrossfadeCurve fadeCurve_{}; + std::atomic active_{0},fadeFrom_{0},fadeTo_{1}; + std::atomic fadePosition_{0},fadeFrames_{1},retired_{-1}; + std::atomic fading_{false}; + // CONTROL-only, not borrowed by the realtime callback. + juce::File preloadedFile_; + Controls preloadedControls_{}; + double preloadedIn_=0.,preloadedOut_=0.; + std::atomic rateHz_{0}; + std::atomic deviceEpoch_{0}; + std::uint64_t preloadedEpoch_=0; // CONTROL only + int fadeMilliseconds_=180; + std::atomic pending_{false},failed_{false}; +}; +} // namespace armix::player diff --git a/engine/player/PlayerCrossfadeCurve.h b/engine/player/PlayerCrossfadeCurve.h new file mode 100644 index 000000000..e7c9c255b --- /dev/null +++ b/engine/player/PlayerCrossfadeCurve.h @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// Immutable equal-power transition table. Filled exactly once on CONTROL; +// audio callback does bounded integer indexing, no trig, heap or locks. +namespace armix::player { +class PlayerCrossfadeCurve final { +public: + static constexpr int resolution=1024; + struct Gains {float oldGain=1.f,newGain=0.f;}; + PlayerCrossfadeCurve() noexcept { + constexpr double pi=3.14159265358979323846; + for(int i=0;i<=resolution;++i) { + const double t=(pi/2)*i/resolution; + old_[static_cast(i)]= + static_cast(std::cos(t)); + next_[static_cast(i)]= + static_cast(std::sin(t)); + } + } + Gains gains(int position,int total) const noexcept { + const int index=std::clamp(static_cast( + (static_cast(std::max(0,position))*resolution)/ + std::max(1,total)),0,resolution); + return {old_[static_cast(index)], + next_[static_cast(index)]}; + } +private: + std::array old_{},next_{}; +}; +} // namespace armix::player diff --git a/engine/player/PlayerShowEditPolicy.h b/engine/player/PlayerShowEditPolicy.h new file mode 100644 index 000000000..afc6b4075 --- /dev/null +++ b/engine/player/PlayerShowEditPolicy.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +// Stable-index changes for the operator's current song, selected NEXT, +// and pending async transition. No data allocations or UI/runtime dependencies. +namespace armix::player { +struct PlayerShowEditPolicy final { + static int afterMove(int index,int from,int to,int size) noexcept { + if(index<0)return -1; + if(from<0 || to<0 || from>=size || to>=size || from==to) + return index; + if(index==from)return to; + if(fromfrom && index<=to)return index-1; + if(from>to && index>=to && indexremoved?index-1:index; + } + static int afterInsert(int index,int inserted) noexcept { + if(index<0 || inserted<0)return index; + return index>=inserted?index+1:index; + } +}; +} // namespace armix::player diff --git a/engine/player/PlayerShowTransitionPolicy.h b/engine/player/PlayerShowTransitionPolicy.h new file mode 100644 index 000000000..7b5bc4856 --- /dev/null +++ b/engine/player/PlayerShowTransitionPolicy.h @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// Show transport decisions only; deterministic and allocation-free on +// inspection paths. Never owns JUCE, an audio device, or a DSP callback. +namespace armix::player { +// One outstanding Auto Next attempt per logical playback segment. A/B +// decoders may share numeric generations, so generation XOR is not a valid +// identity for queued repeats. Only a successful native ACK or explicit +// operator gesture rearms the next segment; errors do not busy-loop. +class PlayerAutoAdvanceGate final { +public: + bool claim() noexcept { + if(claimed_)return false; + claimed_=true; + return true; + } + void rearm() noexcept {claimed_=false;} + bool claimed() const noexcept {return claimed_;} +private: + bool claimed_=false; // CONTROL thread only; never touched by RT +}; +struct PlayerShowTransitionPolicy final { + // Manual selection/explicit queue always wins over sequential Auto Next. + // queuedIndex=-1 when there is no valid queued song. + static int nextIndex(int current,int selected,int count, + int queuedIndex) noexcept { + if(count<=0)return -1; + if(queuedIndex>=0 && queuedIndex=0 && selected=0 && selected3000 || tickSeconds<=0. || + tickSeconds>0.5 || tempoPercent<80 || tempoPercent>120) + return false; + const double remaining=duration-seconds; + // The UI clock counts ORIGINAL MEDIA seconds. One real second + // consumes tempo/100 source seconds. Ignore this and a 120% song + // runs out before its requested fade can finish. + const double speed=static_cast(tempoPercent)/100.; + const double early=(static_cast(fadeMilliseconds)/1000.+ + tickSeconds)*speed; + return remaining<=early && remaining>=-tickSeconds*speed; + } + // Loop A-B is a rehearsal-only opt-in. Never attempt microscopic + // segments or a fade longer than the segment: require a real period of + // audible music and a bounded overlap. CUT uses a 40ms de-click loop. + static bool validLoop(double cueIn,double cueOut, + int fadeMilliseconds) noexcept { + if(!std::isfinite(cueIn)||!std::isfinite(cueOut)|| + cueIn<0. || cueOut<=cueIn || cueOut>86400. || + fadeMilliseconds<0 || fadeMilliseconds>3000)return false; + const double overlap=std::max(40,fadeMilliseconds)/1000.; + return cueOut-cueIn>=std::max(1.5,overlap+0.35); + } + // A queued entry is a logical song ID/path, not a whole-file deletion. + // Preserve duplicates and current order; UI sends source/target indices. + template + static bool moveQueued(std::vector& queue,int from,int to) { + const int count=static_cast(queue.size()); + if(from<0 || to<0 || from>=count || to>=count || + from==to)return false; + auto item=std::move(queue[static_cast(from)]); + queue.erase(queue.begin()+from); + queue.insert(queue.begin()+to,std::move(item)); + return true; + } + template + static bool commitQueuedFront(std::vector& queue, + const T& successfullyStarted) { + // The queue must not be consumed when decoder load or routing fails, + // or when another operator has since changed the head. + if(queue.empty() || queue.front()!=successfullyStarted)return false; + queue.erase(queue.begin()); + return true; + } +}; +} // namespace armix::player diff --git a/engine/player/PlayerWaveformIndex.h b/engine/player/PlayerWaveformIndex.h new file mode 100644 index 000000000..24f6fdabe --- /dev/null +++ b/engine/player/PlayerWaveformIndex.h @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// Compact, progressive, allocation-free waveform summary. Decoder worker +// alone writes; JUCE UI may read atomic bins without touching file/FFT/audio. +// No duplicated full-file scan competes with singer monitoring. +namespace armix::player { +class PlayerWaveformIndex final { +public: + static constexpr std::size_t bins=256; + PlayerWaveformIndex() noexcept {reset(0);} + void reset(std::uint64_t frames) noexcept { + total_.store(frames,std::memory_order_release); + for(auto& peak:peaks_)peak.store(0,std::memory_order_relaxed); + } + void observe(const float* l,const float* r,int frames, + std::uint64_t start) noexcept { + if(!l||!r||frames<=0)return; + const auto total=total_.load(std::memory_order_acquire); + if(!total)return; + constexpr int hop=12; + for(int i=0;i(i); + if(sample>=total)break; + const auto index=std::min(bins-1, + static_cast((static_cast(sample)* + bins)/total)); + const float peak=std::max(std::abs(l[i]),std::abs(r[i])); + if(!std::isfinite(peak))continue; + const auto value=static_cast( + std::clamp(std::lround(peak*65535.f),0L,65535L)); + auto old=peaks_[index].load(std::memory_order_relaxed); + while(old snapshot() const noexcept { + std::array values{}; + for(std::size_t i=0;i total_{0}; + std::array,bins> peaks_{}; +}; +} // namespace armix::player diff --git a/site/preview-v2/assets/arson-player.js b/site/preview-v2/assets/arson-player.js index 79be6dc43..9420fefbb 100644 --- a/site/preview-v2/assets/arson-player.js +++ b/site/preview-v2/assets/arson-player.js @@ -7,7 +7,8 @@ if(!root||!toggle)return; const backend=window.__JUCE__?.backend; const native=Boolean(backend?.emitEvent&&backend?.addEventListener); - let model={tracks:[],selected:-1,current:-1,autoNext:false, + let model={tracks:[],setlists:[],queue:[],activeSetlist:0, + selected:-1,current:-1,autoNext:false, transport:{state:"EMPTY",title:"",currentSeconds:0,durationSeconds:0}, error:""}; const send=(action,value)=>{ @@ -38,6 +39,53 @@ send(model.transport?.state==="PLAYING"?"playerPause":"playerPlay"); }); $("playerStop").addEventListener("click",()=>send("playerStop")); + for(const id of ["playerCueIn","playerCueOut","playerCueGoIn","playerCueClear"]) + $(id).addEventListener("click",()=>send(id)); + $("playerLoopAB").addEventListener("click",()=> + send("playerLoopToggle",!Boolean(model.loopAB))); + const seek=$("playerSeek"),waveCanvas=$("playerWaveform"); + let draggingSeek=false; + seek.addEventListener("pointerdown",()=>{draggingSeek=true;}); + seek.addEventListener("pointerup",()=>{draggingSeek=false;}); + seek.addEventListener("pointercancel",()=>{draggingSeek=false;}); + // 'change' emits one intentional seek on release or keyboard commit. + // Never send a native seek for each pointermove while the show is live. + seek.addEventListener("change",()=>{ + draggingSeek=false; + const length=Number(model.transport?.durationSeconds)||0; + const fraction=Number(seek.value)/1000; + if(length>0 && Number.isFinite(fraction)) + send("playerSeek",Math.max(0,Math.min(length, + Math.round(fraction*length*100)/100))); + }); + let lastWaveSignature=""; + const renderWaveform=transport=>{ + const peaks=transport.waveform; + if(!Array.isArray(peaks)||peaks.length!==256)return; + const fraction=Number(transport.durationSeconds)>0? + Math.max(0,Math.min(1, + Number(transport.currentSeconds)/Number(transport.durationSeconds))):0; + // Incremental worker histogram. Redraw only when bins or playhead change. + const signature=peaks.join(",")+"|"+Math.round(fraction*256); + if(signature===lastWaveSignature)return; + lastWaveSignature=signature; + const ctx=waveCanvas.getContext("2d"); + if(!ctx)return; + const w=waveCanvas.width,h=waveCanvas.height,half=h/2; + ctx.clearRect(0,0,w,h); + ctx.fillStyle="#1e363e";ctx.fillRect(0,0,w,h); + for(let i=0;i<256;++i){ + // Display only already decoded regions, no fake waveform data. + const normalized=Math.max(0,Math.min(1,(Number(peaks[i])||0)/65535)); + const size=Math.max(0,Math.sqrt(normalized)*(half-2)); + if(size<0.5)continue; + ctx.fillStyle=i<=fraction*256?"#62d1b4":"#567e87"; + ctx.fillRect(i,half-size,1,size*2); + } + ctx.fillStyle="#def1e9"; + ctx.fillRect(Math.round(fraction*255),0,1,h); + }; + $("playerKeyMinus").addEventListener("click",()=>send("playerKeyStep",-1)); $("playerKeyPlus").addEventListener("click",()=>send("playerKeyStep",1)); $("playerTempoMinus").addEventListener("click",()=>send("playerTempoStep",-1)); @@ -47,7 +95,74 @@ $("playerNext").addEventListener("click",()=>send("playerNext")); $("playerAutoNext").addEventListener("click",()=> send("playerAutoNext",!model.autoNext)); + $("playerFadeMs").addEventListener("change",event=> + send("playerFadeMs",Number(event.target.value))); + $("playerNewSetlist").addEventListener("click",()=>send("playerNewSetlist")); + $("playerDeleteSetlist").addEventListener("click",()=>send("playerDeleteSetlist",model.activeSetlist)); + $("playerSetlistSelect").addEventListener("change",event=> + send("playerSelectSetlist",Number(event.target.value))); + $("playerSetlistName").addEventListener("change",event=> + send("playerRenameSetlist",event.target.value.trim())); + $("playerSetlistName").addEventListener("keydown",event=>{ + if(event.key==="Enter"){event.preventDefault();event.target.blur();} + }); + $("playerUndoRemove").addEventListener("click",()=>send("playerUndoRemove")); const list=$("playerList"),search=$("playerSearch"); + const actionButton=(label,title,onClick)=>{ + const button=document.createElement("button"); + button.type="button";button.className="ap-row-action"; + button.textContent=label;button.title=title; + button.setAttribute("aria-label",title); + button.addEventListener("click",onClick); + return button; + }; + let renderedSets=-1; + function renderSetlists(){ + if(renderedSets===libraryRevision)return; + renderedSets=libraryRevision; + const selector=$("playerSetlistSelect"),name=$("playerSetlistName"); + const oldFocus=document.activeElement===name; + selector.replaceChildren(); + for(const set of model.setlists||[]){ + const option=document.createElement("option"); + option.value=String(set.id); + option.textContent=String(set.name||"Setlist")+" · "+set.count; + selector.append(option); + } + selector.value=String(model.activeSetlist||0); + if(!oldFocus)name.value=model.setlists?.[model.activeSetlist]?.name||""; + $("playerDeleteSetlist").disabled=(model.setlists?.length||0)<=1; + $("playerUndoRemove").hidden=!model.canUndoRemove; + const panel=$("playerQueuePanel"),queue=$("playerQueueList"); + const upcoming=model.queue||[]; + panel.hidden=!upcoming.length; + $("playerQueueCount").textContent=String(upcoming.length); + queue.replaceChildren(); + for(const item of upcoming.slice(0,12)){ + const row=document.createElement("div"); + row.className="ap-queue-row";row.setAttribute("role","listitem"); + const title=document.createElement("span"); + title.textContent=String(item.title||"Untitled"); + const controls=document.createElement("span"); + controls.className="ap-row-actions"; + const up=actionButton("↑","Move "+item.title+" earlier", + ()=>send("playerQueueMove",{from:item.id,to:item.id-1})); + const down=actionButton("↓","Move "+item.title+" later", + ()=>send("playerQueueMove",{from:item.id,to:item.id+1})); + up.disabled=item.id===0; + down.disabled=item.id===upcoming.length-1; + controls.append(up,down,actionButton("×", + "Remove "+item.title+" from queue", + ()=>send("playerQueueRemove",item.id))); + row.append(title,controls); + queue.append(row); + } + if(upcoming.length>12){ + const more=document.createElement("small"); + more.textContent="+"+(upcoming.length-12)+" more queued";queue.append(more); + } + } + let libraryRevision=0,rendered=""; function renderTracks(){ // Avoid serializing and rebuilding a 2,000-song list on every realtime @@ -68,13 +183,15 @@ list.append(message);return; } for(const song of songs){ - const row=document.createElement("button"); - row.type="button";row.className="ap-song"; - row.dataset.selected=String(song.id===model.selected); - row.dataset.current=String(song.id===model.current); - row.setAttribute("role","option"); - row.setAttribute("aria-selected",String(song.id===model.selected)); - row.title="Select next · double-click to play now"; + const row=document.createElement("div"); + row.className="ap-songrow";row.setAttribute("role","listitem"); + row.draggable=native; + const choose=document.createElement("button"); + choose.type="button";choose.className="ap-song"; + choose.dataset.selected=String(song.id===model.selected); + choose.dataset.current=String(song.id===model.current); + choose.setAttribute("aria-selected",String(song.id===model.selected)); + choose.title="Click to prepare NEXT · Double-click to play now"; const index=document.createElement("span"); index.className="ap-index"; index.textContent=String(song.id+1).padStart(2,"0"); @@ -85,16 +202,40 @@ state.textContent=song.missing?"Missing": song.id===model.current?"NOW": song.id===model.selected?"NEXT":""; - row.append(index,title,state); - row.addEventListener("click",()=>send("playerSelect",song.id)); - row.addEventListener("dblclick",()=>send("playerPlayNow",song.id)); - row.addEventListener("keydown",event=>{ + choose.append(index,title,state); + choose.addEventListener("click",()=>send("playerSelect",song.id)); + choose.addEventListener("dblclick",()=>send("playerPlayNow",song.id)); + choose.addEventListener("keydown",event=>{ if(event.key==="Enter"){ event.preventDefault(); send("playerPlayNow",song.id); } }); - list.append(row); + const actions=document.createElement("span"); + actions.className="ap-row-actions"; + const move=delta=>send("playerMoveSong", + {from:song.id,to:song.id+delta}); + actions.append( + actionButton("↑","Move "+song.title+" up",()=>move(-1)), + actionButton("↓","Move "+song.title+" down",()=>move(1)), + actionButton("↥","Play "+song.title+" next", + ()=>send("playerQueueNext",song.id)), + actionButton("+","Add "+song.title+" to queue", + ()=>send("playerQueueAppend",song.id)), + actionButton("×","Remove "+song.title+" from this setlist", + ()=>send("playerRemoveSong",song.id))); + row.addEventListener("dragstart",event=>{ + event.dataTransfer?.setData("text/plain",String(song.id)); + if(event.dataTransfer)event.dataTransfer.effectAllowed="move"; + }); + row.addEventListener("dragover",event=>event.preventDefault()); + row.addEventListener("drop",event=>{ + event.preventDefault(); + const source=Number(event.dataTransfer?.getData("text/plain")); + if(Number.isInteger(source)&&source>=0 && source!==song.id) + send("playerMoveSong",{from:source,to:song.id}); + }); + row.append(choose,actions);list.append(row); } if(all.length>songs.length){ const hint=document.createElement("div"); @@ -110,8 +251,31 @@ $("playerNow").textContent=t.title||"No music loaded"; $("playerElapsed").textContent=duration(t.currentSeconds); $("playerDuration").textContent=duration(t.durationSeconds); - $("playerProgress").value=+t.durationSeconds>0? - Math.min(1,Math.max(0,+t.currentSeconds/(+t.durationSeconds))):0; + if(!draggingSeek && document.activeElement!==seek){ + seek.value=String(+t.durationSeconds>0? + Math.round(1000*Math.min(1,Math.max(0, + +t.currentSeconds/(+t.durationSeconds)))):0); + } + seek.disabled=!(+t.durationSeconds>0) || !native; + renderWaveform(t); + const currentSong=model.tracks?.[model.current]; + const inPoint=Number(currentSong?.cueIn)||0; + const outPoint=Number(currentSong?.cueOut)||0; + $("playerCueSummary").textContent="IN "+duration(inPoint)+ + " · OUT "+(outPoint>0?duration(outPoint):"end"); + const editable=native && model.current>=0 && + model.selected===model.current && +t.durationSeconds>0; + $("playerCueIn").disabled=!editable; + $("playerCueOut").disabled=!editable; + $("playerCueGoIn").disabled=!editable; + $("playerCueClear").disabled=!editable; + const loopBtn=$("playerLoopAB"); + const loopValid=outPoint>inPoint && + outPoint-inPoint>=Math.max(1.5, + Math.max(40,Number(model.crossfadeMs)||0)/1000+.35); + loopBtn.disabled=!editable || (!model.loopAB && !loopValid); + loopBtn.textContent=model.loopAB?"Loop A–B · On":"Loop A–B"; + loopBtn.setAttribute("aria-pressed",String(Boolean(model.loopAB))); $("playerPlay").textContent=state==="PLAYING"?"Ⅱ Pause":"▶ Play"; const editingIndex=model.selected>=0?model.selected:model.current; const chosen=model.tracks[editingIndex]; @@ -134,6 +298,9 @@ $("playerTempoPlus").disabled=tempo>=120; $("playerAutoNext").textContent=model.autoNext?"Auto Next · On":"Auto Next · Off"; $("playerAutoNext").setAttribute("aria-pressed",String(model.autoNext)); + $("playerFadeMs").value=String(model.crossfadeMs??180); + $("playerTransitionStatus").textContent=t.crossfading?"Crossfading…": + t.transitionPending?"Preparing NEXT…":""; const detail=model.error||t.error||({ EMPTY:"Add music to begin", PREPARING:"Preparing audio…", @@ -158,6 +325,7 @@ $("playerAddFolder").disabled=Boolean(model.libraryBusy); $("playerAdd").disabled=Boolean(model.libraryBusy); $("playerCount").textContent=model.tracks.length+" songs"; + renderSetlists(); renderTracks(); } search.addEventListener("input",renderTracks); diff --git a/site/preview-v2/assets/mixer-contextual-buttons.css b/site/preview-v2/assets/mixer-contextual-buttons.css index 1c19aca07..6dda21698 100644 --- a/site/preview-v2/assets/mixer-contextual-buttons.css +++ b/site/preview-v2/assets/mixer-contextual-buttons.css @@ -356,6 +356,85 @@ body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power):f #arsonPlayer #playerAddFolder:disabled{opacity:.5;cursor:wait} +/* IN/OUT cues live inside the player timeline; no additional drawer. */ +#arsonPlayer .ap-cues{display:flex;align-items:center;gap:4px; + margin-top:6px;flex-wrap:wrap} +#arsonPlayer #playerCueSummary{flex:1;min-width:96px; + color:#92c6bb;font-size:10px;font-variant-numeric:tabular-nums} +#arsonPlayer .ap-cues button{padding:3px 5px;border:1px solid #35505a; + border-radius:4px;background:#1d3940;color:#bbd8d2;font-size:10px} +#arsonPlayer .ap-cues button:disabled{opacity:.38;cursor:default} +#arsonPlayer #playerLoopAB[aria-pressed="true"]{ + border-color:#5bbba4;background:#25534a;color:#d0f9ed} + +/* M3 transition remains one inline control, not a new player mode. */ +#arsonPlayer .ap-showtools{display:flex;align-items:center;gap:8px; + min-height:30px;padding:4px 12px;background:#172830; + border-bottom:1px solid #2a4148;font-size:10px;color:#92b5b5} +#arsonPlayer .ap-showtools select{max-width:138px;padding:4px 6px; + background:#1c353e;border:1px solid #3d5c64;border-radius:5px; + font-size:10px;color:#cbebdf} +#arsonPlayer #playerTransitionStatus{margin-left:auto;min-width:0; + color:#83d7c4;text-align:right;font-size:10px} + +/* Decoder-only peak summary + explicit seek: never streams browser PCM. */ +#arsonPlayer .ap-waveform{display:block;width:100%;height:42px; + border:1px solid #2c454b;border-radius:5px;background:#1e363e} +#arsonPlayer #playerSeek{appearance:none;-webkit-appearance:none; + height:5px;width:100%;min-width:24px;flex:1;cursor:pointer; + background:#39545b;border-radius:4px;accent-color:#72d7bb} +#arsonPlayer #playerSeek::-webkit-slider-thumb{-webkit-appearance:none; + width:12px;height:12px;border:1px solid #8af1d2;border-radius:50%; + background:#408978;box-shadow:0 1px 4px #0008} +#arsonPlayer #playerSeek:disabled{opacity:.4;cursor:default} + +/* ArSon Player Show v3: dense, keyboard/touch-accessible setlist editing. + Reuse the approved panel chrome; no extra floating card, stylesheet or + production mixer control style mutation. */ +#arsonPlayer .ap-settools{display:flex;align-items:center;gap:5px; + padding:7px 11px 4px} +#arsonPlayer .ap-settools select{flex:1;min-width:0;max-width:200px; + padding:5px 7px;border:1px solid #35535c;border-radius:5px; + background:#162b33;color:#c5e3e1;font-size:11px} +#arsonPlayer .ap-settools button,#arsonPlayer .ap-setname button{ + white-space:nowrap;padding:5px 7px;border:1px solid #36535c; + border-radius:5px;background:#1d363d;color:#b4d6d3;font-size:10px} +#arsonPlayer .ap-setname{display:flex;align-items:center;gap:6px; + padding:3px 11px} +#arsonPlayer .ap-setname input{flex:1;min-width:0;max-width:230px; + padding:5px 7px;background:#10232b;color:#d8e9e8; + border:1px solid #31505a;border-radius:5px;font-size:11px} +#arsonPlayer .ap-setname button[hidden]{display:none!important} +#arsonPlayer .ap-settools :disabled{opacity:.4;cursor:default} +#arsonPlayer .ap-songrow{display:flex;align-items:center;gap:2px; + min-width:0;min-height:37px} +#arsonPlayer .ap-songrow .ap-song{flex:1;min-width:0; + width:auto;min-height:36px;padding:6px} +#arsonPlayer .ap-songrow .ap-index{flex-basis:21px} +#arsonPlayer .ap-row-actions{display:flex;align-items:center;gap:1px; + flex:0 0 auto} +#arsonPlayer .ap-row-action{width:22px;height:27px;min-width:22px; + padding:0!important;display:inline-flex;align-items:center;justify-content:center; + border:1px solid transparent;background:transparent;border-radius:4px; + color:#8aadb0;font-size:12px;line-height:1} +#arsonPlayer .ap-row-action:hover{background:#29464d;border-color:#49636b; + color:#def4ed} +#arsonPlayer .ap-songrow[draggable="true"]{cursor:grab} +#arsonPlayer .ap-queue{flex:0 0 auto;max-height:110px;overflow:auto; + padding:6px 11px;border-top:1px solid #2b4449;background:#162830} +#arsonPlayer .ap-queue[hidden]{display:none!important} +#arsonPlayer .ap-queue-title{font-size:10px;color:#94c2b9; + letter-spacing:.03em;padding-bottom:3px} +#arsonPlayer .ap-queue-row{display:flex;align-items:center;justify-content:space-between; + gap:8px;padding:2px 3px;font-size:11px;color:#c6dfdc} +#arsonPlayer .ap-queue-row span{min-width:0;overflow:hidden; + text-overflow:ellipsis;white-space:nowrap} +#arsonPlayer .ap-queue-row .ap-row-action{height:22px} +@media(max-width:410px){ + #arsonPlayer .ap-row-action{width:20px;min-width:20px} + #arsonPlayer .ap-settools button{padding:5px} +} + /* Shared modeless window workspace. Header-only drag: underlying FX knobs, faders, routing wires, search, buttons and scroll panes are never gesture targets. Viewport coordinates diff --git a/site/preview-v2/assets/mixer-contextual-buttons.js b/site/preview-v2/assets/mixer-contextual-buttons.js index f3be4b4ad..8b7f9a3f5 100644 --- a/site/preview-v2/assets/mixer-contextual-buttons.js +++ b/site/preview-v2/assets/mixer-contextual-buttons.js @@ -51,8 +51,13 @@ panel.setAttribute('aria-label','ArSon music player and live setlist'); panel.innerHTML=`
ArSon PlayerMusic · Setlist
-
PLAYER A · CURRENT
No music loaded
00:0000:00
+
PLAYER A · CURRENT
No music loaded
+ +
00:0000:00
+
IN 00:00 · OUT end
+
+
KEY0 st
TEMPO100%
@@ -60,9 +65,16 @@
Add music to begin
Setlist0 songs
+
+ + + +
+
-
-
Click to prepare · Double-click to play · Native audio through your mixer
`; +
+ +
Select NEXT · Double-click to play · Drag or ↑/↓ to reorder · Native mixer audio
`; toolbar.insertAdjacentElement('afterend',panel); const base=document.currentScript?.src||document.baseURI; // Player CSS is folded into the EXISTING approved runtime stylesheet. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 65baae3d3..cb6ad2e4e 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -10,7 +10,7 @@ #include "NativeMixerSessionFxRestore.h" #include "NativeTopologyEditSafety.h" #include "../engine/dsp/NativeMasterLoudness.h" -#include "../engine/player/NativePlayerDeck.h" +#include "../engine/player/NativePlayerShowDeck.h" #include "../engine/builtin_fx/ChannelEqProcessor.h" #include "../engine/builtin_fx/ChannelCompressorProcessor.h" #include "../engine/builtin_fx/ChannelHarmonyProcessor.h" @@ -1818,7 +1818,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // A single explicit user Play gesture prepares the previously verified // MAIN and creates its owned virtual MUSIC channel if absent. No manual // PATCH, MONITOR or ARM control is part of the ordinary user workflow. - juce::String loadPlayerMusic(const juce::File& file) { + juce::String loadPlayerMusic(const juce::File& file, + double cueIn=0.,double cueOut=0.) { if(!file.existsAsFile())return "Music file is missing"; if(!file.hasFileExtension("wav;aiff;aif;mp3;flac;ogg")) return "Choose a supported music file (WAV, MP3, FLAC, AIFF, OGG)"; @@ -1864,7 +1865,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } playerChannelId_=result.created; playerFile_=file; + playerPendingFile_={}; playerBoundEpoch_=dryRoutingLab_.epoch(); + if(!playerDeck_.setCueRange(cueIn,cueOut)) + return "Invalid song IN/OUT markers"; + playerCueIn_=cueIn;playerCueOut_=cueOut; playerDeck_.load(file,true); // async worker; real PLAYING only after PCM // The fresh PLAY gesture itself authorizes same verified output. // Never override an intentional MAIN MUTE or different physical port. @@ -1880,7 +1885,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if((playerBoundEpoch_!=dryRoutingLab_.epoch() || dryRoutingLab_.nativePlayerSource()!=playerChannelId_) && playerFile_!=juce::File{}) - return loadPlayerMusic(playerFile_); + return loadPlayerMusic(playerFile_,playerCueIn_,playerCueOut_); if(!playerChannelId_.value || !directFence_.permitted() || !dryRoutingLab_.channelIdPhysicalPcmActive() || masterMute_.load(std::memory_order_acquire) || @@ -1895,8 +1900,68 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // the decoder worker consumes more/fewer backing-track PCM frames. return playerDeck_.setPitchTempo(semitones,percent); } + // Preloading never touches the native graph or opens another physical + // output. Both decoded sources ultimately share PLAYER A ChannelId. + bool preloadPlayerMusic(const juce::File& file,int key,int tempo, + double cueIn=0.,double cueOut=0.) { + // A queued repeat of CURRENT is legitimate: the inactive decoder + // must preload a second instance without stopping current PCM. + if(playerFile_==juce::File{} || + playerBoundEpoch_!=dryRoutingLab_.epoch() || + !directFence_.permitted() || + !dryRoutingLab_.channelIdPhysicalPcmActive()) + return false; + return playerDeck_.preload(file,key,tempo,cueIn,cueOut); + } + bool queuePlayerTransition(const juce::File& file,int key,int tempo, + int fadeMilliseconds=180, + double cueIn=0.,double cueOut=0.) { + if(playerFile_==juce::File{} || !file.existsAsFile() || + !file.hasFileExtension("wav;mp3;flac;aif;aiff;ogg") || + playerBoundEpoch_!=dryRoutingLab_.epoch() || + !directFence_.permitted() || + !dryRoutingLab_.channelIdPhysicalPcmActive()) + return false; + if(!playerDeck_.queueTransition(file,key,tempo,fadeMilliseconds, + cueIn,cueOut)) + return false; + playerPendingCueIn_=cueIn;playerPendingCueOut_=cueOut; + playerPendingFile_=file; + return true; + } + bool playerTransitionFailed() const noexcept { + return playerDeck_.transitionFailed(); + } + bool servicePlayerTransition() { + if(!playerDeck_.service()) { + if(playerDeck_.transitionFailed() || + (!playerDeck_.transitionPending() && + !playerDeck_.transitionActive())) + playerPendingFile_={}; + return false; + } + if(playerPendingFile_!=juce::File{}) { + playerFile_=playerPendingFile_; + playerCueIn_=playerPendingCueIn_; + playerCueOut_=playerPendingCueOut_; + } + playerPendingFile_={}; + return true; + } + bool setPlayerCueRange(double in,double out) noexcept { + if(!playerDeck_.setCueRange(in,out))return false; + playerCueIn_=in;playerCueOut_=out; + return true; + } void playerPause() noexcept {playerDeck_.pause();} - void playerStop() noexcept {playerDeck_.stop();} + void playerStop() noexcept { + playerPendingFile_={}; + playerDeck_.stop(); + } + bool playerSeekSeconds(double seconds) noexcept { + return playerFile_!=juce::File{} && + playerDeck_.seekSeconds(seconds); + } juce::var playerStatus() const { const auto status=playerDeck_.snapshot(); const auto* state="EMPTY"; @@ -1913,12 +1978,17 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } auto data=std::make_unique(); data->setProperty("state",state); + data->setProperty("transitionPending",playerDeck_.transitionPending()); + data->setProperty("crossfading",playerDeck_.transitionActive()); data->setProperty("title",status.title); data->setProperty("error",status.error); + // Operator seek/IN/OUT always use the ORIGINAL media clock. + // Output-frame counters (separately retained on the deck) control + // physical end-of-stream and stretch/tempo latency accounting. data->setProperty("currentSeconds",status.deviceRate>0? - static_cast(status.played)/status.deviceRate:0.0); + static_cast(status.mediaPlayed)/status.deviceRate:0.0); data->setProperty("durationSeconds",status.deviceRate>0? - static_cast(status.duration)/status.deviceRate:0.0); + static_cast(status.mediaDuration)/status.deviceRate:0.0); data->setProperty("underrunFrames",juce::String( static_cast(status.underruns))); data->setProperty("keySemitones",status.keySemitones); @@ -1927,6 +1997,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback data->setProperty("requestedTempo",status.requestedTempo); data->setProperty("processingChangePending", status.processingChangePending); + // A bounded 256-bin atomic snapshot, not a second audio decode. + juce::Array waveform; + waveform.ensureStorageAllocated( + static_cast(armix::player::PlayerWaveformIndex::bins)); + for(const auto sample:status.waveform) + waveform.add(static_cast(sample)); + data->setProperty("waveform",juce::var(waveform)); data->setProperty("generation",juce::String( static_cast(status.generation))); data->setProperty("channelId",juce::String( @@ -2790,9 +2867,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic fxMovePendingOrder_ {Graph::canonicalOrder}; bool attached_ = false; juce::AudioBuffer scratch_; - armix::player::NativePlayerDeck playerDeck_; // one asynchronous decoder, no device owner + armix::player::NativePlayerShowDeck playerDeck_; // A/B workers, ONE mixer PCM source armix::mixer::ChannelId playerChannelId_{}; // CONTROL only, native identity - juce::File playerFile_; // CONTROL only, last explicitly selected song + juce::File playerFile_; // CONTROL only, last active song + juce::File playerPendingFile_; // CONTROL only, next decoded song + double playerCueIn_=0.,playerCueOut_=0.; + double playerPendingCueIn_=0.,playerPendingCueOut_=0.; std::uint64_t playerBoundEpoch_=0; // never borrow old device approval std::array,2> playerScratch_{}; // preallocated RT block armix::dsp::NativeMasterLoudness masterLoudness_; diff --git a/src/Main.cpp b/src/Main.cpp index 1d1c5c6ab..574e46e50 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -57,6 +57,8 @@ #include #include #include "../engine/player/PlayerSetlistPolicy.h" +#include "../engine/player/PlayerShowEditPolicy.h" +#include "../engine/player/PlayerShowTransitionPolicy.h" #include "../engine/player/PlayerLibraryPolicy.h" #include #include @@ -495,14 +497,38 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool studioBackupBusy_ = false; std::unique_ptr chooser_; std::unique_ptr playerFileChooser_; - std::vector playerLibrary_; // one compact default setlist - struct PlayerTrackSettings {int key=0,tempo=100;}; - std::vector playerTrackSettings_; // parallel stable entry IDs + // PlayerShow v3: one active setlist projects into the existing native + // 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 + }; + 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 + struct PlayerUndoRemove { + int set=-1,index=-1; + juce::File file; + PlayerTrackSettings controls{}; + }; + PlayerUndoRemove playerUndoRemove_{}; int playerSelected_=-1,playerCurrent_=-1; + int playerPendingIndex_=-1; // becomes CURRENT only after native fade ACK + juce::File playerPendingQueueFile_; // commit queue ONLY after real PCM ACK + int playerFadeMilliseconds_=180; // compact optional transition setting int playerOutputPendingIndex_=-1; // only after explicit Choose output gesture bool playerAutoNext_=false; + bool playerLoopCurrent_=false; // explicit rehearsal toggle, never persisted bool playerFolderBusy_=false; // GUI only; background scanner never touches this - std::uint64_t lastAutoAdvanceGeneration_=0; + armix::player::PlayerAutoAdvanceGate playerAutoAdvanceGate_; juce::String playerError_; juce::File lastPluginFolder_ = juce::File::getSpecialLocation (juce::File::userHomeDirectory); // Destruction order: editorWindow_ releases its JUCE GUI BEFORE the @@ -3704,67 +3730,338 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr }); } - // One native player, one local setlist, one worker decoder, same JUCE - // callback. The WebView may only select songs or send transport intents. + // 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; + const auto& chosen=playerSets_[static_cast(index)]; + playerLibrary_=chosen.files; + playerTrackSettings_=chosen.controls; + playerCurrent_=-1; + playerAutoAdvanceGate_.rearm(); + playerLoopCurrent_=false; + playerPendingIndex_=-1; + playerPendingQueueFile_={}; + playerSelected_=playerLibrary_.empty()?-1:0; + playerQueue_.clear(); + playerOutputPendingIndex_=-1; + playerUndoRemove_={}; + } void restorePlayerLibrary() { + playerSets_.clear(); const auto file=settingsDirectory().getChildFile("player-library.json"); - if(!file.existsAsFile())return; - auto json=juce::JSON::parse(file.loadFileAsString()); + if(!file.existsAsFile()) { + 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)) { - playerError_="Saved setlist could not be read; music files were not changed"; + if(!json.isObject() || (version!=1 && version!=2 && version!=3)) { + playerSets_.push_back({"My Setlist",{},{}}); + playerError_="Setlists could not be read; no music files were changed"; return; } - const auto tracks=json.getProperty("files",{}); - if(const auto* list=tracks.getArray()) { - for(const auto& item:*list) { - if(playerLibrary_.size()>=2000)break; - if((version==1 && !item.isString()) || - (version==2 && !item.isObject()))continue; - const auto text=version==1?item.toString(): - item.getProperty("path","").toString(); - if(text.isEmpty() || text.length()>4096)continue; - const juce::File entry(text); - if(!juce::File::isAbsolutePath(text) || - !entry.hasFileExtension("wav;mp3;flac;aif;aiff;ogg") || - std::find(playerLibrary_.begin(),playerLibrary_.end(),entry) - !=playerLibrary_.end()) - continue; - PlayerTrackSettings controls; - if(version==2) { - controls.key=static_cast(item.getProperty("key",0)); - controls.tempo=static_cast(item.getProperty("tempo",100)); - if(controls.key< -6 || controls.key>6 || - controls.tempo<80 || controls.tempo>120) - controls={}; // corrupt automation cannot alter audio + 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); } - playerLibrary_.push_back(entry); - playerTrackSettings_.push_back(controls); + } + }; + // 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)); - if(!playerLibrary_.empty())playerSelected_=0; + const int fade=static_cast(json.getProperty("crossfadeMs",180)); + playerFadeMilliseconds_=(fade>=0 && fade<=3000)?fade:180; } void persistPlayerLibrary() { + saveActivePlayerSet(); auto document=std::make_unique(); - document->setProperty("version",2); + document->setProperty("version",3); + document->setProperty("activeSetlist",playerActiveSet_); document->setProperty("autoNext",playerAutoNext_); - juce::Array files; - for(std::size_t i=0;i(); - entry->setProperty("path",playerLibrary_[i].getFullPathName()); - entry->setProperty("key",playerTrackSettings_[i].key); - entry->setProperty("tempo",playerTrackSettings_[i].tempo); - files.add(juce::var(entry.release())); + 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("files",juce::var(files)); + 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 setlist; check folder permissions"; + playerError_="Unable to save setlists; check folder permissions"; + } + bool playerShowMaySwitchSet() { + const auto state=engine_.playerStatus().getProperty("state","").toString(); + if(state=="PLAYING" || state=="PREPARING" || state=="PAUSED") { + playerError_="Stop the current song before switching setlists"; + emitPlayerState();return false; + } + return !playerFolderBusy_; + } + void playerEditSetlist(const juce::String& action,const juce::var& value) { + 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),{},{}}); + 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; + } + playerSets_[static_cast(playerActiveSet_)].name=name; + playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + return; + } + if(action=="playerMoveSong") { + const int from=static_cast(value.getProperty("from",-1)); + 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_); + const auto remap=[&](int index) { + return armix::player::PlayerShowEditPolicy::afterMove( + index,from,to,count); + }; + playerSelected_=remap(playerSelected_); + playerCurrent_=remap(playerCurrent_); + playerPendingIndex_=remap(playerPendingIndex_); + persistPlayerLibrary();emitPlayerState(true); + return; + } + if(action=="playerRemoveSong") { + const int index=static_cast(value); + if(index<0 || index>=static_cast(playerLibrary_.size()))return; + if(index==playerPendingIndex_) { + playerError_="NEXT is preparing; wait before removing this song"; + emitPlayerState();return; + } + if(index==playerCurrent_ && + engine_.playerStatus().getProperty("state","").toString()!="ENDED" && + engine_.playerStatus().getProperty("state","").toString()!="STOPPED") { + playerError_="Stop the playing song before removing it"; + emitPlayerState();return; + } + playerUndoRemove_={playerActiveSet_,index, + playerLibrary_[static_cast(index)], + playerTrackSettings_[static_cast(index)]}; + playerQueue_.erase( + std::remove(playerQueue_.begin(),playerQueue_.end(), + playerUndoRemove_.file),playerQueue_.end()); + playerLibrary_.erase(playerLibrary_.begin()+index); + playerTrackSettings_.erase(playerTrackSettings_.begin()+index); + const auto remap=[&](int old) { + return armix::player::PlayerShowEditPolicy::afterRemove( + old,index); + }; + playerCurrent_=remap(playerCurrent_); + playerSelected_=remap(playerSelected_); + playerPendingIndex_=remap(playerPendingIndex_); + if(playerSelected_<0 && !playerLibrary_.empty()) + playerSelected_=std::min(index, + static_cast(playerLibrary_.size())-1); + playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + return; + } + if(action=="playerUndoRemove") { + const auto removed=playerUndoRemove_; + if(removed.set!=playerActiveSet_ || removed.index<0)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); + playerCurrent_=armix::player::PlayerShowEditPolicy::afterInsert( + playerCurrent_,index); + playerSelected_=armix::player::PlayerShowEditPolicy::afterInsert( + playerSelected_,index); + playerPendingIndex_=armix::player::PlayerShowEditPolicy::afterInsert( + playerPendingIndex_,index); + playerUndoRemove_={}; + playerError_.clear();persistPlayerLibrary();emitPlayerState(true); + return; + } + if(action=="playerQueueNext" || action=="playerQueueAppend") { + const int index=static_cast(value); + if(index<0 || index>=static_cast(playerLibrary_.size()) || + playerQueue_.size()>=128)return; + const auto file=playerLibrary_[static_cast(index)]; + if(action=="playerQueueNext" && playerPendingIndex_>=0) { + playerError_="NEXT is transitioning; queue changes after ACK"; + emitPlayerState();return; + } + if(action=="playerQueueNext") + playerQueue_.insert(playerQueue_.begin(),file); + else playerQueue_.push_back(file); + // Queue edits are explicit operator decisions. If a previous + // automatic attempt failed, allow the revised queue to retry. + if(playerPendingIndex_<0)playerAutoAdvanceGate_.rearm(); + // A manually queued NEXT deserves a warm decoder even with + // Auto Next OFF. Only CONTROL does file/preload work. + if(playerPendingIndex_<0 && !playerQueue_.empty() && + playerCurrent_>=0) { + const auto found=std::find(playerLibrary_.begin(), + playerLibrary_.end(),playerQueue_.front()); + if(found!=playerLibrary_.end()) { + const auto n=static_cast( + found-playerLibrary_.begin()); + const auto preset=playerTrackSettings_[n]; + (void)engine_.preloadPlayerMusic(playerQueue_.front(), + preset.key,preset.tempo,preset.cueIn,preset.cueOut); + } + } + playerError_.clear();emitPlayerState(true);return; + } + if(action=="playerQueueMove" || action=="playerQueueRemove") { + const int index=action=="playerQueueMove"? + static_cast(value.getProperty("from",-1)): + static_cast(value); + if(index<0 || index>=static_cast(playerQueue_.size()))return; + if(playerPendingIndex_>=0) { + playerError_="NEXT is transitioning; queue changes after ACK"; + emitPlayerState();return; + } + if(action=="playerQueueMove") { + const int to=static_cast(value.getProperty("to",-1)); + if(!armix::player::PlayerShowTransitionPolicy::moveQueued( + playerQueue_,index,to))return; + } else playerQueue_.erase(playerQueue_.begin()+index); + playerAutoAdvanceGate_.rearm(); + playerError_.clear(); + emitPlayerState(true);return; + } } void emitPlayerState(bool includeLibrary=false) { if(!browser_.loaded)return; @@ -3774,12 +4071,39 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr 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("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)); juce::Array rows; for(std::size_t i=0;i(); @@ -3789,6 +4113,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr 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)); @@ -4000,14 +4326,36 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // starts. Never transpose microphone input or alter ASIO clock. const auto controls=playerTrackSettings_[ static_cast(playerSelected_)]; + // An active show never reloads its current decoder mid-song. + // Warm the inactive deck and wait for genuine PCM readiness; + // the timer publishes the new CURRENT only after fade begins. + const bool hasCurrent=playerCurrent_>=0 && + (phase=="PLAYING" || phase=="PAUSED" || + phase=="READY" || phase=="ENDED"); + if(hasCurrent && playerCurrent_!=playerSelected_) { + playerLoopCurrent_=false; // operator explicitly changes song + if(engine_.queuePlayerTransition( + playerLibrary_[static_cast(playerSelected_)], + controls.key,controls.tempo,playerFadeMilliseconds_, + controls.cueIn,controls.cueOut)) { + playerPendingIndex_=playerSelected_; + playerError_.clear(); + } else playerError_= + "Unable to prepare NEXT on the verified mixer output"; + emitPlayerState(true); + return; + } if(!engine_.setPlayerPitchTempo(controls.key,controls.tempo)) { playerError_="Invalid KEY or TEMPO settings"; emitPlayerState();return; } const auto error=engine_.loadPlayerMusic( - playerLibrary_[static_cast(playerSelected_)]); + playerLibrary_[static_cast(playerSelected_)], + controls.cueIn,controls.cueOut); playerError_=error; if(error.isEmpty()) { + playerLoopCurrent_=false; + playerPendingIndex_=-1; playerCurrent_=playerSelected_; // A newly native-owned MUSIC ChannelId is visible in the // authoritative mixer immediately after publisher ACK. @@ -4018,13 +4366,49 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr emitPlayerState(true); } void playNextMusic() { - const int next=armix::player::SetlistPolicy::nextTrack( + if(playerPendingIndex_>=0)return; + // Next is a deliberate escape from rehearsal looping. + playerLoopCurrent_=false; + int queued=-1; + while(!playerQueue_.empty() && queued<0) { + const auto found=std::find(playerLibrary_.begin(), + playerLibrary_.end(),playerQueue_.front()); + if(found!=playerLibrary_.end()) { + queued=static_cast(found-playerLibrary_.begin()); + } else playerQueue_.erase(playerQueue_.begin()); // stale only + } + const int next=armix::player::PlayerShowTransitionPolicy::nextIndex( playerCurrent_,playerSelected_, - static_cast(playerLibrary_.size())); + static_cast(playerLibrary_.size()),queued); if(next<0) { + playerPendingQueueFile_={}; engine_.playerStop();emitPlayerState();return; } - playerSelected_=next;playSelectedMusic(); + const auto file=playerLibrary_[static_cast(next)]; + playerSelected_=next; + // Explicitly queued CURRENT is a repeat request, not a resume. + // The standby worker can decode another instance of the same file. + if(queued==playerCurrent_ && queued>=0) { + const auto control=playerTrackSettings_[static_cast(next)]; + if(engine_.queuePlayerTransition(file,control.key,control.tempo, + playerFadeMilliseconds_,control.cueIn,control.cueOut)) { + playerPendingIndex_=next; + playerPendingQueueFile_=file; + playerError_.clear(); + } else playerError_="Could not prepare queued song repeat"; + emitPlayerState(true);return; + } + playSelectedMusic(); + if(queued>=0 && playerError_.isEmpty()) { + if(playerPendingIndex_==next) { + playerPendingQueueFile_=file; + } else if(playerCurrent_==next) { + (void)armix::player::PlayerShowTransitionPolicy:: + commitQueuedFront(playerQueue_,file); + playerPendingQueueFile_={}; + emitPlayerState(true); + } + } } void onAction (const juce::var& args) @@ -4046,6 +4430,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action="audioSetup"; } if(action=="playerSubscribe")return emitPlayerState(true); + if(action=="playerNewSetlist" || action=="playerSelectSetlist" || + action=="playerDeleteSetlist" || action=="playerRenameSetlist" || + action=="playerMoveSong" || action=="playerRemoveSong" || + action=="playerUndoRemove" || action=="playerQueueNext" || + action=="playerQueueAppend" || action=="playerQueueRemove" || + action=="playerQueueMove") + return playerEditSetlist(action,value); if(action=="playerAdd")return choosePlayerFiles(); if(action=="playerAddFolder")return choosePlayerFolder(); if(action=="playerRelink")return choosePlayerRelink(); @@ -4061,7 +4452,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } const int direction=static_cast(value); auto next=playerTrackSettings_[static_cast(i)]; - if(action=="playerPitchTempoReset")next={}; + if(action=="playerPitchTempoReset") { + // Reset KEY/TEMPO only. Song cue IN/OUT and duration trims + // are independent setlist metadata, never collateral edits. + next.key=0; + next.tempo=100; + } else if((direction==1 || direction==-1) && action=="playerKeyStep") next.key=std::clamp(next.key+direction,-6,6); @@ -4080,26 +4476,153 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } return; } + if(action=="playerLoopToggle") { + const bool enable=value.isBool() && static_cast(value); + if(!enable) { + playerLoopCurrent_=false; + playerError_.clear(); + emitPlayerState();return; + } + if(playerPendingIndex_>=0 || playerCurrent_<0 || + playerCurrent_>=static_cast(playerTrackSettings_.size()) || + playerSelected_!=playerCurrent_) { + playerError_="Select CURRENT and finish NEXT before enabling loop"; + emitPlayerState();return; + } + const auto cue=playerTrackSettings_[ + static_cast(playerCurrent_)]; + if(!armix::player::PlayerShowTransitionPolicy::validLoop( + cue.cueIn,cue.cueOut,playerFadeMilliseconds_)) { + playerError_="Set IN/OUT at least 1.5 seconds apart for Loop A-B"; + emitPlayerState();return; + } + playerLoopCurrent_=true; + playerError_.clear(); + emitPlayerState();return; + } + if(action=="playerCueIn" || action=="playerCueOut" || + action=="playerCueClear" || action=="playerCueGoIn") { + if(playerCurrent_<0 || playerCurrent_>= + static_cast(playerTrackSettings_.size()) || + playerSelected_!=playerCurrent_) { + playerError_="Select the playing song to edit its cue"; + emitPlayerState();return; + } + auto& cues=playerTrackSettings_[static_cast( + playerCurrent_)]; + const auto transport=engine_.playerStatus(); + const double now=static_cast( + transport.getProperty("currentSeconds",0.0)); + const double total=static_cast( + transport.getProperty("durationSeconds",0.0)); + if(action=="playerCueGoIn") { + if(!engine_.playerSeekSeconds(cues.cueIn)) + playerError_="Unable to jump to song IN marker"; + 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) { + 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)) { + playerError_="Could not update native song markers"; + emitPlayerState();return; + } + if(playerLoopCurrent_ && + !armix::player::PlayerShowTransitionPolicy::validLoop( + cues.cueIn,cues.cueOut,playerFadeMilliseconds_)) + playerLoopCurrent_=false; + playerError_.clear();persistPlayerLibrary(); + emitPlayerState(true);return; + } if(action=="playerPlay")return playTransportMusic(); + if(action=="playerSeek") { + const double seconds=static_cast(value); + const double total=static_cast( + engine_.playerStatus().getProperty("durationSeconds",0.0)); + if(std::isfinite(seconds) && seconds>=0. && + std::isfinite(total) && total>0. && seconds<=total && + engine_.playerSeekSeconds(seconds)) { + playerError_.clear(); + } else playerError_="Seek unavailable for this song"; + emitPlayerState();return; + } if(action=="playerPause") { + playerAutoAdvanceGate_.rearm(); + playerPendingQueueFile_={}; + playerPendingIndex_=-1; engine_.playerPause();emitPlayerState();return; } if(action=="playerStop") { + playerAutoAdvanceGate_.rearm(); + playerLoopCurrent_=false; playerOutputPendingIndex_=-1; + playerPendingQueueFile_={}; + playerPendingIndex_=-1; engine_.playerStop();emitPlayerState();return; } - if(action=="playerNext")return playNextMusic(); + if(action=="playerNext") { + playerAutoAdvanceGate_.rearm(); // explicit user retry + return playNextMusic(); + } if(action=="playerAutoNext") { + playerAutoAdvanceGate_.rearm(); playerAutoNext_=value.isBool() && static_cast(value); persistPlayerLibrary();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(playerLoopCurrent_ && playerCurrent_>=0 && + playerCurrent_(playerTrackSettings_.size())) { + const auto cue=playerTrackSettings_[ + static_cast(playerCurrent_)]; + if(!armix::player::PlayerShowTransitionPolicy::validLoop( + cue.cueIn,cue.cueOut,ms)) + playerLoopCurrent_=false; + } + persistPlayerLibrary();emitPlayerState();return; + } if(action=="playerSelect" || action=="playerPlayNow") { const int i=static_cast(value); if(i>=0 && i(playerLibrary_.size())) { if(i!=playerSelected_)playerOutputPendingIndex_=-1; + if(i!=playerSelected_ || action=="playerPlayNow") + playerAutoAdvanceGate_.rearm(); playerSelected_=i; if(action=="playerPlayNow")playSelectedMusic(); - else emitPlayerState(true); + else { + // Selecting NEXT never alters CURRENT. Idle standby + // decode starts now so the performer can advance later + // with an already-buffered next song. + const auto state=engine_.playerStatus().getProperty( + "state","").toString(); + if(i!=playerCurrent_ && playerPendingIndex_<0 && + playerCurrent_>=0 && state=="PLAYING") { + const auto settings=playerTrackSettings_[ + static_cast(i)]; + (void)engine_.preloadPlayerMusic( + playerLibrary_[static_cast(i)], + settings.key,settings.tempo, + settings.cueIn,settings.cueOut); + } + emitPlayerState(true); + } } return; } @@ -7118,8 +7641,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } } - if (!browser_.loaded) return; - if (!initialStateSent_) + // A hidden/reloading WebView MUST NOT suspend the native player's + // control-thread ACK, Auto Next, or A-B loop. Browser events are + // optional observers; JUCE transport is the authority. + if (browser_.loaded && !initialStateSent_) { initialStateSent_ = true; emitCatalog(); @@ -7128,21 +7653,140 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr emitPresets(); emitPlayerState(true); } - if (catalog_.busy() && timerTicks_ % 3 == 0) + if (browser_.loaded && catalog_.busy() && timerTicks_ % 3 == 0) emitScanProgress(); - if(timerTicks_%3==0) { + // Run transport deadlines at 12 Hz only while necessary. The + // browser still receives lightweight state at its old 4 Hz pace. + if(timerTicks_%3==0 || playerAutoNext_ || + playerLoopCurrent_ || playerPendingIndex_>=0) { + // Start only a genuinely prepared NEXT and ACK the row identity + // in the same UI-owner thread. No session/graph mutation here. + if(engine_.servicePlayerTransition()) { + // A native ACK is a NEW logical song/loop epoch even if + // standby A/B happen to publish the same generation. + playerAutoAdvanceGate_.rearm(); + if(playerPendingIndex_>=0 && + playerPendingIndex_(playerLibrary_.size())) { + playerCurrent_=playerPendingIndex_; + playerSelected_=playerCurrent_; + if(playerPendingQueueFile_!=juce::File{}) + (void)armix::player::PlayerShowTransitionPolicy:: + commitQueuedFront(playerQueue_, + playerPendingQueueFile_); + } + playerPendingQueueFile_={}; + playerPendingIndex_=-1; + playerError_.clear(); + emitPlayerState(true); + } else if(playerPendingIndex_>=0 && + engine_.playerTransitionFailed()) { + // Preserve queued entry on decode error: the performer can + // retry. A failed NEXT must not consume the user's setlist. + playerPendingQueueFile_={}; + playerPendingIndex_=-1; + playerError_="NEXT could not decode; current song is unchanged"; + emitPlayerState(true); + } const auto transport=engine_.playerStatus(); - if(playerAutoNext_ && - transport.getProperty("state","").toString()=="ENDED") { - const auto generation=static_cast( - transport.getProperty("generation","0").toString().getLargeIntValue()); - if(generation!=lastAutoAdvanceGeneration_) { - lastAutoAdvanceGeneration_=generation; + const auto phase=transport.getProperty( + "state","").toString(); + const bool fading=static_cast( + transport.getProperty("crossfading",false)); + const bool preparing=static_cast( + transport.getProperty("transitionPending",false)); + const bool activeCurrent=playerCurrent_>=0 && + playerCurrent_(playerLibrary_.size()); + int queued=-1; + if(!playerQueue_.empty()) { + const auto found=std::find(playerLibrary_.begin(), + playerLibrary_.end(),playerQueue_.front()); + if(found!=playerLibrary_.end()) + queued=static_cast(found-playerLibrary_.begin()); + } + const int upcoming=activeCurrent? + armix::player::PlayerShowTransitionPolicy::nextIndex( + playerCurrent_,playerSelected_, + static_cast(playerLibrary_.size()), + queued):-1; + // Rehearsal loop has priority over Auto Next and queued + // songs, which remain untouched until the operator presses Next. + // Reuse the exact M3 standby worker for a click-safe A-B return; + // never seek inside the hardware callback. + if(playerLoopCurrent_ && activeCurrent && + phase=="PLAYING" && !fading && !preparing && + playerPendingIndex_<0) { + const auto loop=playerTrackSettings_[ + static_cast(playerCurrent_)]; + if(armix::player::PlayerShowTransitionPolicy::validLoop( + loop.cueIn,loop.cueOut,playerFadeMilliseconds_)) { + const auto currentFile=playerLibrary_[ + static_cast(playerCurrent_)]; + (void)engine_.preloadPlayerMusic(currentFile, + loop.key,loop.tempo,loop.cueIn,loop.cueOut); + const auto position=static_cast( + transport.getProperty("currentSeconds",0.0)); + const auto duration=static_cast( + transport.getProperty("durationSeconds",0.0)); + const int fade=std::max(40,playerFadeMilliseconds_); + // The in-flight transition is the only loop latch: + // alternating A/B decoders can share generation IDs. + // On failure, turn looping off below (no retry storm). + if(armix::player::PlayerShowTransitionPolicy:: + armBeforeEnd(position,duration,fade,0.085,loop.tempo)) { + if(engine_.queuePlayerTransition(currentFile, + loop.key,loop.tempo,fade,loop.cueIn,loop.cueOut)) { + playerPendingIndex_=playerCurrent_; + playerPendingQueueFile_={}; + playerError_.clear(); + } else { + playerError_="Loop standby failed; original music remains"; + playerLoopCurrent_=false; + } + } + } else playerLoopCurrent_=false; + } + // Queue is explicit operator intent: warm NEXT even while Auto + // Next is OFF. Auto alone may prepare the following setlist row. + if(!playerLoopCurrent_ && (playerAutoNext_ || queued>=0) && + phase=="PLAYING" && !fading && !preparing && + playerPendingIndex_<0 && upcoming>=0 && + (upcoming!=playerCurrent_ || queued>=0)) { + const auto preset=playerTrackSettings_[ + static_cast(upcoming)]; + (void)engine_.preloadPlayerMusic( + playerLibrary_[static_cast(upcoming)], + preset.key,preset.tempo, + preset.cueIn,preset.cueOut); + } + if(playerAutoNext_ && !playerLoopCurrent_ && activeCurrent && + !fading && !preparing && playerPendingIndex_<0 && + upcoming>=0 && + (upcoming!=playerCurrent_ || queued>=0) && + (phase=="PLAYING" || phase=="ENDED")) { + // CUT is an end-only switch. Positive fade begins before + // EOF, bounded by media remaining + one 12 Hz timer tick. + // Failure latches until a user gesture; successful native + // ACK rearms the gate for the NEXT logical song, including + // consecutive repeats of exactly the same media file. + const double position=static_cast( + transport.getProperty("currentSeconds",0.0)); + const double duration=static_cast( + transport.getProperty("durationSeconds",0.0)); + const bool preEnd=playerFadeMilliseconds_>0 && + armix::player::PlayerShowTransitionPolicy::armBeforeEnd( + position,duration,playerFadeMilliseconds_,0.085, + static_cast(transport.getProperty( + "tempoPercent",100))); + if((preEnd || phase=="ENDED") && + playerAutoAdvanceGate_.claim()) { playNextMusic(); } } - emitPlayerState(); + if(browser_.loaded && timerTicks_%3==0)emitPlayerState(); } + // Only UI/status publication depends on WebView availability. + // No native playback continuity, cleanup or next-song ACK does. + if(!browser_.loaded)return; const double statusStart = timing ? juce::Time::getMillisecondCounterHiRes() : 0.0; auto state = engine_.status(); if (timing) diff --git a/tests/player_crossfade_curve_test.cpp b/tests/player_crossfade_curve_test.cpp new file mode 100644 index 000000000..57a81f9c9 --- /dev/null +++ b/tests/player_crossfade_curve_test.cpp @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/player/PlayerCrossfadeCurve.h" +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +using Curve=armix::player::PlayerCrossfadeCurve; +int main() { + const Curve curve; + for(int total: {1,2,64,4320,24000,144000}) { + const auto begin=curve.gains(0,total),end=curve.gains(total,total); + assert(begin.oldGain==1.f && begin.newGain==0.f); + assert(std::abs(end.oldGain)<0.00001f && + std::abs(end.newGain-1.f)<0.00001f); + float previousOld=1.f,previousNew=0.f; + for(int pos=0;pos<=total;++pos) { + const auto g=curve.gains(pos,total); + assert(std::isfinite(g.oldGain)&&std::isfinite(g.newGain)); + assert(g.oldGain<=previousOld+1e-6f); + assert(g.newGain>=previousNew-1e-6f); + assert(g.oldGain>=-1e-6f && g.newGain>=0.f); + assert(std::abs(g.oldGain*g.oldGain+ + g.newGain*g.newGain-1.f)<0.002f); + previousOld=g.oldGain;previousNew=g.newGain; + } + assert(curve.gains(total*2,total).newGain==1.f); + } + const auto midpoint=curve.gains(500,1000); + assert(std::abs(midpoint.oldGain-0.7071f)<0.004f); + assert(std::abs(midpoint.newGain-0.7071f)<0.004f); + std::puts("M3: bounded equal-power curve, endpoints and finite gain PASS"); +} diff --git a/tests/player_native_decode_test.cpp b/tests/player_native_decode_test.cpp index 2ad6da31d..1367c0e2c 100644 --- a/tests/player_native_decode_test.cpp +++ b/tests/player_native_decode_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/player/NativePlayerDeck.h" +#include "../engine/player/NativePlayerShowDeck.h" #include "../engine/player/PlayerSetlistPolicy.h" #include "../engine/player/PlayerLibraryPolicy.h" #ifdef NDEBUG @@ -306,6 +307,195 @@ int main() { changeDuringPlayback(0,100); // normal 0/100 passthrough restored assert(player.snapshot().played>original.played); } // ensure native decoder closes the file before Windows deletion + // Relinking an edited/shorter file must reject a stale IN marker, + // not play a misleading 1-sample tail as if music were valid. + { + armix::player::NativePlayerDeck badCue; + badCue.deviceRate(48000.0); + assert(badCue.setCueRange(9.0,0.0)); // valid metadata, not this WAV + badCue.load(longFile,true); // genuine file is 8 seconds + bool rejected=false; + for(int i=0;i<600;++i) { + const auto state=badCue.snapshot(); + if(state.state==armix::player::NativePlayerDeck::State::error) { + assert(state.error.containsIgnoreCase("IN marker")); + rejected=true;break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(rejected && !badCue.snapshot().outputReady); + assert(badCue.setCueRange(1.0,4.0)); + badCue.load(longFile,true); + bool recovered=false; + for(int i=0;i<600;++i) { + if(badCue.isPlayingRequested()){recovered=true;break;} + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(recovered); + badCue.stop(); + } + // M2: genuine JUCE WAV -> resampler -> generation-fenced seek, + // with progressive waveform indexed ONLY during decoding. + { + armix::player::NativePlayerDeck seekDeck; + seekDeck.deviceRate(48000.0); + seekDeck.load(longFile,true); + for(int attempt=0;attempt<600 && !seekDeck.isPlayingRequested();++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + assert(seekDeck.isPlayingRequested()); + std::array l{},r{}; + for(int i=0;i<12;++i)seekDeck.pull(l.data(),r.data(),512); + const auto beforeSeek=seekDeck.snapshot(); + assert(beforeSeek.played>0); + assert(seekDeck.seekSeconds(3.25)); + bool seekReady=false; + for(int i=0;i<600;++i) { + const auto state=seekDeck.snapshot(); + if(state.outputReady && + state.played>static_cast(3*48000)) { + seekReady=true;break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(seekReady); + seekDeck.pull(l.data(),r.data(),512); + const auto afterSeek=seekDeck.snapshot(); + assert(afterSeek.played>static_cast(3*48000)); + int waveformEvidence=0; + for(const auto value:afterSeek.waveform) + if(value>1000)++waveformEvidence; + assert(waveformEvidence>0); + for(int i=0;i<512;++i) + assert(std::isfinite(l[i]) && std::isfinite(r[i])); + seekDeck.stop(); + } + // M3: preloaded B comes from a SECOND DECODER WORKER, yet A and B + // merge as ONE existing PLAYER A stereo PCM signal. No second + // hardware callback, device, browser track or routing authority. + { + armix::player::NativePlayerShowDeck show; + show.deviceRate(48000.0); + show.load(longFile,true); + for(int attempt=0;attempt<600 && !show.isPlayingRequested();++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + assert(show.isPlayingRequested()); + assert(show.preload(file,0,100)); + std::array left{},right{}; + bool queued=false; + for(int i=0;i<600;++i) { + if(i==0) { + assert(show.queueTransition(file,0,100,180)); + } + if(show.service()){queued=true;break;} + show.pull(left.data(),right.data(),256); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(queued && show.transitionActive()); + bool heardSound=false; + for(int i=0;i<70;++i) { + show.pull(left.data(),right.data(),256); + for(int n=0;n<256;++n) { + assert(std::isfinite(left[n]) && std::isfinite(right[n])); + if(std::abs(left[n])>0.01f)heardSound=true; + } + } + assert(heardSound && !show.transitionActive()); + show.service(); // retire old decoder off realtime + assert(show.snapshot().title==file.getFileNameWithoutExtension()); + show.deviceRate(0.0); + assert(!show.isPlayingRequested()); + } + // M2 + M3 real PCM: A-B rehearsal uses TWO decoder instances + // of the SAME file, fades between them without a callback seek, + // preserves original media clock, and cancels NEXT on STOP. + { + armix::player::NativePlayerShowDeck loop; + loop.deviceRate(48000.0); + assert(loop.setCueRange(1.0,4.0)); + loop.load(longFile,true); + bool ready=false; + for(int i=0;i<600;++i) { + if(loop.isPlayingRequested()){ready=true;break;} + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(ready); + const auto first=loop.snapshot(); + assert(first.mediaPlayed>=48000); // cue IN, not zero + std::array left{},right{}; + // Deliberately do NOT call service() between fades: a live + // operator may queue NEXT immediately on callback completion. + // preload() must retire the old decoder before reusing it. + for(int pass=0;pass<4;++pass) { + assert(loop.preload(longFile,0,100,1.,4.)); + assert(loop.queueTransition(longFile,0,100,180,1.,4.)); + bool started=false; + for(int tries=0;tries<600;++tries) { + if(loop.service()){started=true;break;} + loop.pull(left.data(),right.data(),256); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(started && loop.transitionActive()); + double energy=0.; + for(int b=0;b<50;++b) { + loop.pull(left.data(),right.data(),256); + for(int i=0;i<256;++i) { + assert(std::isfinite(left[i]) && + std::isfinite(right[i])); + energy+=left[i]*left[i]; + } + } + assert(energy>0.01); + assert(!loop.transitionActive()); + const auto now=loop.snapshot(); + assert(now.mediaPlayed>=48000); + assert(now.mediaDuration<=4*48000+1); + assert(now.title==longFile.getFileNameWithoutExtension()); + } + // A user STOP during standby must prevent any stale queue from + // becoming a different current after the decoder completes. + assert(loop.queueTransition(longFile,0,100,180,1.,4.)); + assert(loop.transitionPending()); + loop.stop(); + assert(!loop.transitionPending()); + assert(!loop.isPlayingRequested()); + loop.pull(left.data(),right.data(),256); + for(int i=0;i<256;++i) + assert(left[i]==0.f && right[i]==0.f); + // Restart across 96 -> disconnected -> 44.1 kHz. Pending + // standby PCM must not leak into the next hardware epoch, + // and device reopen itself must NEVER auto-play into MAIN. + loop.deviceRate(96000.0); + loop.load(longFile,true); + bool warm96=false; + for(int i=0;i<600;++i) { + if(loop.isPlayingRequested()){warm96=true;break;} + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(warm96); + assert(loop.queueTransition(longFile,0,100,500,1.,4.)); + assert(loop.transitionPending()); + loop.deviceRate(0.0); + assert(!loop.transitionPending()); + assert(!loop.transitionActive()); + assert(!loop.isPlayingRequested()); + loop.deviceRate(44100.0); + bool ready44=false; + for(int i=0;i<600;++i) { + if(loop.snapshot().outputReady){ready44=true;break;} + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + assert(ready44); + assert(!loop.isPlayingRequested()); // explicit Play required + loop.pull(left.data(),right.data(),256); + for(int i=0;i<256;++i) + assert(left[i]==0.f && right[i]==0.f); + loop.play(); + assert(loop.isPlayingRequested()); + loop.pull(left.data(),right.data(),256); + for(int i=0;i<256;++i) + assert(std::isfinite(left[i]) && std::isfinite(right[i])); + loop.stop(); + } assert(longFile.deleteFile()); } assert(file.deleteFile()); diff --git a/tests/player_show_edit_policy_test.cpp b/tests/player_show_edit_policy_test.cpp new file mode 100644 index 000000000..1afb2f967 --- /dev/null +++ b/tests/player_show_edit_policy_test.cpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/player/PlayerShowEditPolicy.h" +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +using P=armix::player::PlayerShowEditPolicy; +int main() { + // Every surviving song ID must continue to point to the same + // logical song after dragging a setlist row in either direction. + for(int count=1;count<=32;++count)for(int from=0;from songs(count); + std::iota(songs.begin(),songs.end(),0); + const auto moved=songs[static_cast(from)]; + songs.erase(songs.begin()+from); + songs.insert(songs.begin()+to,moved); + for(int old=0;old=0 && remap(remap)]==old); + } + } + for(int count=1;count<=64;++count)for(int index=0;index=0 && mapped +#include +#include +#include +#include +#include +using P=armix::player::PlayerShowTransitionPolicy; +int main() { + // Distinct A/B decoder instances can both report generation 2. + // The logical Auto Next gate must rearm on actual transition ACK, + // not an XOR of generation/current/selected indices. + armix::player::PlayerAutoAdvanceGate autoNext; + assert(!autoNext.claimed()); + for(int pass=0;pass<7;++pass) { + assert(autoNext.claim()); // enqueue next repeat + assert(autoNext.claimed()); + assert(!autoNext.claim()); // pending/failure does not spin + // Real native ACK: NEXT is now CURRENT and may use the very + // same file, index and per-decoder generation as the last pass. + autoNext.rearm(); + } + assert(autoNext.claim()); + assert(!autoNext.claim()); // error remains latched + autoNext.rearm(); // explicit operator retry + assert(autoNext.claim()); + // Explicit queue wins; manual-selected NEXT wins over default row; + // sequential only after the operator does not designate another song. + assert(P::nextIndex(3,8,10,2)==2); + assert(P::nextIndex(3,8,10,-1)==8); + assert(P::nextIndex(3,3,10,-1)==4); + assert(P::nextIndex(9,9,10,-1)==-1); + assert(P::nextIndex(4,4,10,4)==4); // intentional repeat CURRENT + assert(P::nextIndex(-1,-1,10,-1)==0); + assert(P::nextIndex(-1,2,10,-1)==2); + assert(P::nextIndex(0,0,0,-1)==-1); + assert(P::nextIndex(0,0,10,999)==1); + // A 500ms crossfade must start shortly before the end, never at + // arbitrary mid-song positions and never when time is invalid. + assert(!P::armBeforeEnd(60.,120.,500,.085)); + assert(!P::armBeforeEnd(119.3,120.,500,.085)); + assert(P::armBeforeEnd(119.5,120.,500,.085)); + assert(P::armBeforeEnd(120.,120.,500,.085)); + assert(!P::armBeforeEnd(121.,120.,500,.085)); + assert(P::armBeforeEnd(119.999,120.,0,.085)); + assert(!P::armBeforeEnd(-1.,120.,500,.085)); + assert(!P::armBeforeEnd(10.,0.,500,.085)); + assert(!P::armBeforeEnd(std::numeric_limits::quiet_NaN(),120.,500,.085)); + assert(!P::armBeforeEnd(10.,std::numeric_limits::infinity(),500,.085)); + assert(!P::armBeforeEnd(10.,120.,3001,.085)); + assert(!P::armBeforeEnd(10.,120.,500,0.)); + // A source timeline is NOT the same as output time when tempo differs. + // At 120% the 500ms fade needs 600ms of source media; at 80% it + // needs only 400ms. Both retain an 85ms timer cushion. + assert(P::armBeforeEnd(119.45,120.,500,.085,120)); + assert(!P::armBeforeEnd(119.45,120.,500,.085,80)); + assert(P::armBeforeEnd(119.55,120.,500,.085,80)); + // 120% threshold is (0.500+0.085)*1.2=0.702 media seconds. + assert(!P::armBeforeEnd(119.2,120.,500,.085,120)); + assert(!P::armBeforeEnd(119.,120.,500,.085,75)); + assert(!P::armBeforeEnd(119.,120.,500,.085,125)); + // All public transition settings, 44.1/48/96k, simulated 12 Hz + // display cadence: never request a switch midway through a long song. + for(int fade: {0,180,500,1500})for(int hz: {44100,48000,96000}) { + const double duration=180.; + const double step=static_cast(512)/hz; + bool hit=false; + for(double sec=0.;sec::quiet_NaN(),180)); + // Reordering preserves duplicates and avoids accidental queue loss. + std::vector queue={"song-A","song-B","song-A","song-C"}; + assert(!P::moveQueued(queue,-1,2)); + assert(!P::moveQueued(queue,0,4)); + assert(!P::moveQueued(queue,1,1)); + assert(P::moveQueued(queue,2,0)); + assert((queue==std::vector{"song-A","song-A","song-B","song-C"})); + // A failed decode must NOT consume the queue; commit occurs only on + // actual native acknowledged track switch and the same queue head. + assert(!P::commitQueuedFront(queue,std::string("song-C"))); + assert(queue.size()==4); + assert(P::commitQueuedFront(queue,std::string("song-A"))); + assert(queue.size()==3 && queue.front()=="song-A"); + assert(P::commitQueuedFront(queue,std::string("song-A"))); + assert(queue.size()==2 && queue.front()=="song-B"); + assert(!P::commitQueuedFront(queue,std::string("song-A"))); + assert(P::commitQueuedFront(queue,std::string("song-B"))); + assert(P::commitQueuedFront(queue,std::string("song-C"))); + assert(queue.empty() && !P::commitQueuedFront(queue,std::string("song-C"))); + std::puts("M1/M3 PASS: queued identity, repeat, reorder, commit-on-ACK, pre-end crossfade deadlines"); +} diff --git a/tests/player_transport_lifecycle_contract.test.mjs b/tests/player_transport_lifecycle_contract.test.mjs new file mode 100644 index 000000000..8b9b79aaa --- /dev/null +++ b/tests/player_transport_lifecycle_contract.test.mjs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Fast source-lifecycle guard: playback must not be owned by WebView state. +// JUCE native decoder behaviour is checked by player_native_decode_test.cpp. +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; + +const source=readFileSync('src/Main.cpp','utf8'); +const begin=source.indexOf( + '// A hidden/reloading WebView MUST NOT suspend the native player'); +const after=source.indexOf('const double statusStart = timing ?',begin); +assert.ok(begin>0 && after>begin,'live player timer boundary missing'); +const timer=source.slice(begin,after); +const service=timer.indexOf('engine_.servicePlayerTransition()'); +const next=timer.indexOf('const bool preEnd=playerFadeMilliseconds_>0'); +const loop=timer.indexOf('if(playerLoopCurrent_ && activeCurrent'); +const uiGate=timer.indexOf('if(!browser_.loaded)return;'); +assert.match(timer,/playerLoopCurrent_ \|\| playerPendingIndex_>=0/, + 'A-B must be serviced at 12 Hz when Auto Next is off'); +assert.ok(service>=0 && next>service && loop>service, + 'native transport must be maintained on JUCE control timer'); +assert.ok(uiGate>next && uiGate>loop, + 'WebView availability must gate ONLY UI publishing, not native ACK/loop/NEXT'); +assert.match(timer,/if \(browser_\.loaded && !initialStateSent_\)/); +assert.match(timer,/if\(browser_\.loaded && timerTicks_%3==0\)emitPlayerState\(\)/); +assert.doesNotMatch(timer,/lastLoopAttemptGeneration_/, + 'same-generation A/B decks must never suppress second A-B loop'); +console.log('M4 PASS: transport, Loop A-B and NEXT survive WebView unload/reload'); diff --git a/tests/player_waveform_index_test.cpp b/tests/player_waveform_index_test.cpp new file mode 100644 index 000000000..c242164b8 --- /dev/null +++ b/tests/player_waveform_index_test.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/player/PlayerWaveformIndex.h" +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include +using W=armix::player::PlayerWaveformIndex; +int main() { + W index; + std::array left{},right{}; + for(int i=0;i<1024;++i){ + left[static_cast(i)]= + i%4==0?.85f:.12f; + right[static_cast(i)]=-.35f; + } + index.observe(left.data(),right.data(),1024,0); + for(auto v:index.snapshot())assert(v==0); // no source yet + index.reset(4096); + std::atomic done{false}; + std::thread worker([&]{ + for(int offset=0;offset<4096;offset+=1024) + index.observe(left.data(),right.data(),1024, + static_cast(offset)); + done.store(true,std::memory_order_release); + }); + do { + const auto bins=index.snapshot(); + for(auto value:bins)assert(value<=65535); + }while(!done.load(std::memory_order_acquire)); + worker.join(); + const auto bins=index.snapshot(); + const auto expected=static_cast(.85f*65535); + int hits=0; + for(const auto value:bins){ + if(value>expected-10&&value220); // every part of the entire song was indexed + index.reset(48000); + for(const auto value:index.snapshot())assert(value==0); + left[0]=NAN;right[0]=NAN; + index.observe(left.data(),right.data(),1,0); + assert(index.snapshot()[0]==0); // corrupt media never emits NaN + std::puts("M2: bounded progressive waveform, finite peaks, reset and thread-safe snapshots PASS"); +}