-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStageLinQInput.h
More file actions
2694 lines (2401 loc) · 110 KB
/
StageLinQInput.h
File metadata and controls
2694 lines (2401 loc) · 110 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
//
// StageLinQInput -- Denon StageLinQ protocol implementation.
//
// Connects to Denon Engine OS hardware (SC5000, SC6000, Prime 4/2/Go,
// X1800, X1850) via the StageLinQ network protocol. Receives deck state,
// track metadata, mixer fader positions, and beat info.
//
// Protocol overview:
// 1. Discovery: UDP broadcast on port 51337 ("airD" magic, both sides)
// 2. Service request: TCP to the device's advertised port -> device replies with services
// 3. StateMap: TCP subscription to key/value paths (UTF-16BE + JSON)
// 4. BeatInfo: TCP binary stream (beat/totalBeats/BPM per deck)
//
// Protocol references (all MIT licensed):
// - chrisle/StageLinq (TypeScript) -- most complete implementation
// - icedream/go-stagelinq (Go) -- clean C-like reference
// - Jaxc/PyStageLinQ (Python) -- byte-level protocol documentation
//
// NOTE: This implementation is based entirely on the open-source reverse-
// engineering work cited above. No Denon hardware was available during
// development. Extensive logging is included for Wireshark-assisted
// debugging when hardware becomes available.
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include "NetworkUtils.h"
#include <atomic>
#include <array>
#include <cstring>
#include <mutex>
#include <map>
#include <set>
#include <vector>
#include <functional>
//==============================================================================
// Protocol constants
//==============================================================================
namespace StageLinQ
{
// Discovery UDP port -- all StageLinQ devices broadcast here
static constexpr int kDiscoveryPort = 51337;
// Magic bytes for discovery frames
static constexpr uint8_t kDiscoveryMagic[4] = { 'a', 'i', 'r', 'D' };
// Magic bytes for StateMap messages
static constexpr uint8_t kSmaaMagic[4] = { 0x73, 0x6D, 0x61, 0x61 }; // "smaa"
// StateMap sub-types (bytes 8-11 inside smaa block)
static constexpr uint32_t kSmaaStateEmit = 0x00000000; // device -> us: state value
static constexpr uint32_t kSmaaEmitResponse = 0x000007D1; // device -> us: subscription ack
static constexpr uint32_t kSmaaSubscribe = 0x000007D2; // us -> device: subscribe request
// TCP message IDs (first 4 bytes of TCP messages)
static constexpr uint32_t kMsgServiceAnnounce = 0x00000000;
static constexpr uint32_t kMsgReference = 0x00000001;
static constexpr uint32_t kMsgServiceRequest = 0x00000002;
// BeatInfo message types
static constexpr uint32_t kBeatStartStream = 0x00000000;
static constexpr uint32_t kBeatStopStream = 0x00000001;
static constexpr uint32_t kBeatEmit = 0x00000002;
// Connection action strings
static constexpr const char* kActionHowdy = "DISCOVERER_HOWDY_";
static constexpr const char* kActionExit = "DISCOVERER_EXIT_";
// Token length in bytes
static constexpr int kTokenLen = 16;
// Our identity
static constexpr const char* kOurDeviceName = "SuperTimecodeConverter";
static constexpr const char* kOurSwName = "STC";
static constexpr const char* kOurSwVersion = "1.7.0";
// Timing
static constexpr double kDiscoveryInterval = 1.0; // seconds between our announcements
static constexpr double kReferenceInterval = 0.25; // seconds between reference keepalives
static constexpr double kReconnectDelay = 3.0; // seconds before reconnect attempt
static constexpr int kSocketTimeoutMs = 2000; // TCP read timeout
static constexpr double kDeviceTimeoutSec = 5.0; // no discovery = device gone
// Maximum supported decks per device (Prime 4 has 4)
static constexpr int kMaxDecksPerDevice = 4;
// Maximum total decks (we map to STC players 1-4)
static constexpr int kMaxDecks = 4;
// Maximum mixer channels
static constexpr int kMaxMixerChannels = 4;
//==========================================================================
// Big-endian byte helpers
//==========================================================================
inline uint16_t readU16BE(const uint8_t* p) { return (uint16_t(p[0]) << 8) | p[1]; }
inline uint32_t readU32BE(const uint8_t* p) { return (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16)
| (uint32_t(p[2]) << 8) | p[3]; }
inline uint64_t readU64BE(const uint8_t* p) {
return (uint64_t(readU32BE(p)) << 32) | readU32BE(p + 4);
}
inline double readF64BE(const uint8_t* p) {
uint64_t raw = readU64BE(p);
double result;
std::memcpy(&result, &raw, 8);
return result;
}
inline void writeU16BE(uint8_t* p, uint16_t v) { p[0] = uint8_t(v >> 8); p[1] = uint8_t(v); }
inline void writeU32BE(uint8_t* p, uint32_t v) { p[0] = uint8_t(v >> 24); p[1] = uint8_t(v >> 16);
p[2] = uint8_t(v >> 8); p[3] = uint8_t(v); }
//==========================================================================
// UTF-16BE string encoding/decoding
//==========================================================================
// Encode ASCII/Latin1 string to UTF-16BE bytes.
// Returns a vector of the UTF-16BE encoded bytes (no length prefix).
inline std::vector<uint8_t> encodeUTF16BE(const juce::String& str)
{
std::vector<uint8_t> result;
result.reserve(str.length() * 2);
for (int i = 0; i < str.length(); ++i)
{
auto ch = (uint16_t)str[i];
result.push_back(uint8_t(ch >> 8));
result.push_back(uint8_t(ch & 0xFF));
}
return result;
}
// Decode UTF-16BE bytes to a juce::String.
inline juce::String decodeUTF16BE(const uint8_t* data, int byteLen)
{
int numChars = byteLen / 2;
if (numChars <= 0) return {};
// Build into a pre-allocated buffer to avoid O(n^2) appends
juce::String result;
result.preallocateBytes((size_t)(numChars + 1) * sizeof(juce::juce_wchar));
for (int i = 0; i + 1 < byteLen; i += 2)
{
juce::juce_wchar ch = (juce::juce_wchar(data[i]) << 8) | data[i + 1];
result += ch;
}
return result;
}
//==========================================================================
// Write a network string: [length:u32BE][UTF-16BE bytes]
//==========================================================================
inline void appendNetworkString(std::vector<uint8_t>& buf, const juce::String& str)
{
auto encoded = encodeUTF16BE(str);
uint8_t lenBytes[4];
writeU32BE(lenBytes, (uint32_t)encoded.size());
buf.insert(buf.end(), lenBytes, lenBytes + 4);
buf.insert(buf.end(), encoded.begin(), encoded.end());
}
//==========================================================================
// Read a network string from buffer at offset.
// Returns the new offset, or -1 on error.
//==========================================================================
inline int readNetworkString(const uint8_t* data, int dataLen, int offset, juce::String& out)
{
if (offset + 4 > dataLen) return -1;
uint32_t strLen = readU32BE(data + offset);
offset += 4;
if (offset + (int)strLen > dataLen) return -1;
out = decodeUTF16BE(data + offset, (int)strLen);
return offset + (int)strLen;
}
//==========================================================================
// JSON value parser for StateMap values
//
// StageLinQ StateMap values are NOT simple primitives. They are JSON
// objects with named fields (confirmed from chrisle/StageLinq Player.ts):
//
// {"string": "Artist Name"} -- text values (artist, title, paths)
// {"state": true} -- boolean values (play, songLoaded)
// {"value": 128.0} -- numeric values (BPM, volume, pitch)
// {"color": 12345} -- color values (jog colors)
//
// Some paths may also send the "type" field: {"type": 0, "value": 128.0}
//==========================================================================
struct JsonValue
{
enum Type { kNull, kBool, kInt, kDouble, kString };
Type type = kNull;
bool boolVal = false;
int64_t intVal = 0;
double doubleVal = 0.0;
juce::String stringVal;
bool asBool() const { return (type == kBool) ? boolVal : (intVal != 0); }
int asInt() const { return (type == kInt) ? (int)intVal : (type == kDouble) ? (int)doubleVal : (boolVal ? 1 : 0); }
double asDouble() const { return (type == kDouble) ? doubleVal : (type == kInt) ? (double)intVal : 0.0; }
juce::String asString() const { return stringVal; }
};
inline JsonValue parseJsonValue(const juce::String& json)
{
JsonValue v;
auto trimmed = json.trim();
if (trimmed.isEmpty()) return v;
// Try JUCE JSON parser first (handles objects, arrays, primitives)
auto parsed = juce::JSON::parse(trimmed);
if (auto* obj = parsed.getDynamicObject())
{
// Object: extract named fields per StageLinQ convention
// Priority: "string" > "state" > "value" > "color"
if (obj->hasProperty("string"))
{
v.type = JsonValue::kString;
v.stringVal = obj->getProperty("string").toString();
}
else if (obj->hasProperty("state"))
{
auto stateVal = obj->getProperty("state");
if (stateVal.isBool())
{
v.type = JsonValue::kBool;
v.boolVal = (bool)stateVal;
}
else
{
// PlayState sends state as integer
v.type = JsonValue::kInt;
v.intVal = (int64_t)(int)stateVal;
v.doubleVal = (double)(int)stateVal;
}
}
else if (obj->hasProperty("value"))
{
v.type = JsonValue::kDouble;
v.doubleVal = (double)obj->getProperty("value");
v.intVal = (int64_t)v.doubleVal;
}
else if (obj->hasProperty("color"))
{
v.type = JsonValue::kInt;
v.intVal = (int64_t)(int)obj->getProperty("color");
v.doubleVal = (double)v.intVal;
}
else
{
// Unknown object structure -- log the first few for debugging
v.type = JsonValue::kString;
v.stringVal = trimmed;
}
}
else if (parsed.isBool())
{
// Bare primitive (unlikely but handle gracefully)
v.type = JsonValue::kBool;
v.boolVal = (bool)parsed;
}
else if (parsed.isDouble() || parsed.isInt() || parsed.isInt64())
{
v.type = JsonValue::kDouble;
v.doubleVal = (double)parsed;
v.intVal = (int64_t)v.doubleVal;
}
else if (parsed.isString())
{
v.type = JsonValue::kString;
v.stringVal = parsed.toString();
}
return v;
}
//==========================================================================
// Token generation
//
// Known-good token from chrisle/StageLinq (SoundSwitch identity).
// Random tokens can fail silently on some firmware versions due to
// undocumented constraints. Both chrisle/StageLinq and djctl switched
// to pre-defined tokens after encountering issues with random generation.
//
// CRITICAL CONSTRAINT (from PyStageLinQ protocol docs): if the most
// significant bit of the token's first byte is 1, the device will
// silently ignore the service request and never reply with services.
// Our known-good token has byte[0]=0x52 (MSB=0), so this is safe.
// If you ever switch to random tokens, mask byte[0] with 0x7F.
//
// The SoundSwitch token is used by multiple third-party implementations
// and is known to work with all tested Denon firmware versions.
//==========================================================================
static constexpr uint8_t kKnownGoodToken[kTokenLen] = {
82, 253, 252, 7, 33, 130, 101, 79, 22, 63, 95, 15, 154, 98, 29, 114
};
inline void generateToken(uint8_t token[kTokenLen])
{
// Use the known-good SoundSwitch token for maximum compatibility
std::memcpy(token, kKnownGoodToken, kTokenLen);
}
//==========================================================================
// Build a discovery frame
//==========================================================================
inline std::vector<uint8_t> buildDiscoveryFrame(
const uint8_t token[kTokenLen],
const juce::String& deviceName,
const juce::String& action,
const juce::String& swName,
const juce::String& swVersion,
uint16_t servicePort)
{
std::vector<uint8_t> frame;
frame.reserve(256);
// Magic "airD"
frame.insert(frame.end(), kDiscoveryMagic, kDiscoveryMagic + 4);
// Token
frame.insert(frame.end(), token, token + kTokenLen);
// Network strings
appendNetworkString(frame, deviceName);
appendNetworkString(frame, action);
appendNetworkString(frame, swName);
appendNetworkString(frame, swVersion);
// Service port
uint8_t portBytes[2];
writeU16BE(portBytes, servicePort);
frame.push_back(portBytes[0]);
frame.push_back(portBytes[1]);
return frame;
}
//==========================================================================
// Build a service request frame (TCP)
//==========================================================================
inline std::vector<uint8_t> buildServiceRequest(const uint8_t token[kTokenLen])
{
std::vector<uint8_t> frame;
frame.reserve(20);
// Message ID: 0x00000002
uint8_t id[4];
writeU32BE(id, kMsgServiceRequest);
frame.insert(frame.end(), id, id + 4);
// Token
frame.insert(frame.end(), token, token + kTokenLen);
return frame;
}
//==========================================================================
// Build a service announcement frame (TCP, sent to service ports)
//==========================================================================
inline std::vector<uint8_t> buildServiceAnnouncement(
const uint8_t token[kTokenLen],
const juce::String& serviceName,
uint16_t port)
{
std::vector<uint8_t> frame;
frame.reserve(64);
uint8_t id[4];
writeU32BE(id, kMsgServiceAnnounce);
frame.insert(frame.end(), id, id + 4);
frame.insert(frame.end(), token, token + kTokenLen);
appendNetworkString(frame, serviceName);
uint8_t portBytes[2];
writeU16BE(portBytes, port);
frame.push_back(portBytes[0]);
frame.push_back(portBytes[1]);
return frame;
}
//==========================================================================
// Build a reference/keepalive frame (TCP)
//==========================================================================
inline std::vector<uint8_t> buildReferenceFrame(
const uint8_t ownToken[kTokenLen],
const uint8_t deviceToken[kTokenLen],
int64_t reference)
{
std::vector<uint8_t> frame;
frame.reserve(44);
uint8_t id[4];
writeU32BE(id, kMsgReference);
frame.insert(frame.end(), id, id + 4);
frame.insert(frame.end(), ownToken, ownToken + kTokenLen);
frame.insert(frame.end(), deviceToken, deviceToken + kTokenLen);
uint8_t refBytes[8] = {};
for (int i = 0; i < 8; ++i)
refBytes[i] = uint8_t(reference >> (56 - i * 8));
frame.insert(frame.end(), refBytes, refBytes + 8);
return frame;
}
//==========================================================================
// Build a StateMap subscribe frame
//==========================================================================
inline std::vector<uint8_t> buildStateMapSubscribe(const juce::String& path)
{
// Body: "smaa"[4] + subtype[4] + pathString(UTF16BE) + interval[4]
auto pathEncoded = encodeUTF16BE(path);
// Body size = 4(smaa) + 4(subtype) + 4(pathLen) + pathEncoded.size() + 4(interval)
uint32_t bodySize = 4 + 4 + 4 + (uint32_t)pathEncoded.size() + 4;
std::vector<uint8_t> frame;
frame.reserve(4 + bodySize);
// Length prefix
uint8_t lenBytes[4];
writeU32BE(lenBytes, bodySize);
frame.insert(frame.end(), lenBytes, lenBytes + 4);
// "smaa"
frame.insert(frame.end(), kSmaaMagic, kSmaaMagic + 4);
// Sub-type: subscribe
uint8_t subType[4];
writeU32BE(subType, kSmaaSubscribe);
frame.insert(frame.end(), subType, subType + 4);
// Path as network string
uint8_t pathLenBytes[4];
writeU32BE(pathLenBytes, (uint32_t)pathEncoded.size());
frame.insert(frame.end(), pathLenBytes, pathLenBytes + 4);
frame.insert(frame.end(), pathEncoded.begin(), pathEncoded.end());
// Interval (0)
uint8_t intervalBytes[4] = { 0, 0, 0, 0 };
frame.insert(frame.end(), intervalBytes, intervalBytes + 4);
return frame;
}
//==========================================================================
// Build a BeatInfo start-stream frame
//==========================================================================
inline std::vector<uint8_t> buildBeatInfoStart()
{
std::vector<uint8_t> frame;
uint8_t lenBytes[4];
writeU32BE(lenBytes, 4);
frame.insert(frame.end(), lenBytes, lenBytes + 4);
uint8_t magic[4];
writeU32BE(magic, kBeatStartStream);
frame.insert(frame.end(), magic, magic + 4);
return frame;
}
// Build a BeatInfo stop frame. Should be sent before closing the
// BeatInfo socket for a clean disconnect (otherwise the device only
// learns we left via TCP RST).
inline std::vector<uint8_t> buildBeatInfoStop()
{
std::vector<uint8_t> frame;
uint8_t lenBytes[4];
writeU32BE(lenBytes, 4);
frame.insert(frame.end(), lenBytes, lenBytes + 4);
uint8_t magic[4];
writeU32BE(magic, kBeatStopStream);
frame.insert(frame.end(), magic, magic + 4);
return frame;
}
//==========================================================================
// StateMap paths we subscribe to for each deck
//==========================================================================
inline juce::StringArray getDeckPaths(int deckNum)
{
juce::String d = "/Engine/Deck" + juce::String(deckNum);
return {
// Playback state
d + "/Play",
d + "/PlayState",
d + "/PlayStatePath",
d + "/CurrentBPM",
d + "/Speed",
d + "/SpeedState",
d + "/SpeedNeutral",
d + "/SpeedRange",
d + "/SpeedOffsetUp",
d + "/SpeedOffsetDown",
d + "/SyncMode",
d + "/ExternalMixerVolume",
d + "/ExternalScratchWheelTouch",
d + "/Pads/View",
// Track metadata
d + "/Track/ArtistName",
d + "/Track/SongName",
d + "/Track/TrackName",
d + "/Track/TrackLength",
d + "/Track/SongLoaded",
d + "/Track/SongAnalyzed",
d + "/Track/CurrentBPM",
d + "/Track/CurrentKeyIndex",
d + "/Track/KeyLock",
d + "/Track/CuePosition",
d + "/Track/SampleRate",
d + "/Track/TrackNetworkPath",
d + "/Track/TrackUri",
d + "/Track/TrackData",
d + "/Track/TrackBytes",
d + "/Track/TrackWasPlayed",
d + "/Track/Bleep",
d + "/Track/SoundSwitchGuid",
d + "/Track/PlayPauseLEDState",
// Live loop state
d + "/Track/CurrentLoopInPosition",
d + "/Track/CurrentLoopOutPosition",
d + "/Track/CurrentLoopSizeInBeats",
d + "/Track/LoopEnableState",
d + "/Track/Loop/QuickLoop1",
d + "/Track/Loop/QuickLoop2",
d + "/Track/Loop/QuickLoop3",
d + "/Track/Loop/QuickLoop4",
d + "/Track/Loop/QuickLoop5",
d + "/Track/Loop/QuickLoop6",
d + "/Track/Loop/QuickLoop7",
d + "/Track/Loop/QuickLoop8",
// DeckIsMaster lives under /Client, not /Engine
"/Client/Deck" + juce::String(deckNum) + "/DeckIsMaster",
};
}
inline juce::StringArray getMixerPaths()
{
return {
"/Mixer/CH1faderPosition",
"/Mixer/CH2faderPosition",
"/Mixer/CH3faderPosition",
"/Mixer/CH4faderPosition",
"/Mixer/CrossfaderPosition",
"/Mixer/ChannelAssignment1",
"/Mixer/ChannelAssignment2",
"/Mixer/ChannelAssignment3",
"/Mixer/ChannelAssignment4",
"/Mixer/NumberOfChannels",
};
}
inline juce::StringArray getGlobalPaths()
{
return {
"/Engine/DeckCount",
"/Engine/Master/MasterTempo",
"/Engine/Sync/Network/MasterStatus",
"/Client/Preferences/LayerA",
"/Client/Preferences/LayerB",
"/Client/Preferences/Player",
"/Client/Preferences/PlayerJogColorA",
"/Client/Preferences/PlayerJogColorB",
"/Client/Preferences/Profile/Application/SyncMode",
"/Client/Preferences/Profile/Application/PlayerColor1",
"/Client/Preferences/Profile/Application/PlayerColor1A",
"/Client/Preferences/Profile/Application/PlayerColor1B",
"/Client/Preferences/Profile/Application/PlayerColor2",
"/Client/Preferences/Profile/Application/PlayerColor2A",
"/Client/Preferences/Profile/Application/PlayerColor2B",
"/Client/Preferences/Profile/Application/PlayerColor3",
"/Client/Preferences/Profile/Application/PlayerColor3A",
"/Client/Preferences/Profile/Application/PlayerColor3B",
"/Client/Preferences/Profile/Application/PlayerColor4",
"/Client/Preferences/Profile/Application/PlayerColor4A",
"/Client/Preferences/Profile/Application/PlayerColor4B",
"/Client/Librarian/DevicesController/CurrentDevice",
"/Client/Librarian/DevicesController/HasSDCardConnected",
"/Client/Librarian/DevicesController/HasUsbDeviceConnected",
"/GUI/Decks/Deck/ActiveDeck",
"/GUI/ViewLayer/LayerB",
};
}
//==========================================================================
// Convert playhead position (ms) to SMPTE Timecode
//==========================================================================
inline Timecode playheadToTimecode(uint32_t playheadMs, FrameRate fps)
{
return wallClockToTimecode(double(playheadMs), fps);
}
}
//==============================================================================
// Per-deck state -- atomics for cross-thread access
//==============================================================================
struct StageLinQDeckState
{
std::atomic<bool> active { false }; // deck exists / has data
std::atomic<int> deckNumber { 0 }; // 1-4
// Playback
std::atomic<bool> isPlaying { false }; // from /Engine/DeckN/Play
std::atomic<int> playState { 0 }; // from /Engine/DeckN/PlayState
std::atomic<double> currentBPM { 0.0 }; // from /Engine/DeckN/CurrentBPM
std::atomic<double> speed { 0.0 }; // from /Engine/DeckN/Speed (pitch multiplier)
std::atomic<bool> speedReceived { false }; // true once Speed path has sent at least one value
std::atomic<int> speedState { 0 }; // from /Engine/DeckN/SpeedState
std::atomic<double> speedNeutral { 1.0 }; // from SpeedNeutral (pitch at 0%)
std::atomic<double> speedRange { 0.08 }; // from SpeedRange (+/-8% default)
std::atomic<double> speedOffsetUp { 0.0 }; // from SpeedOffsetUp (pitch bend)
std::atomic<double> speedOffsetDown { 0.0 }; // from SpeedOffsetDown (pitch bend)
std::atomic<int> syncMode { 0 }; // from SyncMode
std::atomic<bool> scratchWheelTouch { false }; // from ExternalScratchWheelTouch
std::atomic<int> padsView { 0 }; // from Pads/View
std::atomic<bool> bleep { false }; // from Track/Bleep (reverse mode)
// Track metadata
juce::String artistName; // guarded by metaMutex
juce::String songName; // guarded by metaMutex
juce::String trackNetworkPath; // from Track/TrackNetworkPath (guarded by metaMutex)
juce::String trackUri; // from Track/TrackUri (streaming) (guarded by metaMutex)
juce::String soundSwitchGuid; // from Track/SoundSwitchGuid (guarded by metaMutex)
std::atomic<double> trackLength { 0.0 }; // seconds, from Track/TrackLength
std::atomic<bool> songLoaded { false }; // from Track/SongLoaded
std::atomic<bool> songAnalyzed { false }; // from Track/SongAnalyzed
std::atomic<double> trackBPM { 0.0 }; // from Track/CurrentBPM
std::atomic<double> cuePosition { 0.0 }; // from Track/CuePosition
std::atomic<int> currentKeyIndex { -1 }; // from Track/CurrentKeyIndex (live, changes with key shift)
std::atomic<bool> keyLock { false }; // from Track/KeyLock
std::atomic<double> sampleRate { 44100.0 }; // from Track/SampleRate
std::atomic<int> trackBytes { 0 }; // from Track/TrackBytes (file size)
std::atomic<bool> trackWasPlayed { false }; // from Track/TrackWasPlayed
std::atomic<int> playPauseLEDState { 0 }; // from Track/PlayPauseLEDState
// Live loop state (sample offsets, from StateMap -- real-time, not from DB)
std::atomic<double> loopInPosition { -1.0 }; // from Track/CurrentLoopInPosition (samples)
std::atomic<double> loopOutPosition { -1.0 }; // from Track/CurrentLoopOutPosition (samples)
std::atomic<double> loopSizeInBeats { 0.0 }; // from Track/CurrentLoopSizeInBeats
std::atomic<bool> loopEnabled { false }; // from Track/LoopEnableState
std::atomic<bool> quickLoops[8] = {}; // from Track/Loop/QuickLoop1-8
// From BeatInfo service
std::atomic<double> beatInfoBeat { 0.0 }; // current beat position
std::atomic<double> beatInfoTotalBeats { 0.0 }; // total beats in track
std::atomic<double> beatInfoBPM { 0.0 }; // BPM from BeatInfo
std::atomic<double> beatInfoTimeline { 0.0 }; // timeline position (ms?)
// Mixer (per-channel)
std::atomic<double> faderPosition { 0.0 }; // from /Mixer/CH{N}faderPosition (0-1)
std::atomic<double> externalVolume { 0.0 }; // from ExternalMixerVolume
std::atomic<bool> isMaster { false }; // from /Client/DeckN/DeckIsMaster
std::atomic<int> channelAssignment { 0 }; // from /Mixer/ChannelAssignment{N} (deck->channel map)
// Timing
std::atomic<double> lastUpdateTime { 0.0 }; // juce hiRes ms
std::atomic<uint32_t> trackVersion { 0 }; // incremented on track change
// Derived playhead in ms (computed from beatInfo timeline or speed+time)
std::atomic<uint32_t> playheadMs { 0 };
mutable std::mutex metaMutex;
void reset()
{
active.store(false, std::memory_order_release);
deckNumber.store(0);
isPlaying.store(false);
playState.store(0);
currentBPM.store(0.0);
speed.store(0.0);
speedReceived.store(false);
speedState.store(0);
speedNeutral.store(1.0);
speedRange.store(0.08);
speedOffsetUp.store(0.0);
speedOffsetDown.store(0.0);
syncMode.store(0);
scratchWheelTouch.store(false);
padsView.store(0);
bleep.store(false);
{
std::lock_guard<std::mutex> lock(metaMutex);
artistName.clear();
songName.clear();
trackNetworkPath.clear();
trackUri.clear();
soundSwitchGuid.clear();
}
trackLength.store(0.0);
songLoaded.store(false);
songAnalyzed.store(false);
trackBPM.store(0.0);
cuePosition.store(0.0);
currentKeyIndex.store(-1);
keyLock.store(false);
sampleRate.store(44100.0);
trackBytes.store(0);
trackWasPlayed.store(false);
playPauseLEDState.store(0);
loopInPosition.store(-1.0);
loopOutPosition.store(-1.0);
loopSizeInBeats.store(0.0);
loopEnabled.store(false);
for (auto& ql : quickLoops) ql.store(false);
beatInfoBeat.store(0.0);
beatInfoTotalBeats.store(0.0);
beatInfoBPM.store(0.0);
beatInfoTimeline.store(0.0);
faderPosition.store(0.0);
externalVolume.store(0.0);
isMaster.store(false);
channelAssignment.store(0);
lastUpdateTime.store(0.0);
trackVersion.store(0);
playheadMs.store(0);
}
};
//==============================================================================
// Mixer state (crossfader, global)
//==============================================================================
struct StageLinQMixerState
{
std::atomic<double> crossfaderPosition { 0.0 }; // 0=left, 0.5=center, 1=right
std::atomic<double> masterBPM { 0.0 }; // from /Engine/Master/MasterTempo
std::atomic<int> numChannels { 0 }; // from /Mixer/NumberOfChannels
// Deck ring LED colors (from /Client/Preferences/Profile/Application/PlayerColorN)
// Index 0-3 = deck 1-4. Each has base, A (layer A), B (layer B) variants.
// Value is an integer color from Engine OS (interpretation TBD with hardware).
std::atomic<int> playerColor[4] = {}; // PlayerColor1-4
std::atomic<int> playerColorA[4] = {}; // PlayerColor1A-4A
std::atomic<int> playerColorB[4] = {}; // PlayerColor1B-4B
};
//==============================================================================
// Discovered device info
//==============================================================================
struct StageLinQDeviceInfo
{
juce::String ip;
juce::String deviceName;
juce::String swName;
juce::String swVersion;
uint16_t servicePort = 0;
uint8_t token[StageLinQ::kTokenLen] = {};
double lastSeenTime = 0.0; // hiRes ms -- updated on each discovery frame
double lastConnectAttempt = 0.0; // hiRes ms -- for reconnect cooldown
int deckCount = 0; // from /Engine/DeckCount or default 2
bool connected = false;
};
//==============================================================================
// StageLinQInput -- main network handler
//==============================================================================
class StageLinQInput : public juce::Thread
{
public:
//--------------------------------------------------------------------------
// TrackInfo -- per-deck track metadata (matches ProDJLinkInput::TrackInfo)
//--------------------------------------------------------------------------
struct TrackInfo
{
juce::String artist;
juce::String title;
};
//--------------------------------------------------------------------------
StageLinQInput()
: Thread("StageLinQ Input")
{
for (auto& d : decks) d.reset();
StageLinQ::generateToken(ownToken);
}
~StageLinQInput() override
{
stop();
}
//==========================================================================
// Network interface management
//==========================================================================
void refreshNetworkInterfaces()
{
availableInterfaces = ::getNetworkInterfaces();
}
juce::StringArray getInterfaceNames() const
{
juce::StringArray names;
for (auto& ni : availableInterfaces)
names.add(ni.name + " (" + ni.ip + ")");
return names;
}
int getInterfaceCount() const { return availableInterfaces.size(); }
juce::String getBindInfo() const { return bindIp; }
int getSelectedInterface() const { return selectedInterface; }
//==========================================================================
// Start / Stop
//==========================================================================
bool start(int interfaceIndex = 0)
{
if (isRunningFlag.load(std::memory_order_relaxed))
return true;
refreshNetworkInterfaces();
if (availableInterfaces.isEmpty())
{
DBG("StageLinQ: No network interfaces available");
return false;
}
int idx = juce::jlimit(0, availableInterfaces.size() - 1, interfaceIndex);
const auto& iface = availableInterfaces[idx];
bindIp = iface.ip;
selectedInterface = idx;
// Reset all decks
for (auto& d : decks) d.reset();
// Clear discovered devices
{
std::lock_guard<std::mutex> lock(devicesMutex);
discoveredDevices.clear();
}
// Generate fresh token each start
StageLinQ::generateToken(ownToken);
isRunningFlag.store(true, std::memory_order_release);
startThread(juce::Thread::Priority::normal);
DBG("StageLinQ: Started on " + bindIp);
return true;
}
void stop()
{
if (!isRunningFlag.load(std::memory_order_relaxed))
return;
isRunningFlag.store(false, std::memory_order_release);
signalThreadShouldExit();
// Close sockets to unblock reads
{
std::lock_guard<std::mutex> lock(socketMutex);
if (discoverySocket)
{
discoverySocket->shutdown();
discoverySocket.reset();
}
}
// Close all device connections
closeAllDeviceConnections();
stopThread(3000);
for (auto& d : decks) d.reset();
DBG("StageLinQ: Stopped");
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_acquire); }
// Callbacks for database integration (set by MainComponent to avoid
// circular header dependency with StageLinQDbClient).
// onMetadataRequest: called when a new TrackNetworkPath arrives.
// onFileTransferAvailable: called when a device's FileTransfer port is discovered.
std::function<void(const juce::String& networkPath)> onMetadataRequest;
std::function<void(const juce::String& ip, uint16_t port, const uint8_t* token)> onFileTransferAvailable;
//==========================================================================
// Public getters -- match ProDJLinkInput API patterns
//==========================================================================
// Deck number is 1-based (1-4)
bool isDeckActive(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return false;
return decks[idx].active.load(std::memory_order_acquire);
}
bool isPlayerPlaying(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return false;
return decks[idx].isPlaying.load(std::memory_order_relaxed);
}
uint32_t getPlayheadMs(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 0;
return decks[idx].playheadMs.load(std::memory_order_relaxed);
}
double getBPM(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 0.0;
// Prefer BeatInfo BPM (higher rate), fall back to StateMap
double biBpm = decks[idx].beatInfoBPM.load(std::memory_order_relaxed);
if (biBpm > 0.0) return biBpm;
return decks[idx].currentBPM.load(std::memory_order_relaxed);
}
double getActualSpeed(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 0.0;
double spd = decks[idx].speed.load(std::memory_order_relaxed);
// Fall back to 1.0 ONLY if the Speed path has NEVER sent a value.
// Some firmware versions may not emit Speed at all (chrisle/StageLinq
// doesn't even subscribe to it). Without the fallback, the PLL gets
// 0 velocity forever and timecode interpolation stops.
//
// Previously this checked isPlaying instead of speedReceived, which
// caused a race: if Speed=0.0 (pause) arrived before Play=false
// (two different StateMap paths, order not guaranteed), the fallback
// returned 1.0 -- telling the PLL we're at full speed when actually
// stopped. Using speedReceived avoids this: once Speed has sent any
// value (including 0.0 for pause), we trust it.
if (spd == 0.0 && !decks[idx].speedReceived.load(std::memory_order_relaxed))
return 1.0;
return spd;
}
uint32_t getTrackLengthSec(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 0;
return (uint32_t)decks[idx].trackLength.load(std::memory_order_relaxed);
}
float getPlayPositionRatio(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 0.0f;
double len = decks[idx].trackLength.load(std::memory_order_relaxed);
if (len <= 0.0) return 0.0f;
double posMs = (double)decks[idx].playheadMs.load(std::memory_order_relaxed);
return juce::jlimit(0.0f, 1.0f, (float)(posMs / (len * 1000.0)));
}
TrackInfo getTrackInfo(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return {};
std::lock_guard<std::mutex> lock(decks[idx].metaMutex);
return { decks[idx].artistName, decks[idx].songName };
}
juce::String getTrackNetworkPath(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return {};
std::lock_guard<std::mutex> lock(decks[idx].metaMutex);
return decks[idx].trackNetworkPath;
}
// --- New getters for extended StateMap data ---
int getCurrentKeyIndex(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return -1;
return decks[idx].currentKeyIndex.load(std::memory_order_relaxed);
}
juce::String getCurrentKeyString(int deckNum) const
{
int keyIdx = getCurrentKeyIndex(deckNum);
if (keyIdx < 0 || keyIdx > 23) return {};
static const char* const keys[] = {
"C", "Am", "G", "Em", "D", "Bm",
"A", "F#m", "E", "Dbm", "B", "Abm",
"F#", "Ebm", "Db", "Bbm", "Ab", "Fm",
"Eb", "Cm", "Bb", "Gm", "F", "Dm"
};
return keys[keyIdx];
}
bool getKeyLock(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return false;
return decks[idx].keyLock.load(std::memory_order_relaxed);
}
double getSampleRate(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 44100.0;
return decks[idx].sampleRate.load(std::memory_order_relaxed);
}
double getSpeedRange(int deckNum) const
{
int idx = deckNum - 1;
if (idx < 0 || idx >= StageLinQ::kMaxDecks) return 0.08;