-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProDJLinkView.h
More file actions
2648 lines (2387 loc) · 117 KB
/
ProDJLinkView.h
File metadata and controls
2648 lines (2387 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
//
// ProDJLinkView -- External window showing global Pro DJ Link network state.
//
// Displays all 4 CDJ decks with:
// - Album artwork (from DbServerClient cache)
// - Color waveform with playhead cursor
// - Track info (artist, title, key)
// - BPM, pitch %, play state
// - Raw timecode from playhead
// - TrackMap offset (if mapped)
// - Engine assignment (which STC engine is monitoring this player)
// - On-air / master / beat indicators
// - DJM mixer fader + crossfader visualization
//
// Architecture: Owns its own 60Hz Timer, reads data from shared objects
// (ProDJLinkInput, DbServerClient, TrackMap, engines) via const getters.
// Actively requests metadata from DbServerClient for all discovered
// players (independently of engine assignments) so waveform, artwork,
// and track info load regardless of which players have engines.
#pragma once
#include <JuceHeader.h>
#include "ProDJLinkInput.h"
#include "DbServerClient.h"
#include "MediaDisplay.h"
#include "WaveformDetailDisplay.h"
#include "TimecodeEngine.h"
#include "AppSettings.h"
#include "CustomLookAndFeel.h"
#include <vector>
#include <memory>
//==============================================================================
// ProDJLinkViewComponent -- Main content: 4 deck panels + mixer strip
//==============================================================================
class ProDJLinkViewComponent : public juce::Component,
public juce::Timer
{
public:
ProDJLinkViewComponent(ProDJLinkInput& pdl,
DbServerClient& db,
TrackMap& tmap,
std::vector<std::unique_ptr<TimecodeEngine>>& engs)
: proDJLink(pdl), dbClient(db), trackMap(tmap), engines(engs)
{
setSize(900, 680);
// --- Toolbar buttons ---
addAndMakeVisible(btnLayout);
btnLayout.setButtonText("4x1");
btnLayout.setColour(juce::TextButton::buttonColourId, bgDeck);
btnLayout.setColour(juce::TextButton::textColourOffId, textMid);
btnLayout.setClickingTogglesState(false);
btnLayout.onClick = [this]
{
layoutHorizontal = !layoutHorizontal;
btnLayout.setButtonText(layoutHorizontal ? "2x2" : "4x1");
resized();
repaint();
if (onLayoutChanged) onLayoutChanged();
};
addAndMakeVisible(btnShowMixer);
btnShowMixer.setButtonText("DJM");
btnShowMixer.setClickingTogglesState(true);
btnShowMixer.setToggleState(true, juce::dontSendNotification);
btnShowMixer.setColour(juce::ToggleButton::textColourId, textMid);
btnShowMixer.setColour(juce::ToggleButton::tickColourId, accentCyan);
btnShowMixer.onClick = [this]
{
showMixer = btnShowMixer.getToggleState();
resized();
repaint();
if (onLayoutChanged) onLayoutChanged();
};
startTimerHz(60);
}
~ProDJLinkViewComponent() override
{
stopTimer();
}
// Called when BPM multiplier is saved to TrackMap via double-click.
// Wire this to save settings and refresh engine lookups.
std::function<void()> onTrackMapChanged;
/// Callback to check if Show Lock is active. If set and returns true,
/// TrackMap writes (BPM mult double-click) are blocked.
std::function<bool()> isShowLockedFn;
// Called when layout or mixer visibility changes (for settings persistence)
std::function<void()> onLayoutChanged;
void setLayoutHorizontal(bool h)
{
layoutHorizontal = h;
btnLayout.setButtonText(layoutHorizontal ? "2x2" : "4x1");
resized(); repaint();
}
void setShowMixer(bool m)
{
showMixer = m;
btnShowMixer.setToggleState(m, juce::dontSendNotification);
resized(); repaint();
}
bool getLayoutHorizontal() const { return layoutHorizontal; }
bool getShowMixer() const { return showMixer; }
private:
//==========================================================================
// Per-deck state cache (updated every timer tick)
//==========================================================================
struct DeckState
{
bool discovered = false;
juce::String model, ip, playState, posSource;
juce::String artist, title, key, offset;
double bpm = 0.0, faderPitch = 1.0;
bool isOnAir = false, isMaster = false, isPlaying = false, isReverse = false, trackMapped = false;
uint8_t beatInBar = 0;
uint8_t xfAssign = 0; // 0=THRU, 1=A, 2=B (from DJM mixer data)
uint32_t playheadMs = 0, trackLenSec = 0, trackId = 0;
uint32_t artworkId = 0;
int cueCount = 0; // rekordbox cue/hot cue/loop count
float posRatio = 0.0f;
juce::String fpsStr;
Timecode timecode {};
Timecode offsetTimecode {}; // timecode with TrackMap offset applied (running clock)
juce::StringArray engineNames;
// Per-deck waveform component (painted LIVE by paintDeck).
// NOT a child component -- paint() is called manually with translated Graphics.
WaveformDisplay waveform;
WaveformDetailDisplay detailWaveform;
juce::Rectangle<int> wfLocalBounds; // waveform area relative to deck (set during paintDeckStatic)
juce::Rectangle<int> detailLocalBounds; // detail waveform area relative to deck
uint32_t displayedDetailTrackId = 0;
int detailRetryTicks = 0; // countdown for supplementary data retry
// Fed-tracking: avoid redundant full metadata copies during retry
bool previewCuesFed = false, previewBeatGridFed = false;
int previewRetryTicks = 0; // countdown for preview supplementary data
bool detailCuesFed = false, detailBeatGridFed = false, detailSongStructFed = false;
uint32_t lastMetaVersion = 0; // tracks DbServerClient cache version to skip redundant copies
uint32_t lastDetailVersion = 0; // separate version tracker for detail waveform section
juce::Rectangle<int> tcLocalBounds; // timecode row relative to deck (set during paintDeckStatic)
juce::Rectangle<int> mapLocalBounds; // offset timecode row relative to deck
juce::Rectangle<int> timeLocalBounds; // track time row relative to deck (for click-to-toggle)
bool showRemainingTime = false; // false=elapsed, true=remaining (per deck)
juce::Image cachedArtworkImg; // cached from DbServerClient (avoid lock during paint)
uint32_t displayedWaveformTrackId = 0;
uint32_t displayedArtworkId = 0;
uint32_t prevTrackId = 0;
bool metadataRequested = false; // true once we've sent a dbserver request for this track
int metadataRequestTick = 0; // tick counter for retry after ~3s
// Cached deck image -- Windows only (GDI benefits from caching).
// On macOS, painting directly preserves CoreGraphics subpixel AA.
#if JUCE_WINDOWS
juce::Image cachedDeckImg;
int cachedDeckW = 0, cachedDeckH = 0;
float cachedDeckScale = 0.0f;
bool deckImgValid = false;
void invalidateDeckImg() { deckImgValid = false; }
#else
void invalidateDeckImg() { } // no-op on macOS (no cache)
#endif
// BPM multiplier state (updated each tick from engine + TrackMap)
int bpmSessionOverride = TimecodeEngine::kBpmNoOverride; // from engine: kBpmNoOverride=none, 0=1x, 1=x2...
int bpmTrackMapValue = 0; // from TrackMap entry: same encoding
// Cached button hit-test bounds (set during paint, used in mouseDown)
juce::Rectangle<int> bpmBtnBounds[5]; // order: /4 /2 1x x2 x4
// Per-deck double-click timing for BPM multiplier buttons
juce::int64 lastBpmClickMs = 0;
int lastBpmClickMult = -999;
// Snapshot of last-painted state -- used to skip repaint() when nothing changed
struct Snapshot
{
bool discovered = false, isOnAir = false, isMaster = false, isPlaying = false, isReverse = false, trackMapped = false;
uint8_t beatInBar = 0, xfAssign = 0;
double bpm = -1.0, faderPitch = -1.0;
uint32_t playheadMs = 0xFFFFFFFF, trackId = 0;
int bpmSessionOverride = -999, bpmTrackMapValue = -999;
juce::String playState, artist, title, posSource, fpsStr;
Timecode timecode {}, offsetTimecode {};
juce::StringArray engineNames;
} snapshot;
};
public:
// BPM multiplier button click handler with timing-based double-click detection.
// Single click: toggle session override (temporary, cleared on track change).
// Double click: persist to TrackMap (creates entry if track not mapped).
void mouseDown(const juce::MouseEvent& e) override
{
auto pos = e.getPosition();
for (int deck = 0; deck < 4; ++deck)
{
if (!deckBounds[deck].contains(pos)) continue;
auto& ds = deckState[deck];
int pn = deck + 1;
// Convert to deck-local coords (bpmBtnBounds are set in local space
// because paintDeckStatic receives {0,0,w,h} local coordinates)
auto localPos = pos - deckBounds[deck].getPosition();
static const int kBpmValues[5] = { -2, -1, 0, 1, 2 };
for (int bi = 0; bi < 5; ++bi)
{
if (!ds.bpmBtnBounds[bi].contains(localPos)) continue;
int clickedMult = kBpmValues[bi];
// Timing-based double-click detection (same approach as MainComponent)
auto now = (juce::int64)juce::Time::getMillisecondCounter();
bool isDouble = (clickedMult == ds.lastBpmClickMult
&& (now - ds.lastBpmClickMs) < 400);
ds.lastBpmClickMs = now;
ds.lastBpmClickMult = clickedMult;
if (isDouble)
{
// Double click: persist to TrackMap (toggle)
// Blocked during Show Lock -- TrackMap is configuration.
if (!isShowLockedFn || !isShowLockedFn())
saveBpmToTrackMap(pn, ds, clickedMult);
}
else
{
// Single click: set session override (skip if already effective)
for (auto& eng : engines)
{
if (eng->getActiveInput() == TimecodeEngine::InputSource::ProDJLink
&& eng->getEffectivePlayer() == pn)
{
if (eng->getEffectiveBpmMultiplier() == clickedMult)
break; // already active -- do nothing
eng->setBpmPlayerOverride(clickedMult);
break;
}
}
}
return;
}
// Detail waveform zoom buttons: click + / -
if (ds.detailWaveform.hasDetailData()
&& !ds.detailLocalBounds.isEmpty() && ds.detailLocalBounds.contains(localPos))
{
auto detLocal = localPos - ds.detailLocalBounds.getPosition();
int zoom = ds.detailWaveform.hitTestZoomButtons(detLocal);
if (zoom != 0)
{
int cur = ds.detailWaveform.getScale();
ds.detailWaveform.setScale(cur - zoom); // +1 = zoom in (less entries/px)
return;
}
}
// Track time area: click to toggle elapsed / remaining
if (!ds.timeLocalBounds.isEmpty() && ds.timeLocalBounds.contains(localPos))
{
ds.showRemainingTime = !ds.showRemainingTime;
ds.invalidateDeckImg();
repaint(deckBounds[deck]);
return;
}
break;
}
}
void mouseWheelMove(const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
{
auto pos = e.getPosition();
for (int deck = 0; deck < 4; ++deck)
{
if (!deckBounds[deck].contains(pos)) continue;
auto& ds = deckState[deck];
auto localPos = pos - deckBounds[deck].getPosition();
if (!ds.detailLocalBounds.isEmpty() && ds.detailLocalBounds.contains(localPos))
{
int cur = ds.detailWaveform.getScale();
if (wheel.deltaY > 0.0f)
ds.detailWaveform.setScale(cur - 1); // zoom in
else if (wheel.deltaY < 0.0f)
ds.detailWaveform.setScale(cur + 1); // zoom out
return;
}
break;
}
}
//--------------------------------------------------------------------------
// Persist BPM multiplier to TrackMap.
// Toggle logic: if TrackMap already has this value, clear it; else set it.
// After saving, session override is cleared (TrackMap = source of truth).
// Creates a new TrackMap entry if the track isn't mapped yet.
//--------------------------------------------------------------------------
void saveBpmToTrackMap(int playerNum, DeckState& ds, int clickedMult)
{
if (ds.title.isEmpty()) return;
int dur = (int)ds.trackLenSec;
auto* entry = trackMap.find(ds.artist, ds.title, dur);
if (!entry && dur > 0)
entry = trackMap.find(ds.artist, ds.title, 0);
if (!entry)
entry = trackMap.findIgnoringDuration(ds.artist, ds.title);
int currentMapValue = (entry != nullptr) ? entry->bpmMultiplier : 0;
// Double-click on 1x: clear saved value. Otherwise: save (no toggle).
int newValue;
if (clickedMult == 0)
newValue = 0; // 1x = clear
else if (clickedMult == currentMapValue)
return; // already saved, do nothing
else
newValue = clickedMult; // save new value
if (entry != nullptr)
{
entry->bpmMultiplier = newValue;
}
else if (newValue != 0)
{
TrackMapEntry newEntry;
newEntry.artist = ds.artist;
newEntry.title = ds.title;
newEntry.durationSec = dur;
newEntry.bpmMultiplier = newValue;
// Auto-populate cue points from rekordbox if available
if (ds.trackId != 0)
{
auto meta = dbClient.getCachedMetadataByTrackId(ds.trackId);
if (meta.isValid() && !meta.cueList.empty())
{
for (auto& rc : meta.cueList)
{
if (rc.positionMs == 0) continue;
CuePoint cp;
cp.positionMs = rc.positionMs;
auto letter = rc.hotCueLetter();
if (letter.isNotEmpty())
cp.name = letter;
if (rc.comment.isNotEmpty())
cp.name += cp.name.isNotEmpty()
? " " + rc.comment : rc.comment;
if (cp.name.isEmpty())
{
if (rc.type == TrackMetadata::RekordboxCue::MemoryPoint)
cp.name = "MEM";
else if (rc.type == TrackMetadata::RekordboxCue::Loop)
cp.name = "LOOP";
}
newEntry.cuePoints.push_back(std::move(cp));
}
newEntry.sortCuePoints();
}
}
trackMap.addOrUpdate(newEntry);
}
else
{
return; // no entry and clearing to 0 = nothing to do
}
// Clear session override: TrackMap is now the source of truth.
// Update engine's cachedBpmMultiplier so it takes effect immediately.
for (auto& eng : engines)
{
if (eng->getActiveInput() == TimecodeEngine::InputSource::ProDJLink
&& eng->getEffectivePlayer() == playerNum)
{
eng->setBpmPlayerOverride(TimecodeEngine::kBpmNoOverride);
eng->setCachedBpmMultiplier(newValue);
break;
}
}
if (onTrackMapChanged) onTrackMapChanged();
}
//==========================================================================
void paint(juce::Graphics& g) override
{
g.fillAll(bgMain);
}
void resized() override
{
auto bounds = getLocalBounds().reduced(6);
if (bounds.getWidth() < 50 || bounds.getHeight() < 50) return;
for (auto& ds : deckState)
ds.invalidateDeckImg();
// --- Toolbar (top) ---
auto toolbar = bounds.removeFromTop(22);
btnLayout.setBounds(toolbar.removeFromLeft(40));
toolbar.removeFromLeft(6);
btnShowMixer.setBounds(toolbar.removeFromLeft(60));
bounds.removeFromTop(4);
// --- Mixer panel (right side, conditional) ---
if (showMixer && bounds.getWidth() > 300)
{
int mixerW = juce::jlimit(200, 280, bounds.getWidth() / 5);
bounds.removeFromRight(4);
mixerBounds = bounds.removeFromRight(mixerW);
}
else
{
mixerBounds = {};
}
// --- Deck layout ---
int gapH = 4, gapV = 4;
if (layoutHorizontal)
{
// 4x1: four decks side by side, evenly distributed
int totalDeckW = juce::jmax(0, bounds.getWidth() - gapH * 3);
for (int i = 0; i < 4; ++i)
{
int w = totalDeckW * (i + 1) / 4 - totalDeckW * i / 4;
deckBounds[i] = bounds.removeFromLeft(w);
if (i < 3) bounds.removeFromLeft(gapH);
}
}
else
{
// 2x2 grid
int deckW = juce::jmax(0, (bounds.getWidth() - gapH) / 2);
int deckH = juce::jmax(0, (bounds.getHeight() - gapV) / 2);
auto topRow = bounds.removeFromTop(deckH);
bounds.removeFromTop(gapV);
auto bottomRow = bounds;
deckBounds[0] = topRow.removeFromLeft(deckW);
topRow.removeFromLeft(gapH);
deckBounds[1] = topRow;
deckBounds[2] = bottomRow.removeFromLeft(deckW);
bottomRow.removeFromLeft(gapH);
deckBounds[3] = bottomRow;
}
}
//==========================================================================
void timerCallback() override
{
for (int deck = 0; deck < 4; ++deck)
{
int pn = deck + 1; // 1-based player number
auto& ds = deckState[deck];
ds.discovered = proDJLink.isPlayerDiscovered(pn);
ds.model = proDJLink.getPlayerModel(pn);
ds.ip = proDJLink.getPlayerIP(pn);
ds.playState = proDJLink.getPlayStateString(pn);
ds.bpm = proDJLink.getBPM(pn);
ds.faderPitch = proDJLink.getFaderPitch(pn);
ds.isOnAir = proDJLink.isPlayerOnAir(pn);
ds.isMaster = proDJLink.isPlayerMaster(pn);
ds.isPlaying = proDJLink.isPlayerPlaying(pn);
ds.isReverse = proDJLink.isPlayingReverse(pn);
ds.beatInBar = proDJLink.getBeatInBar(pn);
ds.xfAssign = proDJLink.hasMixerFaderData() ? proDJLink.getChannelXfAssign(pn) : 0;
ds.playheadMs = proDJLink.getPlayheadMs(pn);
ds.trackLenSec = proDJLink.getTrackLengthSec(pn);
ds.trackId = proDJLink.getTrackID(pn);
ds.posSource = proDJLink.getPositionSourceString(pn);
// Timecode from playhead
FrameRate fps = proDJLink.getDetectedFrameRate(pn);
ds.timecode = ProDJLink::playheadToTimecode(ds.playheadMs, fps);
ds.fpsStr = frameRateToString(fps);
// Position ratio for waveform cursor
ds.posRatio = proDJLink.getPlayPositionRatio(pn);
// TrackMap lookup (single find, reused for offset + BPM multiplier)
const TrackMapEntry* tmEntry = nullptr;
ds.trackMapped = false;
ds.offset = "00:00:00:00";
ds.offsetTimecode = {};
if (ds.title.isNotEmpty())
{
tmEntry = trackMap.find(ds.artist, ds.title, (int)ds.trackLenSec);
if (!tmEntry && ds.trackLenSec > 0)
tmEntry = trackMap.find(ds.artist, ds.title, 0);
if (!tmEntry)
tmEntry = trackMap.findIgnoringDuration(ds.artist, ds.title);
if (tmEntry != nullptr)
{
ds.trackMapped = true;
ds.offset = tmEntry->timecodeOffset;
// Parse offset and compute running timecode with offset applied
int oH, oM, oS, oF;
if (TrackMapEntry::parseTimecodeString(tmEntry->timecodeOffset, oH, oM, oS, oF))
{
ds.offsetTimecode = applyTimecodeOffset(
ds.timecode, fps, oH, oM, oS, oF, fps);
}
}
}
// Engine assignment: find which engines monitor this player
ds.engineNames.clear();
ds.bpmSessionOverride = TimecodeEngine::kBpmNoOverride;
ds.bpmTrackMapValue = tmEntry ? tmEntry->bpmMultiplier : 0;
for (auto& eng : engines)
{
if (eng->getActiveInput() == TimecodeEngine::InputSource::ProDJLink
&& eng->getEffectivePlayer() == pn)
{
ds.engineNames.add(eng->getName());
ds.bpmSessionOverride = eng->getBpmPlayerOverride();
}
}
// --- Track changed? ---
bool trackChanged = (ds.trackId != ds.prevTrackId);
if (trackChanged)
{
ds.waveform.clearWaveform();
ds.detailWaveform.clear();
ds.displayedWaveformTrackId = 0;
ds.displayedDetailTrackId = 0;
ds.detailRetryTicks = 0;
ds.previewRetryTicks = 0;
ds.previewCuesFed = false;
ds.previewBeatGridFed = false;
ds.detailCuesFed = false;
ds.detailBeatGridFed = false;
ds.detailSongStructFed = false;
ds.lastMetaVersion = 0;
ds.lastDetailVersion = 0;
ds.displayedArtworkId = 0;
ds.cachedArtworkImg = {};
ds.artist.clear();
ds.title.clear();
ds.key.clear();
ds.artworkId = 0;
ds.cueCount = 0;
ds.invalidateDeckImg();
ds.prevTrackId = ds.trackId;
ds.metadataRequested = false; // reset so we request for new track
}
// --- Request metadata independently of engines ---
// ProDJLinkView requests metadata for ALL discovered players,
// so waveform/artwork/info loads even without an engine assigned.
// IMPORTANT: resolve SOURCE player IP -- when CDJ 2 loads from
// CDJ 1's USB via Link Export, the metadata is on CDJ 1.
uint8_t srcPlayer = proDJLink.getLoadedPlayer(pn);
if (srcPlayer == 0) srcPlayer = (uint8_t)pn;
juce::String srcIP = proDJLink.getPlayerIP((int)srcPlayer);
if (srcIP.isEmpty()) srcIP = ds.ip;
if (ds.trackId != 0 && !ds.metadataRequested
&& !srcIP.isEmpty() && dbClient.getIsRunning())
{
uint8_t slot = proDJLink.getLoadedSlot(pn);
if (slot != 0)
{
int dbCtx = proDJLink.getVCDJPlayerNumber();
juce::String model = proDJLink.getPlayerModel((int)srcPlayer);
dbClient.requestMetadata(
srcIP, slot, 1, ds.trackId, dbCtx, model);
ds.metadataRequested = true;
ds.metadataRequestTick = 0;
}
}
// Retry if metadata hasn't arrived after ~3s (180 ticks at 60Hz)
if (ds.metadataRequested && ds.artist.isEmpty()
&& ds.displayedWaveformTrackId != ds.trackId)
{
if (++ds.metadataRequestTick > 180)
ds.metadataRequested = false; // allow re-request
}
// --- Metadata from DbServerClient ---
if (ds.trackId != 0)
{
// Only re-fetch metadata if we still need artist/title or waveform
// (artwork image is fetched separately below, doesn't need metadata re-fetch)
bool needMeta = ds.artist.isEmpty()
|| ds.displayedWaveformTrackId != ds.trackId;
if (needMeta && !srcIP.isEmpty())
{
auto meta = dbClient.getCachedMetadata(srcIP, ds.trackId);
if (meta.isValid())
{
ds.lastMetaVersion = meta.cacheVersion;
if (meta.artist.isNotEmpty()) ds.artist = meta.artist;
if (meta.title.isNotEmpty()) ds.title = meta.title;
ds.key = meta.key;
ds.artworkId = meta.artworkId;
ds.cueCount = (int)meta.cueList.size();
if (meta.hasWaveform() && ds.displayedWaveformTrackId != ds.trackId)
{
ds.waveform.setColorWaveformData(meta.waveformData,
meta.waveformEntryCount, meta.waveformBytesPerEntry);
if (meta.durationSeconds > 0)
ds.waveform.setDurationMs((uint32_t)meta.durationSeconds * 1000);
if (meta.hasCueList())
{ ds.waveform.setRekordboxCues(meta.cueList); ds.previewCuesFed = true; }
if (meta.hasBeatGrid())
{ ds.waveform.setBeatGrid(meta.beatGrid); ds.previewBeatGridFed = true; }
ds.displayedWaveformTrackId = ds.trackId;
ds.previewRetryTicks = (!ds.previewCuesFed || !ds.previewBeatGridFed) ? 180 : 0;
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
// Save waveform + artwork to disk cache for future sessions
if (meta.title.isNotEmpty())
{
auto diskKey = TrackMapEntry::makeKey(
meta.artist, meta.title, meta.durationSeconds);
if (!WaveformCache::exists(diskKey))
{
uint32_t durMs = (meta.durationSeconds > 0)
? (uint32_t)meta.durationSeconds * 1000 : 0;
WaveformCache::save(diskKey, meta.waveformData,
meta.waveformEntryCount, meta.waveformBytesPerEntry, durMs);
}
}
}
else if (!meta.hasWaveform() && ds.displayedWaveformTrackId != ds.trackId
&& ds.title.isNotEmpty())
{
// Dbserver hasn't returned waveform yet -- try disk cache
// Use meta.durationSeconds (same source as save path),
// fall back to ds.trackLenSec if dbserver didn't provide it.
int durForKey = (meta.durationSeconds > 0)
? meta.durationSeconds : (int)ds.trackLenSec;
auto diskKey = TrackMapEntry::makeKey(
ds.artist, ds.title, durForKey);
if (WaveformCache::exists(diskKey))
{
auto cached = WaveformCache::load(diskKey);
if (cached.valid)
{
ds.waveform.setColorWaveformData(cached.data,
cached.entryCount, cached.bytesPerEntry);
if (cached.durationMs > 0)
ds.waveform.setDurationMs(cached.durationMs);
ds.displayedWaveformTrackId = ds.trackId;
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
}
}
}
}
else
{
// Fallback: try by trackId only (cached from another player)
auto metaById = dbClient.getCachedMetadataByTrackId(ds.trackId);
if (metaById.isValid())
{
ds.lastMetaVersion = metaById.cacheVersion;
if (metaById.artist.isNotEmpty()) ds.artist = metaById.artist;
if (metaById.title.isNotEmpty()) ds.title = metaById.title;
ds.key = metaById.key;
ds.artworkId = metaById.artworkId;
ds.cueCount = (int)metaById.cueList.size();
if (metaById.hasWaveform() && ds.displayedWaveformTrackId != ds.trackId)
{
ds.waveform.setColorWaveformData(metaById.waveformData,
metaById.waveformEntryCount, metaById.waveformBytesPerEntry);
if (metaById.durationSeconds > 0)
ds.waveform.setDurationMs((uint32_t)metaById.durationSeconds * 1000);
if (metaById.hasCueList())
{ ds.waveform.setRekordboxCues(metaById.cueList); ds.previewCuesFed = true; }
if (metaById.hasBeatGrid())
{ ds.waveform.setBeatGrid(metaById.beatGrid); ds.previewBeatGridFed = true; }
ds.displayedWaveformTrackId = ds.trackId;
ds.previewRetryTicks = (!ds.previewCuesFed || !ds.previewBeatGridFed) ? 180 : 0;
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
}
}
}
}
// Preview supplementary retry: cues / beat grid may arrive
// after the preview waveform. Only fetch when the background
// thread has actually updated the cache (version changed).
if (ds.displayedWaveformTrackId == ds.trackId
&& ds.previewRetryTicks > 0
&& (!ds.previewCuesFed || !ds.previewBeatGridFed))
{
uint32_t ver = dbClient.getMetadataVersion(srcIP, ds.trackId);
if (ver == 0) ver = dbClient.getMetadataVersionByTrackId(ds.trackId);
if (ver != ds.lastMetaVersion && !srcIP.isEmpty())
{
ds.lastMetaVersion = ver;
auto pm = dbClient.getCachedMetadata(srcIP, ds.trackId);
if (!pm.isValid())
pm = dbClient.getCachedMetadataByTrackId(ds.trackId);
if (pm.isValid())
{
bool changed = false;
if (!ds.previewCuesFed && pm.hasCueList())
{
ds.waveform.setRekordboxCues(pm.cueList);
ds.previewCuesFed = true;
ds.cueCount = (int)pm.cueList.size();
changed = true;
}
if (!ds.previewBeatGridFed && pm.hasBeatGrid())
{
ds.waveform.setBeatGrid(pm.beatGrid);
ds.previewBeatGridFed = true;
changed = true;
}
if (changed)
{
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
DBG("PDL Preview RETRY P" + juce::String(pn)
+ ": cuesFed=" + juce::String((int)ds.previewCuesFed)
+ " beatsFed=" + juce::String((int)ds.previewBeatGridFed)
+ " ver=" + juce::String(ver));
}
}
}
if (ds.previewCuesFed && ds.previewBeatGridFed)
ds.previewRetryTicks = 0;
else
ds.previewRetryTicks--;
}
// Fallback: if still no title, show "Track #ID" from protocol
if (ds.title.isEmpty())
ds.title = "Track #" + juce::String(ds.trackId);
// Artwork update (only when artworkId changes)
if (ds.artworkId != 0 && ds.artworkId != ds.displayedArtworkId)
{
auto artImg = dbClient.getCachedArtwork(ds.artworkId);
if (artImg.isValid())
{
ds.cachedArtworkImg = artImg;
ds.displayedArtworkId = ds.artworkId;
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
// Save to disk for future sessions
if (ds.title.isNotEmpty())
{
auto diskKey = TrackMapEntry::makeKey(
ds.artist, ds.title, (int)ds.trackLenSec);
if (!WaveformCache::artworkExists(diskKey))
WaveformCache::saveArtwork(diskKey, artImg);
}
}
}
// Artwork fallback from disk cache
if (!ds.cachedArtworkImg.isValid() && ds.title.isNotEmpty())
{
auto diskKey = TrackMapEntry::makeKey(
ds.artist, ds.title, (int)ds.trackLenSec);
if (WaveformCache::artworkExists(diskKey))
{
auto cachedArt = WaveformCache::loadArtwork(diskKey);
if (cachedArt.isValid())
{
ds.cachedArtworkImg = cachedArt;
ds.displayedArtworkId = ds.artworkId;
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
}
}
}
}
else
{
// No track loaded: clear everything
if (ds.displayedWaveformTrackId != 0)
{
ds.waveform.clearWaveform();
ds.displayedWaveformTrackId = 0;
}
if (ds.displayedDetailTrackId != 0)
{
ds.detailWaveform.clear();
ds.displayedDetailTrackId = 0;
ds.detailRetryTicks = 0;
}
ds.previewRetryTicks = 0;
ds.previewCuesFed = false;
ds.previewBeatGridFed = false;
ds.detailCuesFed = false;
ds.detailBeatGridFed = false;
ds.detailSongStructFed = false;
ds.lastMetaVersion = 0;
ds.lastDetailVersion = 0;
ds.displayedArtworkId = 0;
ds.cachedArtworkImg = {};
ds.artist.clear();
ds.title.clear();
ds.key.clear();
ds.artworkId = 0;
ds.cueCount = 0;
ds.metadataRequested = false;
}
// Waveform cursor
if (ds.waveform.hasWaveformData())
ds.waveform.setPlayPosition(ds.posRatio);
// Detail waveform: feed data, beat grid, song structure, cues.
// Data arrives asynchronously from DbServerClient (phase 2 + NFS thread).
// Poll periodically until detail data arrives.
if (ds.trackId != 0 && !srcIP.isEmpty())
{
bool needsInitial = (ds.displayedDetailTrackId != ds.trackId);
bool needsSupplementary = (ds.displayedDetailTrackId == ds.trackId
&& (!ds.detailCuesFed || !ds.detailBeatGridFed
|| !ds.detailSongStructFed
|| ds.detailWaveform.getDetailBytesPerEntry() < 3));
bool doFetch = false;
if (needsInitial)
{
bool hasDetail = dbClient.hasDetailWaveformCached(srcIP, ds.trackId);
if (hasDetail)
doFetch = true;
else
{
ds.detailRetryTicks++;
if (ds.detailRetryTicks % 60 == 1)
doFetch = true;
}
// Log once per second to track progress
if (ds.detailRetryTicks % 60 == 0)
{
DBG("PDL Detail POLL P" + juce::String(pn)
+ ": needsInitial tick=" + juce::String(ds.detailRetryTicks)
+ " hasDetail=" + juce::String((int)hasDetail)
+ " doFetch=" + juce::String((int)doFetch)
+ " trackId=" + juce::String(ds.trackId)
+ " srcIP=" + srcIP);
}
}
else if (needsSupplementary)
{
uint32_t curVer = dbClient.getMetadataVersion(srcIP, ds.trackId);
if (curVer == 0) curVer = dbClient.getMetadataVersionByTrackId(ds.trackId);
if (curVer != 0 && curVer != ds.lastDetailVersion)
doFetch = true;
}
if (doFetch)
{
auto meta = dbClient.getCachedMetadata(srcIP, ds.trackId);
if (!meta.isValid())
meta = dbClient.getCachedMetadataByTrackId(ds.trackId);
ds.lastDetailVersion = meta.cacheVersion;
DBG("PDL Detail FETCH P" + juce::String(pn)
+ ": valid=" + juce::String((int)meta.isValid())
+ " hasDetail=" + juce::String((int)meta.hasDetailWaveform())
+ " detailEntries=" + juce::String(meta.detailEntryCount)
+ " detailBpe=" + juce::String(meta.detailBytesPerEntry)
+ " detailDataSz=" + juce::String((int)meta.detailData.size())
+ " beats=" + juce::String((int)meta.beatGrid.size())
+ " cues=" + juce::String((int)meta.cueList.size())
+ " phrases=" + juce::String((int)meta.songStructure.size())
+ " nfsAttempted=" + juce::String((int)meta.nfsAttempted)
+ " ver=" + juce::String(meta.cacheVersion));
if (needsInitial)
{
if (meta.hasDetailWaveform())
{
uint32_t durMs = (meta.durationSeconds > 0)
? (uint32_t)meta.durationSeconds * 1000 : 0;
ds.detailWaveform.setDetailData(meta.detailData,
meta.detailEntryCount, meta.detailBytesPerEntry, durMs);
ds.displayedDetailTrackId = ds.trackId;
ds.detailRetryTicks = 0; // stop polling
ds.invalidateDeckImg();
if (!deckBounds[pn - 1].isEmpty())
repaint(deckBounds[pn - 1]);
// Feed any supplementary data available in this same fetch
// (avoids waiting for the next version change poll)
if (meta.hasBeatGrid())
{
ds.detailWaveform.setBeatGrid(meta.beatGrid);
ds.detailBeatGridFed = true;
for (auto& eng : engines)
{
if (eng->getActiveInput() == TimecodeEngine::InputSource::ProDJLink
&& eng->getEffectivePlayer() == pn)
eng->setBeatGrid(meta.beatGrid, ds.trackId);
}
}
if (meta.hasSongStructure())
{
ds.detailWaveform.setSongStructure(meta.songStructure, meta.phraseMood);
ds.detailSongStructFed = true;
}
if (meta.hasCueList())
{
ds.detailWaveform.setRekordboxCues(meta.cueList);
ds.detailCuesFed = true;
if (ds.cueCount == 0)
ds.cueCount = (int)meta.cueList.size();
}
// Persist ANLZ to disk (detail waveform + whatever else arrived)
saveAnlzFromMeta(meta);
}
}
// Feed supplementary data (may arrive after detail waveform)
if (ds.displayedDetailTrackId == ds.trackId)
{
bool supplementaryFed = false;
// Upgrade detail waveform if better quality arrived
// (e.g. dbserver provided PWV7 3-band after NFS provided PWV5 2-byte)
if (meta.hasDetailWaveform()
&& meta.detailBytesPerEntry > ds.detailWaveform.getDetailBytesPerEntry())
{
uint32_t durMs = (meta.durationSeconds > 0)
? (uint32_t)meta.durationSeconds * 1000 : 0;
ds.detailWaveform.setDetailData(meta.detailData,
meta.detailEntryCount, meta.detailBytesPerEntry, durMs);
supplementaryFed = true;
DBG("PDL Detail UPGRADE P" + juce::String(pn)
+ ": bpe " + juce::String(ds.detailWaveform.getDetailBytesPerEntry())
+ " -> " + juce::String(meta.detailBytesPerEntry));
}
if (!ds.detailBeatGridFed && meta.hasBeatGrid())
{
ds.detailWaveform.setBeatGrid(meta.beatGrid);
ds.detailBeatGridFed = true;
supplementaryFed = true;
// Feed to engines for PLL micro-correction
for (auto& eng : engines)
{
if (eng->getActiveInput() == TimecodeEngine::InputSource::ProDJLink
&& eng->getEffectivePlayer() == pn)
eng->setBeatGrid(meta.beatGrid, ds.trackId);
}
}
if (!ds.detailSongStructFed && meta.hasSongStructure())
{
ds.detailWaveform.setSongStructure(meta.songStructure, meta.phraseMood);
ds.detailSongStructFed = true;
supplementaryFed = true;
}
if (!ds.detailCuesFed && meta.hasCueList())
{
ds.detailWaveform.setRekordboxCues(meta.cueList);
ds.detailCuesFed = true;
supplementaryFed = true;
if (ds.cueCount == 0)
{
ds.cueCount = (int)meta.cueList.size();
ds.invalidateDeckImg();
}
// Auto-populate TrackMap cue points from rekordbox
// hot cues, but only if the entry exists and has NO
// manually-configured cue points.
// Blocked during Show Lock -- TrackMap is configuration.
if (ds.title.isNotEmpty()
&& (!isShowLockedFn || !isShowLockedFn()))
{