-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTimecodeEngine.h
More file actions
1998 lines (1776 loc) · 84 KB
/
TimecodeEngine.h
File metadata and controls
1998 lines (1776 loc) · 84 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
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include "MtcInput.h"
#include "MtcOutput.h"
#include "ArtnetInput.h"
#include "ArtnetOutput.h"
#include "LtcInput.h"
#include "LtcOutput.h"
#include "ProDJLinkInput.h"
#include "DbServerClient.h"
#include "TriggerOutput.h"
#include "LinkBridge.h"
#include "AudioThru.h"
#include "AppSettings.h"
#include "MixerMap.h"
#include <memory>
//==============================================================================
// TimecodeEngine -- one independent routing pipeline
//
// Each engine owns: 1 input source -> N output destinations.
// AudioThru is only available on the primary engine (index 0).
//==============================================================================
// All public methods of TimecodeEngine are designed to be called exclusively
// from the JUCE message thread. Protocol handler callbacks (MTC/ArtNet/LTC)
// communicate back via atomics only. No additional synchronisation is needed.
inline constexpr int kPrimaryEngineIndex = 0;
inline constexpr int kMaxEngines = 8;
class TimecodeEngine
{
public:
enum class InputSource { MTC, ArtNet, SystemTime, LTC, ProDJLink };
//--------------------------------------------------------------------------
explicit TimecodeEngine(int index, const juce::String& name = {})
: engineIndex(index),
engineName(name.isEmpty() ? ("ENGINE " + juce::String(index + 1)) : name)
{
std::fill(std::begin(lastSentMixer), std::end(lastSentMixer), -1); lastMixerPktCount = 0;
// Only the primary engine (index 0) gets AudioThru
if (index == kPrimaryEngineIndex)
audioThru = std::make_unique<AudioThru>();
}
~TimecodeEngine()
{
// Stop MIDI clock timer first (runs on HighResolutionTimer thread)
setMidiClockEnabled(false);
triggerOutput.stopMidi();
triggerOutput.disconnectOsc();
// Shutdown order: outputs first, then inputs
stopMtcOutput();
stopArtnetOutput();
stopLtcOutput();
stopThruOutput();
stopMtcInput();
stopArtnetInput();
stopLtcInput();
// ProDJLink is shared -- not stopped per-engine
}
//==========================================================================
// Identity
//==========================================================================
int getIndex() const { return engineIndex; }
juce::String getName() const { return engineName; }
void setName(const juce::String& name) { engineName = name; }
bool isPrimary() const { return engineIndex == kPrimaryEngineIndex; }
// Called after engine deletion to fix indices so isPrimary() stays correct
// and AudioThru is created for the new primary engine if needed.
// NOTE: The caller (MainComponent::removeEngine) is responsible for
// restarting AudioThru on the new primary engine after reindexing,
// because that requires UI state (device combos) that the engine doesn't own.
void reindex(int newIndex)
{
// If we were the primary engine and are being moved away, destroy AudioThru
// to avoid a stale handler referencing a deleted LtcInput.
if (engineIndex == kPrimaryEngineIndex && newIndex != kPrimaryEngineIndex)
{
stopThruOutput();
audioThru.reset();
outputThruEnabled = false;
}
engineIndex = newIndex;
// Create AudioThru if we just became the primary engine
if (newIndex == kPrimaryEngineIndex && !audioThru)
audioThru = std::make_unique<AudioThru>();
}
//==========================================================================
// Input source
//==========================================================================
InputSource getActiveInput() const { return activeInput; }
FrameRate getCurrentFps() const { return currentFps; }
Timecode getCurrentTimecode() const
{
const juce::SpinLock::ScopedLockType sl(timecodeLock);
return currentTimecode;
}
bool isSourceActive() const { return sourceActive; }
bool getUserOverrodeLtcFps() const { return userOverrodeLtcFps; }
void setInputSource(InputSource source)
{
// Stop current input
switch (activeInput)
{
case InputSource::MTC: stopMtcInput(); break;
case InputSource::ArtNet: stopArtnetInput(); break;
case InputSource::LTC: stopLtcInput(); break;
case InputSource::ProDJLink: stopProDJLinkInput(); break;
default: break;
}
userOverrodeLtcFps = false;
activeInput = source;
sourceActive = false;
// Reset TrackMap cache when leaving ProDJLink
if (source != InputSource::ProDJLink)
{
trackMapped = false;
cachedTrackId = 0;
cachedOffH = cachedOffM = cachedOffS = cachedOffF = 0;
cachedBpmMultiplier = 0;
bpmPlayerOverride = kBpmNoOverride;
cachedTrackArtist.clear();
cachedTrackTitle.clear();
// Disable Link to avoid publishing stale tempo on the network
linkBridge.setEnabled(false);
}
// Note: actual start is deferred to the caller (MainComponent),
// which gathers device params from UI before calling startXxxInput().
if (source == InputSource::SystemTime)
sourceActive = true;
}
void setFrameRate(FrameRate fps)
{
currentFps = fps;
FrameRate outRate = getEffectiveOutputFps();
mtcOutput.setFrameRate(outRate);
artnetOutput.setFrameRate(outRate);
ltcOutput.setFrameRate(outRate);
}
void setUserOverrodeLtcFps(bool v) { userOverrodeLtcFps = v; }
//==========================================================================
// FPS conversion
//==========================================================================
bool isFpsConvertEnabled() const { return fpsConvertEnabled; }
FrameRate getOutputFps() const { return outputFps; }
Timecode getOutputTimecode() const { return outputTimecode; }
/// Playhead in ms from CDJ (for UI cursor / position display).
/// Reads directly from ProDJLinkInput — the CDJ-3000 sends clean
/// monotonic positions at ~30Hz, no smoothing needed.
uint32_t getSmoothedPlayheadMs() const
{
if (sharedProDJLink == nullptr) return 0;
int ep = getEffectivePlayer();
if (ep < 1) return 0;
return sharedProDJLink->getPlayheadMs(ep);
}
/// Play position as 0.0-1.0 ratio from CDJ (for waveform cursor).
float getSmoothedPlayPositionRatio() const
{
if (sharedProDJLink == nullptr) return 0.0f;
int ep = getEffectivePlayer();
if (ep < 1) return 0.0f;
return sharedProDJLink->getPlayPositionRatio(ep);
}
FrameRate getEffectiveOutputFps() const
{
return fpsConvertEnabled ? outputFps : currentFps;
}
void setFpsConvertEnabled(bool enabled)
{
fpsConvertEnabled = enabled;
if (!enabled)
{
outputFps = currentFps;
setOutputFrameRate(currentFps);
}
}
void setOutputFrameRate(FrameRate fps)
{
outputFps = fps;
// ProDJLink has no inherent frame rate (CDJ sends ms, not frames).
// The user's fps choice IS the current fps.
if (activeInput == InputSource::ProDJLink)
currentFps = fps;
FrameRate outRate = getEffectiveOutputFps();
mtcOutput.setFrameRate(outRate);
artnetOutput.setFrameRate(outRate);
ltcOutput.setFrameRate(outRate);
}
//==========================================================================
// Output enables & offsets
//==========================================================================
bool isOutputMtcEnabled() const { return outputMtcEnabled; }
bool isOutputArtnetEnabled() const { return outputArtnetEnabled; }
bool isOutputLtcEnabled() const { return outputLtcEnabled; }
bool isOutputThruEnabled() const { return outputThruEnabled; }
void setOutputMtcEnabled(bool e) { outputMtcEnabled = e; }
void setOutputArtnetEnabled(bool e) { outputArtnetEnabled = e; }
void setOutputLtcEnabled(bool e) { outputLtcEnabled = e; }
void setOutputThruEnabled(bool e) { outputThruEnabled = e; }
int getMtcOutputOffset() const { return mtcOutputOffset; }
int getArtnetOutputOffset() const { return artnetOutputOffset; }
int getLtcOutputOffset() const { return ltcOutputOffset; }
void setMtcOutputOffset(int v) { mtcOutputOffset = v; }
void setArtnetOutputOffset(int v) { artnetOutputOffset = v; }
void setLtcOutputOffset(int v) { ltcOutputOffset = v; }
//==========================================================================
// Protocol handlers -- direct access for device queries
//==========================================================================
MtcInput& getMtcInput() { return mtcInput; }
MtcOutput& getMtcOutput() { return mtcOutput; }
ArtnetInput& getArtnetInput() { return artnetInput; }
ArtnetOutput& getArtnetOutput() { return artnetOutput; }
LtcInput& getLtcInput() { return ltcInput; }
LtcOutput& getLtcOutput() { return ltcOutput; }
ProDJLinkInput& getProDJLinkInput() { jassert(sharedProDJLink != nullptr); return *sharedProDJLink; }
void setSharedProDJLinkInput(ProDJLinkInput* shared) { sharedProDJLink = shared; }
void setDbServerClient(DbServerClient* client) { dbClient = client; }
int getProDJLinkPlayer() const { return proDJLinkPlayer; }
/// Returns the physical player (1-6) actually being followed.
/// In fixed mode: same as proDJLinkPlayer. In XF mode: the resolved player.
int getEffectivePlayer() const
{
return isXfMode() ? resolvedXfPlayer : proDJLinkPlayer;
}
void setProDJLinkPlayer(int p)
{
proDJLinkPlayer = juce::jlimit(1, kPlayerXfB, p);
resolvedXfPlayer = 0; // force re-resolve on next tick
resetProDJLinkCache();
bpmPlayerOverride = kBpmNoOverride;
lastSentClockBpm = -1.0f;
lastSentOscBpm = -1.0f;
}
AudioThru* getAudioThru() { return audioThru.get(); }
//==========================================================================
// Start / Stop input protocols
//==========================================================================
bool startMtcInput(int deviceIndex)
{
stopMtcInput();
mtcInput.refreshDeviceList();
if (deviceIndex < 0 && mtcInput.getDeviceCount() > 0) deviceIndex = 0;
if (deviceIndex >= 0 && mtcInput.start(deviceIndex))
{
inputStatusText = "RX: " + mtcInput.getCurrentDeviceName();
return true;
}
inputStatusText = (deviceIndex < 0) ? "NO MIDI DEVICE AVAILABLE" : "FAILED TO OPEN DEVICE";
return false;
}
void stopMtcInput() { mtcInput.stop(); }
bool startArtnetInput(int interfaceIndex)
{
stopArtnetInput();
if (interfaceIndex < 0) interfaceIndex = 0;
artnetInput.refreshNetworkInterfaces();
if (artnetInput.start(interfaceIndex, 6454))
{
inputStatusText = "RX ON " + artnetInput.getBindInfo();
if (artnetInput.didFallBackToAllInterfaces())
inputStatusText += " [FALLBACK]";
return true;
}
inputStatusText = "FAILED TO BIND PORT 6454";
return false;
}
void stopArtnetInput() { artnetInput.stop(); }
bool startLtcInput(const juce::String& typeName, const juce::String& devName,
int ltcChannel, int thruChannel = -1,
double sampleRate = 0, int bufferSize = 0)
{
stopLtcInput();
if (devName.isEmpty()) { inputStatusText = "NO AUDIO DEVICE AVAILABLE"; return false; }
if (ltcInput.start(typeName, devName, ltcChannel, thruChannel, sampleRate, bufferSize))
{
inputStatusText = "RX: " + ltcInput.getCurrentDeviceName()
+ " Ch " + juce::String(ltcChannel + 1);
return true;
}
inputStatusText = "FAILED TO OPEN AUDIO DEVICE";
return false;
}
void stopLtcInput()
{
stopThruOutput();
ltcInput.stop();
}
//==========================================================================
// Pro DJ Link input (shared across engines)
//==========================================================================
void resetProDJLinkCache()
{
trackMapped = false;
cachedTrackId = 0;
lastSeenTrackVersion = 0;
cachedOffH = cachedOffM = cachedOffS = cachedOffF = 0;
cachedTrackArtist.clear();
cachedTrackTitle.clear();
pll.reset(); pdlTcFrozen = false; pdlLastPlayheadMs = 0;
pdlSnapMs = 0.0; pdlSnapTime = 0.0; pdlSnapSpeed = 1.0;
ltcOutput.setPitchMultiplier(1.0);
std::memset(trigDmxBuffer, 0, sizeof(trigDmxBuffer));
trigDmxHighWater = 0;
}
bool startProDJLinkInput(int player = 1)
{
resetProDJLinkCache();
// Reset forward dedup
lastSentClockBpm = -1.0f;
lastSentOscBpm = -1.0f;
// ProDJLink has no fps auto-detection -- use configured output fps
currentFps = outputFps;
// LTC direct mode is now toggled dynamically per tick
// (direct in transient, auto-increment in stable)
proDJLinkPlayer = juce::jlimit(1, kPlayerXfB, player);
resolvedXfPlayer = 0; // force resolve on first tick
if (sharedProDJLink != nullptr && !isXfMode())
lastSeenTrackVersion = sharedProDJLink->getTrackVersion(proDJLinkPlayer);
if (sharedProDJLink != nullptr && sharedProDJLink->getIsRunning())
{
inputStatusText = "LISTENING | " + sharedProDJLink->getBindInfo();
return true;
}
inputStatusText = "WAITING FOR PRO DJ LINK...";
return sharedProDJLink != nullptr;
}
void stopProDJLinkInput()
{
// Reset PLL and LTC encoder state so other sources start clean.
pll.reset(); pdlTcFrozen = false; pdlLastPlayheadMs = 0;
pdlSnapMs = 0.0; pdlSnapTime = 0.0; pdlSnapSpeed = 1.0;
ltcOutput.setPitchMultiplier(1.0);
}
//==========================================================================
// TrackMap -- track-to-timecode-offset mapping
//==========================================================================
/// Set the TrackMap pointer (owned by AppSettings, not by the engine).
/// Must be called before enabling track mapping. Pass nullptr to disconnect.
void setTrackMap(TrackMap* map)
{
trackMapPtr = map;
if (map == nullptr)
{
// Clear pending flags to avoid stale operations on a null pointer
trackMapDirty = false;
trackMapAutoFilled = false;
}
}
void setMixerMap(MixerMap* map)
{
mixerMapPtr = map;
std::fill(std::begin(lastSentMixer), std::end(lastSentMixer), -1); lastMixerPktCount = 0;
}
/// Enable or disable TrackMap offset application.
/// Triggers fire independently of this setting.
void setTrackMapEnabled(bool enabled)
{
trackMapEnabled = enabled;
if (!enabled)
{
// Reset offset state only -- keep cachedTrackId for trigger use
trackMapped = false;
cachedOffH = cachedOffM = cachedOffS = cachedOffF = 0;
cachedBpmMultiplier = 0;
lastSentClockBpm = -1.0f;
lastSentOscBpm = -1.0f;
}
else if (trackMapPtr && activeInput == InputSource::ProDJLink
&& sharedProDJLink != nullptr && sharedProDJLink->getIsRunning())
{
lastSeenTrackVersion = sharedProDJLink->getTrackVersion(getEffectivePlayer());
uint32_t id = (cachedTrackId != 0) ? cachedTrackId : sharedProDJLink->getTrackID(getEffectivePlayer());
if (id != 0)
{
cachedTrackId = id;
auto tinfo = sharedProDJLink->getTrackInfo(getEffectivePlayer());
cachedTrackArtist = tinfo.artist;
cachedTrackTitle = tinfo.title;
// Phase 2: check dbClient cache or request if missing
if (dbClient != nullptr && dbClient->getIsRunning())
{
auto meta = dbClient->getCachedMetadataByTrackId(id);
if (meta.isValid())
{
cachedTrackArtist = meta.artist;
cachedTrackTitle = meta.title;
// Propagate track duration to player state (NXS2 needs this
// since it doesn't report duration in protocol packets)
if (meta.durationSeconds > 0 && sharedProDJLink != nullptr)
sharedProDJLink->setTrackLengthSec(getEffectivePlayer(),
(uint32_t)meta.durationSeconds);
}
else
{
requestDbMetadata(id);
}
}
lookupTrackInMap();
}
}
}
bool isTrackMapEnabled() const { return trackMapEnabled; }
/// Whether the currently playing track has a mapping in the TrackMap
bool isTrackMapped() const { return trackMapped; }
/// Get the Track ID currently being tracked (0 if none)
uint32_t getActiveTrackId() const { return cachedTrackId; }
/// Get the cached TrackMap entry info for the current track (for UI display).
/// Returns empty strings and zero offset if no track is mapped.
struct ActiveTrackInfo
{
uint32_t trackId = 0;
juce::String artist;
juce::String title;
juce::String offset = "00:00:00:00";
bool mapped = false;
// Phase 2 -- extended metadata from dbserver (empty if not yet resolved)
juce::String album;
juce::String genre;
juce::String key;
int bpmTimes100 = 0;
uint32_t artworkId = 0;
};
ActiveTrackInfo getActiveTrackInfo() const
{
ActiveTrackInfo info;
info.trackId = cachedTrackId;
info.artist = cachedTrackArtist;
info.title = cachedTrackTitle;
info.mapped = trackMapped;
if (trackMapped)
info.offset = TrackMapEntry::formatTimecodeString(
cachedOffH, cachedOffM, cachedOffS, cachedOffF);
// Phase 2: enrich with dbClient cache if available
if (dbClient != nullptr && cachedTrackId != 0)
{
auto meta = dbClient->getCachedMetadataByTrackId(cachedTrackId);
if (meta.isValid())
{
info.album = meta.album;
info.genre = meta.genre;
info.key = meta.key;
info.bpmTimes100 = meta.bpmTimes100;
info.artworkId = meta.artworkId;
// Ensure artist/title are from dbClient if available
if (info.artist.isEmpty() || info.title.startsWith("Track #"))
{
info.artist = meta.artist;
info.title = meta.title;
}
}
}
return info;
}
/// Force a re-lookup of the current track (e.g., after editing TrackMap)
void refreshTrackMapLookup()
{
if (!trackMapPtr || cachedTrackArtist.isEmpty()) return;
lookupTrackInMap();
}
/// Re-request metadata for the current track (used when waveform data
/// hasn't arrived yet but metadata is already cached -- triggers the
/// waveform-only retry path in DbServerClient).
void retryWaveformRequest()
{
if (cachedTrackId != 0)
requestDbMetadata(cachedTrackId);
}
/// Returns true (once) if auto-fill modified the TrackMap and it was saved.
/// Used by MainComponent to refresh the TrackMapEditor window if open.
bool consumeTrackMapAutoFilled()
{
if (trackMapAutoFilled) { trackMapAutoFilled = false; return true; }
return false;
}
//==========================================================================
// Track change triggers (MIDI / OSC)
//==========================================================================
TriggerOutput& getTriggerOutput() { return triggerOutput; }
//==========================================================================
// Start / Stop output protocols
//==========================================================================
bool startMtcOutput(int deviceIndex)
{
stopMtcOutput();
mtcOutput.refreshDeviceList();
if (deviceIndex < 0 && mtcOutput.getDeviceCount() > 0) deviceIndex = 0;
if (deviceIndex >= 0 && mtcOutput.start(deviceIndex))
{
mtcOutput.setFrameRate(getEffectiveOutputFps());
mtcOutStatusText = "TX: " + mtcOutput.getCurrentDeviceName();
return true;
}
mtcOutStatusText = (deviceIndex < 0) ? "NO MIDI DEVICE" : "FAILED TO OPEN";
return false;
}
void stopMtcOutput() { mtcOutput.stop(); mtcOutStatusText = ""; }
bool startArtnetOutput(int interfaceIndex)
{
stopArtnetOutput();
artnetOutput.refreshNetworkInterfaces();
if (artnetOutput.start(interfaceIndex, 6454))
{
artnetOutput.setFrameRate(getEffectiveOutputFps());
artnetOutStatusText = "TX: " + artnetOutput.getBroadcastIp() + ":6454";
return true;
}
artnetOutStatusText = "FAILED TO BIND";
return false;
}
void stopArtnetOutput() { artnetOutput.stop(); artnetOutStatusText = ""; }
bool startLtcOutput(const juce::String& typeName, const juce::String& devName,
int channel, double sampleRate = 0, int bufferSize = 0)
{
stopLtcOutput();
if (devName.isEmpty()) { ltcOutStatusText = "NO AUDIO DEVICE AVAILABLE"; return false; }
// Check for AudioThru device conflict (primary engine only)
if (audioThru && audioThru->getIsRunning()
&& audioThru->getCurrentDeviceName() == devName
&& audioThru->getCurrentTypeName() == typeName)
{
stopThruOutput();
thruOutStatusText = "CONFLICT: same device as LTC OUT";
}
if (ltcOutput.start(typeName, devName, channel, sampleRate, bufferSize))
{
ltcOutput.setFrameRate(getEffectiveOutputFps());
juce::String chName = (channel == -1) ? "Ch 1 + Ch 2" : ("Ch " + juce::String(channel + 1));
ltcOutStatusText = "TX: " + ltcOutput.getCurrentDeviceName() + " " + chName;
return true;
}
ltcOutStatusText = "FAILED TO OPEN AUDIO DEVICE";
return false;
}
void stopLtcOutput() { ltcOutput.stop(); ltcOutStatusText = ""; }
bool startThruOutput(const juce::String& typeName, const juce::String& devName,
int channel, double sampleRate = 0, int bufferSize = 0)
{
stopThruOutput();
if (!audioThru) return false; // not primary engine
if (!ltcInput.getIsRunning() || !ltcInput.hasPassthruChannel())
{
thruOutStatusText = "WAITING FOR LTC INPUT";
return false;
}
ltcInput.resetPassthruCounters();
ltcInput.syncPassthruReadPosition();
if (devName.isEmpty()) { thruOutStatusText = "NO AUDIO DEVICE"; return false; }
// Check for LTC output device conflict
if (outputLtcEnabled && ltcOutput.getIsRunning()
&& ltcOutput.getCurrentDeviceName() == devName
&& ltcOutput.getCurrentTypeName() == typeName)
{
thruOutStatusText = "CONFLICT: same device as LTC OUT";
return false;
}
if (audioThru->start(typeName, devName, channel, <cInput, sampleRate, bufferSize))
{
juce::String chName = (channel == -1) ? "Ch 1 + Ch 2" : ("Ch " + juce::String(channel + 1));
thruOutStatusText = "THRU: " + audioThru->getCurrentDeviceName() + " " + chName;
double inRate = ltcInput.getActualSampleRate();
double outRate = audioThru->getActualSampleRate();
if (std::abs(inRate - outRate) > 1.0)
thruOutStatusText += " [RATE MISMATCH: " + juce::String((int)inRate) + "/" + juce::String((int)outRate) + "]";
return true;
}
thruOutStatusText = "FAILED TO OPEN";
return false;
}
void stopThruOutput()
{
if (audioThru) audioThru->stop();
thruOutStatusText = "";
}
//==========================================================================
// tick() -- called from timerCallback each frame
//==========================================================================
void tick()
{
switch (activeInput)
{
case InputSource::SystemTime:
updateSystemTime();
sourceActive = true;
inputStatusText = "SYSTEM CLOCK";
break;
case InputSource::MTC:
if (mtcInput.getIsRunning())
{
currentTimecode = mtcInput.getCurrentTimecode();
bool rx = mtcInput.isReceiving();
if (rx)
{
auto d = mtcInput.getDetectedFrameRate();
if (d != currentFps) setFrameRate(d);
inputStatusText = "RX: " + mtcInput.getCurrentDeviceName();
}
else
inputStatusText = "PAUSED - " + mtcInput.getCurrentDeviceName();
sourceActive = rx;
}
else { sourceActive = false; inputStatusText = "WAITING FOR DEVICE..."; }
break;
case InputSource::ArtNet:
if (artnetInput.getIsRunning())
{
currentTimecode = artnetInput.getCurrentTimecode();
bool rx = artnetInput.isReceiving();
if (rx)
{
auto d = artnetInput.getDetectedFrameRate();
if (d != currentFps) setFrameRate(d);
inputStatusText = "RX ON " + artnetInput.getBindInfo();
}
else
inputStatusText = "PAUSED - " + artnetInput.getBindInfo();
sourceActive = rx;
}
else { sourceActive = false; inputStatusText = "NOT LISTENING"; }
break;
case InputSource::LTC:
if (ltcInput.getIsRunning())
{
currentTimecode = ltcInput.getCurrentTimecode();
bool rx = ltcInput.isReceiving();
if (rx)
{
auto d = ltcInput.getDetectedFrameRate();
bool ambiguousOverride = userOverrodeLtcFps
&& ((currentFps == FrameRate::FPS_2398 && d == FrameRate::FPS_24)
|| (currentFps == FrameRate::FPS_2997 && d == FrameRate::FPS_30));
if (d != currentFps && !ambiguousOverride)
{
if (d != FrameRate::FPS_24 && d != FrameRate::FPS_30)
userOverrodeLtcFps = false;
setFrameRate(d);
}
inputStatusText = "RX: " + ltcInput.getCurrentDeviceName()
+ " Ch " + juce::String(ltcInput.getSelectedChannel() + 1);
}
else
inputStatusText = "PAUSED - " + ltcInput.getCurrentDeviceName();
sourceActive = rx;
}
else { sourceActive = false; inputStatusText = "WAITING FOR DEVICE..."; }
break;
case InputSource::ProDJLink:
if (sharedProDJLink != nullptr && sharedProDJLink->getIsRunning())
{
// --- XF-A/XF-B auto-follow: resolve physical player ---
if (isXfMode())
resolveXfPlayer();
const int ep = getEffectivePlayer();
if (ep < 1 || ep > ProDJLink::kMaxPlayers)
{
sourceActive = false;
juce::String sideLabel = (proDJLinkPlayer == kPlayerXfA) ? "XF-A" : "XF-B";
inputStatusText = sideLabel + ": NO PLAYER ON SIDE";
break;
}
// PLL runs only for pitch calculation (LTC bit-rate scaling).
// It does NOT drive the displayed timecode — that comes directly
// from the CDJ's playhead, which is clean and monotonic (~30Hz).
double cdjSpeed = sharedProDJLink->getActualSpeed(ep);
pll.tick(
sharedProDJLink->getPlayheadMs(ep),
sharedProDJLink->getAbsPositionTs(ep),
cdjSpeed,
sharedProDJLink->isPositionMoving(ep)
);
// Smooth timecode display using interpolation between CDJ packets.
uint32_t rawPlayheadMs = sharedProDJLink->getPlayheadMs(ep);
double now = juce::Time::getMillisecondCounterHiRes();
bool isNewPacket = (rawPlayheadMs != pdlLastPlayheadMs);
double displayMs = (double)rawPlayheadMs; // default: raw
if (isNewPacket)
{
// New CDJ data arrived — snap to real position
pdlLastPlayheadMs = rawPlayheadMs;
pdlSnapMs = (double)rawPlayheadMs;
pdlSnapTime = now;
pdlSnapSpeed = cdjSpeed;
currentTimecode = ProDJLink::playheadToTimecode(rawPlayheadMs, getEffectiveOutputFps());
}
else if (pdlSnapSpeed > 0.01 && sharedProDJLink->isPlayerPlaying(ep))
{
// Between packets: interpolate forward using CDJ speed
double elapsed = now - pdlSnapTime;
double interpMs = pdlSnapMs + elapsed * pdlSnapSpeed;
double maxAdvance = 50.0 * pdlSnapSpeed;
if (elapsed <= maxAdvance)
{
displayMs = interpMs;
currentTimecode = ProDJLink::playheadToTimecode((uint32_t)interpMs, getEffectiveOutputFps());
}
}
// Freeze timecode on end-of-track only.
// The CDJ freezes actualSpeed at the last playing value on END_TRACK,
// so the PLL keeps advancing while position correction fights back,
// causing frame flicker. Snapshot the timecode and hold it stable.
// Pause is NOT frozen: actualSpeed ramps 0.88->0 in ~4-5s and the
// PLL follows that deceleration smoothly.
bool isEOT = sharedProDJLink->isEndOfTrack(ep);
if (!isEOT)
{
pdlTcFrozen = false;
}
else if (!pdlTcFrozen)
{
pdlFrozenTc = currentTimecode;
pdlTcFrozen = true;
}
if (pdlTcFrozen)
currentTimecode = pdlFrozenTc;
// Feed pitch to LTC output -- scales bit-rate so the audio
// timecode stream runs faster/slower matching the CDJ.
// MTC and ArtNet don't need pitch scaling -- they send at
// nominal rate and the timecode values advance naturally.
// When timecode is frozen (end-of-track), zero the pitch so
// the LTC encoder stops generating audio.
ltcOutput.setPitchMultiplier(pdlTcFrozen ? 0.0 : pll.pitch);
// Always auto-increment: encoder goes N->N+1->N+2 at actualSpeed.
// CDJ status packets (offset 152) report real motor speed including
// ramps, so the encoder rate naturally matches the CDJ. No direct
// mode needed -- auto-increment produces perfectly monotonic output
// during both acceleration and deceleration ramps.
// Resync only on seek (handled by packFrame's >1 frame check).
// --- Track change detection ---
uint32_t pdlTrackVer = sharedProDJLink->getTrackVersion(ep);
if (pdlTrackVer != lastSeenTrackVersion)
{
lastSeenTrackVersion = pdlTrackVer;
uint32_t newId = sharedProDJLink->getTrackID(ep);
if (newId != 0 && newId != cachedTrackId)
{
cachedTrackId = newId;
auto tinfo = sharedProDJLink->getTrackInfo(ep);
cachedTrackArtist = tinfo.artist;
cachedTrackTitle = tinfo.title;
DBG("TimecodeEngine: track changed -- "
+ cachedTrackArtist + " - " + cachedTrackTitle
+ " (cdj_id=" + juce::String(newId) + ")"
+ " player=" + juce::String(ep));
// Request metadata from dbserver (async) -- needed to resolve
// "Track #12345" into real artist/title for TrackMap lookup
requestDbMetadata(newId);
// Attempt TrackMap lookup (succeeds immediately if CDJ provides
// real artist/title; deferred until dbserver resolves if not)
const auto* entry = lookupTrackInMap();
// Reset session override on track change
bpmPlayerOverride = kBpmNoOverride;
lastSentClockBpm = -1.0f;
lastSentOscBpm = -1.0f;
fireTrackTrigger(entry);
}
}
// Phase 2: poll dbClient cache for async metadata results.
// When "Track #12345" resolves to real artist/title, update cache
// and re-run TrackMap lookup (the first attempt on track change would
// have failed because we didn't have real metadata yet).
if (dbClient != nullptr && cachedTrackId != 0
&& cachedTrackTitle.startsWith("Track #"))
{
auto meta = dbClient->getCachedMetadataByTrackId(cachedTrackId);
if (meta.isValid())
{
cachedTrackArtist = meta.artist;
cachedTrackTitle = meta.title;
if (meta.durationSeconds > 0 && sharedProDJLink != nullptr)
sharedProDJLink->setTrackLengthSec(ep,
(uint32_t)meta.durationSeconds);
// NOW we have real artist+title -- do the TrackMap lookup
const auto* entry = lookupTrackInMap();
fireTrackTrigger(entry);
}
}
// --- Persist auto-filled metadata ---
if (trackMapDirty && trackMapPtr != nullptr)
{
trackMapDirty = false;
TrackMap* mapRef = trackMapPtr;
juce::MessageManager::callAsync([mapRef]() { mapRef->save(); });
}
// --- Apply timecode offset ---
if (trackMapEnabled && trackMapped)
{
currentTimecode = applyTimecodeOffset(
currentTimecode, currentFps,
cachedOffH, cachedOffM, cachedOffS, cachedOffF,
currentFps);
}
bool pdlRx = sharedProDJLink->isReceiving();
if (pdlRx)
{
// Note: no fps auto-detection for ProDJLink -- CDJ sends ms,
// not frames. The user's fps selection IS the frame rate.
bool pdlHasTC = sharedProDJLink->hasTimecodeData(ep);
if (pdlHasTC)
{
juce::String pdlModel = sharedProDJLink->getPlayerModel(ep);
inputStatusText = isXfMode()
? ((proDJLinkPlayer == kPlayerXfA ? "XF-A" : "XF-B")
+ juce::String(" P") + juce::String(ep))
: ("RX P" + juce::String(ep));
if (pdlModel.isNotEmpty())
inputStatusText += " " + pdlModel;
if (!sharedProDJLink->isPositionMoving(ep))
inputStatusText += " " + sharedProDJLink->getPlayStateString(ep);
double pdlBpm = sharedProDJLink->getBPM(ep);
if (pdlBpm > 0.0)
inputStatusText += " | " + juce::String(pdlBpm, 1) + " BPM";
}
else
{
inputStatusText = "P" + juce::String(ep)
+ " " + sharedProDJLink->getPlayStateString(ep)
+ " - NO POSITION DATA";
}
if (pdlHasTC && trackMapEnabled
&& cachedTrackArtist.isNotEmpty() && cachedTrackTitle.isNotEmpty()
&& !cachedTrackTitle.startsWith("Track #"))
{
if (trackMapped)
inputStatusText += " | MAP: " + cachedTrackTitle;
else
inputStatusText += " | NO MAP";
}
inputStatusText += " | " + sharedProDJLink->getBindInfo();
}
else
{
inputStatusText = "WAITING";
auto discP = sharedProDJLink->getDiscoveredPlayers();
if (discP.isEmpty())
inputStatusText += " | NO PLAYERS";
else
inputStatusText += " | " + juce::String(discP.size()) + " PLAYER(S)";
inputStatusText += " | " + sharedProDJLink->getBindInfo();
}
// --- MIDI Clock ---
if (pdlRx && midiClockEnabled && triggerOutput.isMidiClockRunning())
{
double pdlClkBpm = sharedProDJLink->getMasterBPM();
pdlClkBpm = applyBpmMultiplier(pdlClkBpm, getEffectiveBpmMultiplier());
if (pdlClkBpm > 0.0 && std::abs((float)pdlClkBpm - lastSentClockBpm) > 0.05f)
{
triggerOutput.updateMidiClockBpm(pdlClkBpm);
lastSentClockBpm = (float)pdlClkBpm;
}
}
// --- Ableton Link ---
if (pdlRx && linkBridge.isEnabled())
{
double pdlLnkBpm = sharedProDJLink->getMasterBPM();
pdlLnkBpm = applyBpmMultiplier(pdlLnkBpm, getEffectiveBpmMultiplier());
if (pdlLnkBpm > 0.0)
linkBridge.setTempo(pdlLnkBpm);
}
// --- OSC BPM Forward ---
if (pdlRx && oscForwardEnabled && triggerOutput.isOscConnected())
{
double pdlOscBpm = sharedProDJLink->getMasterBPM();
pdlOscBpm = applyBpmMultiplier(pdlOscBpm, getEffectiveBpmMultiplier());
if (pdlOscBpm > 0.0 && std::abs((float)pdlOscBpm - lastSentOscBpm) > kOscBpmThreshold)
{
triggerOutput.sendOscFloat(oscFwdBpmAddr, (float)pdlOscBpm);
lastSentOscBpm = (float)pdlOscBpm;
}
}
// --- Mixer Fader Forward (OSC + MIDI CC) ---
// Requires DJM type-0x39 packets (Pioneer bridge on network).
// OSC: normalised float 0.0-1.0 on /mixer/ch1..4, /mixer/crossfader, /mixer/master
// MIDI CC: ch1=CC1, ch2=CC2, ch3=CC3, ch4=CC4, crossfader=CC5, master=CC7
if (sharedProDJLink->hasMixerFaderData()
&& mixerMapPtr != nullptr
&& (oscMixerForwardEnabled || midiMixerForwardEnabled || artnetMixerForwardEnabled))
{
forwardMixerParams();
}
// sourceActive: determined directly from CDJ playState + actualSpeed.
//
// PLAYING/LOOPING/CUE_PLAY: active while actualSpeed >= minimum
// (includes acceleration ramp -- output starts as speed ramps up)
// PAUSED: actualSpeed ramps target->0 in ~4-5s. Output naturally
// stops when speed drops below kMinEncodingPitch. No special case.
// END_TRACK: CDJ freezes actualSpeed (never ramps to 0).
// playState == END_TRACK tells us directly -> force inactive.
// NO_TRACK/LOADING/SEEKING: no useful timecode -> inactive.