Repository navigation
Expand file tree
/
Copy pathStageLinQDbClient.h
More file actions
1777 lines (1555 loc) · 72.2 KB
/
Copy pathStageLinQDbClient.h
File metadata and controls
1777 lines (1555 loc) · 72.2 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
//
// StageLinQDbClient -- Database client for Denon StageLinQ devices.
//
// Connects to the FileTransfer service ("fltx" protocol), downloads the
// Engine Library SQLite database, and provides track metadata + artwork
// lookup. Parallels DbServerClient for Pioneer.
//
// Protocol reference: chrisle/StageLinq (MIT) -- services/FileTransfer.ts
//
// Flow:
// 1. Connect to FileTransfer service port (from service handshake)
// 2. getSources() -> list media locations (USB/SD)
// 3. Download /{source}/Engine Library/Database2/m.db (or v1 fallback)
// 4. Open with SQLite, cache track metadata + artwork
// 5. On TrackNetworkPath change: lookup Track -> AlbumArt -> juce::Image
//
// Requires: sqlite3 amalgamation (sqlite3.h + sqlite3.c) in the project.
#pragma once
#include <JuceHeader.h>
#include "StageLinQInput.h"
#include <atomic>
#include <mutex>
#include <map>
#include <vector>
#include <cstring>
// SQLite amalgamation -- add sqlite3.c to your build (CMake: add_library)
#include "sqlite3.h"
//==============================================================================
// FileTransfer protocol constants ("fltx")
//==============================================================================
namespace StageLinQ
{
// FileTransfer magic
static constexpr uint8_t kFltxMagic[4] = { 'f', 'l', 't', 'x' };
// Request sub-types (us -> device)
static constexpr uint32_t kFltxRequestStat = 0x000007D1;
static constexpr uint32_t kFltxRequestSources = 0x000007D2;
static constexpr uint32_t kFltxRequestTransferId = 0x000007D4;
static constexpr uint32_t kFltxRequestChunkRange = 0x000007D5;
static constexpr uint32_t kFltxTransferComplete = 0x000007D6;
// Response message IDs (device -> us, after fltx[4] + 0x00000000[4])
static constexpr uint32_t kFltxRespFileStat = 1;
static constexpr uint32_t kFltxRespEndOfMessage = 2;
static constexpr uint32_t kFltxRespSourceLocations = 3;
static constexpr uint32_t kFltxRespTransferId = 4;
static constexpr uint32_t kFltxRespChunk = 5;
static constexpr uint32_t kFltxRespUnknown8 = 8; // unsolicited, the string "1" (see fltxWaitFor)
static constexpr uint32_t kFltxRespDisconnect = 9;
static constexpr int kFltxChunkSize = 4096;
// Caps on sizes that come off the wire or out of the device's database
// (AUDIT WIRE-1, WIRE-2). Each is compared in unsigned arithmetic of the
// field's own width before any cast, multiply or add.
// - A downloaded database is held in memory before it is written to a
// temp file: 1 GiB is well above any Engine library seen (and above
// what the 30 s download allows on a LAN), and keeps a corrupt size
// from asking for 4 GiB.
// - An Engine DJ BLOB declares its uncompressed size; nothing decoded
// here (overview waveform, cues, beat grid) comes near 10 MiB.
static constexpr uint32_t kMaxDbFileBytes = 1u << 30;
static constexpr int32_t kMaxBlobBytes = 10 * 1024 * 1024;
//==========================================================================
// Build fltx request frames (with length prefix)
//==========================================================================
// requestStat: fltx + 0x0 + 0x7D1 + path_netstr
inline std::vector<uint8_t> buildFltxStat(const juce::String& path)
{
// Body
std::vector<uint8_t> body;
body.insert(body.end(), kFltxMagic, kFltxMagic + 4);
uint8_t zero4[4] = {}; body.insert(body.end(), zero4, zero4 + 4);
uint8_t sub[4]; writeU32BE(sub, kFltxRequestStat);
body.insert(body.end(), sub, sub + 4);
appendNetworkString(body, path);
// Length prefix + body
std::vector<uint8_t> frame;
uint8_t len[4]; writeU32BE(len, (uint32_t)body.size());
frame.insert(frame.end(), len, len + 4);
frame.insert(frame.end(), body.begin(), body.end());
return frame;
}
// requestSources: fltx + 0x0 + 0x7D2 + 0x0
inline std::vector<uint8_t> buildFltxSources()
{
std::vector<uint8_t> body;
body.insert(body.end(), kFltxMagic, kFltxMagic + 4);
uint8_t zero4[4] = {}; body.insert(body.end(), zero4, zero4 + 4);
uint8_t sub[4]; writeU32BE(sub, kFltxRequestSources);
body.insert(body.end(), sub, sub + 4);
body.insert(body.end(), zero4, zero4 + 4);
std::vector<uint8_t> frame;
uint8_t len[4]; writeU32BE(len, (uint32_t)body.size());
frame.insert(frame.end(), len, len + 4);
frame.insert(frame.end(), body.begin(), body.end());
return frame;
}
// requestFileTransferId: fltx + 0x0 + 0x7D4 + path_netstr + 0x0
inline std::vector<uint8_t> buildFltxTransferId(const juce::String& path)
{
std::vector<uint8_t> body;
body.insert(body.end(), kFltxMagic, kFltxMagic + 4);
uint8_t zero4[4] = {}; body.insert(body.end(), zero4, zero4 + 4);
uint8_t sub[4]; writeU32BE(sub, kFltxRequestTransferId);
body.insert(body.end(), sub, sub + 4);
appendNetworkString(body, path);
body.insert(body.end(), zero4, zero4 + 4);
std::vector<uint8_t> frame;
uint8_t len[4]; writeU32BE(len, (uint32_t)body.size());
frame.insert(frame.end(), len, len + 4);
frame.insert(frame.end(), body.begin(), body.end());
return frame;
}
// requestChunkRange: fltx + 0x0 + 0x7D5 + 0x0 + txid + 0x0 + startChunk + 0x0 + endChunk
inline std::vector<uint8_t> buildFltxChunkRange(uint32_t txid, uint32_t startChunk, uint32_t endChunk)
{
std::vector<uint8_t> body;
body.insert(body.end(), kFltxMagic, kFltxMagic + 4);
uint8_t zero4[4] = {}; body.insert(body.end(), zero4, zero4 + 4);
uint8_t sub[4]; writeU32BE(sub, kFltxRequestChunkRange);
body.insert(body.end(), sub, sub + 4);
body.insert(body.end(), zero4, zero4 + 4);
uint8_t txBytes[4]; writeU32BE(txBytes, txid);
body.insert(body.end(), txBytes, txBytes + 4);
body.insert(body.end(), zero4, zero4 + 4);
uint8_t startBytes[4]; writeU32BE(startBytes, startChunk);
body.insert(body.end(), startBytes, startBytes + 4);
body.insert(body.end(), zero4, zero4 + 4);
uint8_t endBytes[4]; writeU32BE(endBytes, endChunk);
body.insert(body.end(), endBytes, endBytes + 4);
std::vector<uint8_t> frame;
uint8_t len[4]; writeU32BE(len, (uint32_t)body.size());
frame.insert(frame.end(), len, len + 4);
frame.insert(frame.end(), body.begin(), body.end());
return frame;
}
// signalTransferComplete: fltx + 0x0 + 0x7D6
inline std::vector<uint8_t> buildFltxComplete()
{
std::vector<uint8_t> body;
body.insert(body.end(), kFltxMagic, kFltxMagic + 4);
uint8_t zero4[4] = {}; body.insert(body.end(), zero4, zero4 + 4);
uint8_t sub[4]; writeU32BE(sub, kFltxTransferComplete);
body.insert(body.end(), sub, sub + 4);
std::vector<uint8_t> frame;
uint8_t len[4]; writeU32BE(len, (uint32_t)body.size());
frame.insert(frame.end(), len, len + 4);
frame.insert(frame.end(), body.begin(), body.end());
return frame;
}
}
//==============================================================================
// Parsed fltx response
//==============================================================================
struct FltxResponse
{
bool received = false; // a complete message was read
uint32_t code = 0; // non-zero: the device's periodic message (chrisle: "timecode")
uint32_t messageId = 0;
// SourceLocations
juce::StringArray sources;
// FileStat
uint32_t fileSize = 0;
// FileTransferId
uint32_t txFileSize = 0;
uint32_t txId = 0;
// FileTransferChunk
uint32_t chunkOffset = 0;
uint32_t chunkSize = 0;
std::vector<uint8_t> chunkData;
};
//==============================================================================
// Cached track metadata from SQLite
//==============================================================================
struct DenonTrackMeta
{
juce::String artist;
juce::String title;
juce::String album;
juce::String genre;
juce::String key;
double bpm = 0.0;
double length = 0.0;
int albumArtId = 0;
bool valid = false;
};
//==============================================================================
// Decoded overview waveform (3 bytes per entry: mid, high, low for WaveformDisplay)
//==============================================================================
struct DenonWaveformData
{
std::vector<uint8_t> data; // 3 bytes per entry, reordered to mid/high/low
int entryCount = 0;
bool valid = false;
};
//==============================================================================
// Quick cue point (from quickCues BLOB)
//==============================================================================
struct DenonQuickCue
{
juce::String label;
double sampleOffset = -1.0; // -1 = not set
uint8_t r = 0, g = 0, b = 0, a = 255;
bool isSet() const { return sampleOffset >= 0.0; }
};
//==============================================================================
// Loop region (from loops BLOB)
//==============================================================================
struct DenonLoop
{
juce::String label;
double startSampleOffset = 0.0;
double endSampleOffset = 0.0;
bool startSet = false;
bool endSet = false;
uint8_t r = 0, g = 0, b = 0, a = 255;
};
//==============================================================================
// Beat grid marker (from beatData BLOB)
//==============================================================================
struct DenonBeatGridMarker
{
double sampleOffset = 0.0;
int64_t beatNumber = 0;
int32_t numBeats = 0;
};
//==============================================================================
// Complete performance data for a track
//==============================================================================
struct DenonPerformanceData
{
// Quick cues (up to 8)
std::vector<DenonQuickCue> quickCues;
double mainCueSampleOffset = 0.0;
// Loops (up to 8)
std::vector<DenonLoop> loops;
// Beat grid
std::vector<DenonBeatGridMarker> beatGrid;
double sampleRate = 0.0;
double totalSamples = 0.0;
bool valid = false;
};
//==============================================================================
// Musical key index -> string (from libdjinterop musical_key enum)
// Engine DJ stores key as integer in Track table column 'key'
//==============================================================================
inline juce::String musicalKeyToString(int keyIndex)
{
// Camelot-style ordering from Engine DJ (same as libdjinterop::musical_key)
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"
};
if (keyIndex >= 0 && keyIndex < 24)
return keys[keyIndex];
return {};
}
//==============================================================================
// StageLinQDbClient -- FileTransfer + SQLite database client
//==============================================================================
class StageLinQDbClient : public juce::Thread
{
public:
StageLinQDbClient()
: Thread("SLQ-DB")
{
}
~StageLinQDbClient() override
{
stop();
}
//--------------------------------------------------------------------------
// Start: serve the database of the device at ip, FileTransfer port
// fileTransferPort. Called on a StageLinQ connection thread
// (onFileTransferAvailable) each time a device's services are found,
// i.e. on every (re)connection. It only records what is wanted and
// wakes this client's thread, which runs the sessions: it never waits
// for one (StageLinQ::kConnectionStopMs counts on that).
// - While a session is wanted, another device's offer is ignored: one
// database, the first device's (AUDIT SLQ-3). The same device on
// the same port (a reconnection) keeps what is loaded. A device is
// its IP: a unit that restarts on another address (DHCP) counts as
// another device, and the database it had before stays in use for
// as long as that session is wanted -- a rebooted peer does not end
// it.
// - The same device on another port has restarted its services: the
// session ends and the database is fetched again (AUDIT SLQ-9). The
// two #23 captures saw the PRIME 4+ on different ports (and
// addresses); within the second one port served two of STC's
// connections, so a reconnection on the same port is not taken for
// a restart.
// - After a session failed (no sources, download or open failed, the
// device gone), the last offer ignored while a session was wanted --
// another device's, or the same device's again -- starts a new one,
// also when it was ignored before the session's own device restarted
// (the bullet above); without one, the next device to offer
// FileTransfer does. An ignored offer of the session's own device
// (a reconnection on its port) does not replace another device's:
// when the session fails, the other device is tried, not the one
// that just failed. Trade-off: when the session's device itself
// recovers (the failure was transient) after re-offering on its
// port, the other unit's deferred offer is still served, not the
// session's device again, and that unit's database stays in use
// while its session holds -- AUDIT SLQ-3's first-device rule gives
// way. Before, an offer made during a session that then failed was
// lost for good: a second unit was not fetched until it reconnected
// (AUDIT SLQ-9).
// start() and stop() are serialised. MainComponent calls stop() only
// after StageLinQInput::stop() has joined the connection threads, so a
// start() does not wait on a stop() there.
//--------------------------------------------------------------------------
bool start(const juce::String& ip, uint16_t fileTransferPort,
const uint8_t tkn[StageLinQ::kTokenLen])
{
std::lock_guard<std::mutex> life(lifecycleMutex);
{
std::lock_guard<std::mutex> lock(targetMutex);
if (isRunningFlag.load())
{
if (ip != targetIp || fileTransferPort == targetPort)
{
// Ignored while this session is wanted; kept in case it
// fails (run). The latest one replaces an earlier one,
// except that the session's own device does not replace
// another device's (AUDIT SLQ-9).
if (ip != targetIp || !haveDeferred || deferredIp == ip)
{
deferredIp = ip;
deferredPort = fileTransferPort;
std::memcpy(deferredToken, tkn, StageLinQ::kTokenLen);
haveDeferred = true;
}
return true;
}
DBG("StageLinQ DB: " + ip + " is back on FileTransfer port "
+ juce::String(fileTransferPort) + " -- fetching its database again");
}
// The offer served now supersedes an earlier one of its own
// device; another device's is kept, in case this session fails.
if (haveDeferred && deferredIp == ip)
haveDeferred = false;
targetIp = ip;
targetPort = fileTransferPort;
std::memcpy(targetToken, tkn, StageLinQ::kTokenLen);
targetSerial.store(targetSerial.load() + 1);
isRunningFlag.store(true);
}
// The thread lives from the first start() to stop(), between
// sessions too, so it is either running or fully stopped here
if (isThreadRunning())
notify(); // idle, or in a session to end
else if (!startThread(juce::Thread::Priority::normal))
isRunningFlag.store(false); // no thread: the next offer tries again
return true;
}
// Message thread. Ends the session and the thread; the database and
// its temp file are closed, the caches kept until the next session.
void stop()
{
std::lock_guard<std::mutex> life(lifecycleMutex);
{
std::lock_guard<std::mutex> lock(targetMutex);
isRunningFlag.store(false);
haveDeferred = false;
}
if (!isThreadRunning()) return;
signalThreadShouldExit();
closeFtSocket(); // ends a blocking read at once
if (!stopThread(5000))
closeDatabase(); // the thread closes it, unless it was killed
DBG("StageLinQ DB: Stopped");
}
bool getIsRunning() const { return isRunningFlag.load(); }
//--------------------------------------------------------------------------
// Public getters (thread-safe)
//--------------------------------------------------------------------------
// Lookup track by network path (e.g. from StateMap TrackNetworkPath)
DenonTrackMeta getTrackByNetworkPath(const juce::String& networkPath) const
{
// Parse network path: net://uuid/source/Engine Library/Music/path
auto trackPath = parseNetworkPathToDbPath(networkPath);
if (trackPath.isEmpty()) return {};
std::lock_guard<std::mutex> lock(cacheMutex);
auto it = trackCache.find(trackPath.toStdString());
if (it != trackCache.end())
return it->second;
return {};
}
// Get artwork image for a track
juce::Image getArtwork(int albumArtId) const
{
if (albumArtId <= 0) return {};
std::lock_guard<std::mutex> lock(cacheMutex);
auto it = artworkCache.find(albumArtId);
if (it != artworkCache.end())
return it->second;
return {};
}
// Get artwork image by network path (convenience)
juce::Image getArtworkForTrack(const juce::String& networkPath) const
{
auto meta = getTrackByNetworkPath(networkPath);
if (!meta.valid || meta.albumArtId <= 0) return {};
return getArtwork(meta.albumArtId);
}
// Get overview waveform for a track (3 bytes per entry: mid/high/low)
DenonWaveformData getWaveformForTrack(const juce::String& networkPath) const
{
auto trackPath = parseNetworkPathToDbPath(networkPath);
if (trackPath.isEmpty()) return {};
std::lock_guard<std::mutex> lock(cacheMutex);
auto it = waveformCache.find(trackPath.toStdString());
if (it != waveformCache.end())
return it->second;
return {};
}
// Get performance data (quick cues, loops, beat grid) for a track
DenonPerformanceData getPerformanceData(const juce::String& networkPath) const
{
auto trackPath = parseNetworkPathToDbPath(networkPath);
if (trackPath.isEmpty()) return {};
std::lock_guard<std::mutex> lock(cacheMutex);
auto it = perfCache.find(trackPath.toStdString());
if (it != perfCache.end())
return it->second;
return {};
}
// Request metadata load for a track (triggers background DB query)
void requestMetadata(const juce::String& networkPath)
{
if (networkPath.isEmpty()) return;
std::lock_guard<std::mutex> lock(requestMutex);
pendingRequests.add(networkPath);
}
// True if database has been downloaded and opened
bool isDatabaseReady() const { return dbReady.load(); }
private:
//==========================================================================
// Thread main loop
//==========================================================================
// Runs from the first start() to stop(): one session for each device
// and port start() asks for, and a wait for the next one in between.
// A session returns when it fails, when stop() is called, or when
// start() wants another (a restarted device); it leaves no socket,
// database or temp file behind.
void run() override
{
while (!threadShouldExit())
{
bool haveTarget = false;
{
std::lock_guard<std::mutex> lock(targetMutex);
if (isRunningFlag.load() && targetSerial.load() != servedSerial)
{
deviceIp = targetIp;
ftPort = targetPort;
std::memcpy(token, targetToken, StageLinQ::kTokenLen);
servedSerial = targetSerial.load();
haveTarget = true;
}
}
if (!haveTarget)
{
wait(-1); // until start() or stop()
continue;
}
fltxReadBuf.clear(); // nothing of the last session's stream
{
std::lock_guard<std::mutex> lock(cacheMutex); // built from the last database
trackCache.clear();
artworkCache.clear();
waveformCache.clear();
perfCache.clear();
}
runSession();
closeFtSocket();
closeDatabase();
std::lock_guard<std::mutex> lock(targetMutex);
if (targetSerial.load() == servedSerial)
{
// It failed (or stop()). An offer that start() ignored while
// it ran is served now; otherwise the next start() begins
// anew. stop() clears both the flag and the offer.
if (haveDeferred && isRunningFlag.load() && !threadShouldExit())
{
targetIp = deferredIp;
targetPort = deferredPort;
std::memcpy(targetToken, deferredToken, StageLinQ::kTokenLen);
targetSerial.store(targetSerial.load() + 1);
haveDeferred = false;
}
else
isRunningFlag.store(false);
}
}
}
// True when the session must end: stop(), or start() wants another
bool sessionShouldEnd() const
{
return threadShouldExit() || targetSerial.load() != servedSerial;
}
void runSession()
{
DBG("StageLinQ DB: Connecting to FileTransfer at " + deviceIp + ":" + juce::String(ftPort));
// --- Connect to FileTransfer service ---
{
auto sock = std::make_unique<juce::StreamingSocket>();
if (!sock->connect(deviceIp, ftPort, StageLinQ::kSocketTimeoutMs))
{
DBG("StageLinQ DB: FileTransfer connect failed");
return;
}
if (sessionShouldEnd()) return; // stop() or start() came during the connect
// Send service announcement (same as StateMap/BeatInfo)
auto announce = StageLinQ::buildServiceAnnouncement(token, "FileTransfer", 0);
sock->write(announce.data(), (int)announce.size());
{
std::lock_guard<std::mutex> lock(sockMutex);
ftSocket = std::move(sock);
}
}
// Per chrisle/StageLinq: 500 ms before the first request. Waited to
// a deadline, not with one wait(): this thread's event is also
// signalled by start(), and a notify() left unconsumed (JUCE's
// startThread() does not reset the event) would end a single wait()
// at once. stop() still cuts it short.
const double requestsAt = juce::Time::getMillisecondCounterHiRes() + 500.0;
for (double left; !sessionShouldEnd()
&& (left = requestsAt - juce::Time::getMillisecondCounterHiRes()) > 0.0;)
wait((int)std::ceil(left));
if (sessionShouldEnd()) return;
// --- Get source locations ---
juce::StringArray sources = fetchSources();
if (sources.isEmpty())
{
DBG("StageLinQ DB: No sources found on device");
return;
}
for (int si = 0; si < sources.size(); ++si)
{
DBG("StageLinQ DB: Source: " + sources[si]);
}
// --- Download database ---
juce::File dbFile = downloadDatabase(sources);
if (dbFile == juce::File() || !dbFile.existsAsFile())
{
DBG("StageLinQ DB: Failed to download database");
return;
}
// --- Open SQLite database ---
if (!openDatabase(dbFile))
{
DBG("StageLinQ DB: Failed to open database");
return;
}
dbReady.store(true);
DBG("StageLinQ DB: Database ready (" + dbFile.getFullPathName() + ")");
// --- Process metadata requests ---
while (!sessionShouldEnd())
{
drainFltx();
juce::StringArray requests;
{
std::lock_guard<std::mutex> lock(requestMutex);
requests = pendingRequests;
pendingRequests.clear();
}
for (int i = 0; i < requests.size(); ++i)
{
if (sessionShouldEnd())
{
// Left for the next session: a request made just after
// a restarted device's start() is for its new database
std::lock_guard<std::mutex> lock(requestMutex);
for (int j = i; j < requests.size(); ++j)
pendingRequests.addIfNotAlreadyThere(requests[j]);
break;
}
processTrackRequest(requests[i]);
}
wait(100); // cut short by stop() and start()
}
}
//==========================================================================
// FileTransfer protocol: fetch sources
//==========================================================================
juce::StringArray fetchSources()
{
auto frame = StageLinQ::buildFltxSources();
if (!fltxWrite(frame)) return {};
auto resp = fltxWaitFor(StageLinQ::kFltxRespSourceLocations, 3000);
return resp.sources;
}
//==========================================================================
// FileTransfer protocol: download database
//==========================================================================
juce::File downloadDatabase(const juce::StringArray& sources)
{
for (auto& source : sources)
{
// Try v2 database first, then v1
juce::String paths[] = {
"/" + source + "/Engine Library/Database2/m.db",
"/" + source + "/Engine Library/m.db"
};
for (auto& dbPath : paths)
{
if (sessionShouldEnd()) return {};
// Check if file exists (stat)
uint32_t fileSize = fetchFileStat(dbPath);
if (fileSize == 0) continue;
DBG("StageLinQ DB: Found database " + dbPath + " (" + juce::String(fileSize) + " bytes)");
// Download the file
auto data = downloadFile(dbPath, fileSize);
if (data.empty()) continue;
// Save to a temp file of its own (it was always STC_Denon/m.db,
// shared by every STC instance and never deleted); deleted
// again by closeDatabase()
removeStaleTempCopies();
auto tempFile = juce::File::getSpecialLocation(juce::File::tempDirectory)
.getNonexistentChildFile("STC_Denon_m", ".db", false);
if (!tempFile.replaceWithData(data.data(), data.size()))
{
DBG("StageLinQ DB: Could not write " + tempFile.getFullPathName());
tempFile.deleteFile();
return {};
}
DBG("StageLinQ DB: Downloaded " + juce::String((int)data.size()) + " bytes to " + tempFile.getFullPathName());
return tempFile;
}
}
return {};
}
//--------------------------------------------------------------------------
// Copies left by a session that never closed its database (STC killed
// or crashed, or this thread killed by force): each download has a name
// of its own, so nothing else deletes them, and Windows never cleans
// its temp directory. Removed before each download once they are a day
// old. This client's own copy is closed by then (closeDatabase); a copy
// another running STC still has open cannot be deleted on Windows, and
// on POSIX stays readable through that STC's handle. The STC_Denon/m.db
// of earlier versions (and any -journal/-wal/-shm beside it) goes the
// same way, then its folder if that leaves it empty. On this thread.
//--------------------------------------------------------------------------
static void removeStaleTempCopies()
{
const auto tempDir = juce::File::getSpecialLocation(juce::File::tempDirectory);
const auto legacyDir = tempDir.getChildFile("STC_Denon");
const auto dayAgo = juce::Time::getCurrentTime() - juce::RelativeTime::days(1.0);
auto copies = tempDir.findChildFiles(juce::File::findFiles, false, "STC_Denon_m*.db");
if (legacyDir.isDirectory())
copies.addArray(legacyDir.findChildFiles(juce::File::findFiles, false, "m.db*"));
for (const auto& f : copies)
if (f.getLastModificationTime() < dayAgo)
f.deleteFile();
if (legacyDir.isDirectory())
legacyDir.deleteFile(); // removes the folder only when empty
}
//==========================================================================
// FileTransfer protocol: get file size
//==========================================================================
uint32_t fetchFileStat(const juce::String& path)
{
auto frame = StageLinQ::buildFltxStat(path);
if (!fltxWrite(frame)) return 0;
auto resp = fltxWaitFor(StageLinQ::kFltxRespFileStat, 2000);
return resp.fileSize;
}
//==========================================================================
// FileTransfer protocol: download complete file
//==========================================================================
std::vector<uint8_t> downloadFile(const juce::String& path, uint32_t expectedSize)
{
juce::ignoreUnused(expectedSize); // actual size comes from TransferId response
// Request transfer ID
auto frame = StageLinQ::buildFltxTransferId(path);
if (!fltxWrite(frame)) return {};
auto resp = fltxWaitFor(StageLinQ::kFltxRespTransferId, 3000);
if (!resp.received || resp.txFileSize == 0)
return {};
uint32_t fileSize = resp.txFileSize;
uint32_t txId = resp.txId;
if (fileSize > StageLinQ::kMaxDbFileBytes)
{
DBG("StageLinQ DB: " + path + " is " + juce::String((juce::int64)fileSize)
+ " bytes, over the " + juce::String((juce::int64)StageLinQ::kMaxDbFileBytes) + " cap -- skipped");
return {};
}
uint32_t totalChunks = (fileSize + StageLinQ::kFltxChunkSize - 1) / StageLinQ::kFltxChunkSize;
DBG("StageLinQ DB: Transfer ID " + juce::String(txId) + ", size " + juce::String(fileSize)
+ ", chunks " + juce::String(totalChunks));
// Request all chunks
auto chunkReq = StageLinQ::buildFltxChunkRange(txId, 0, totalChunks > 0 ? totalChunks - 1 : 0);
if (!fltxWrite(chunkReq)) return {};
// Receive chunks into buffer (fileSize is capped above; an allocation
// that still fails ends this download, not the thread)
std::vector<uint8_t> fileData;
try { fileData.assign(fileSize, 0); }
catch (const std::bad_alloc&) { return {}; }
uint32_t bytesReceived = 0;
double deadline = juce::Time::getMillisecondCounterHiRes() + 30000.0; // 30s timeout
double lastChunkTime = juce::Time::getMillisecondCounterHiRes();
// Anything but a chunk is skipped, as chrisle's getFile() does: the
// device's periodic code != 0 message, which comes every 4 s whatever
// STC asks (#23 PRIME 4+ capture), ended the download as a "timeout"
// (AUDIT SLQ-1), and so did an end-of-message, which the unit also
// sends after a reply (after the source list in the capture). The
// download ends when the file is complete, when no chunk has come for
// 5 s, after 30 s, or when the device disconnects.
while (bytesReceived < fileSize
&& juce::Time::getMillisecondCounterHiRes() < deadline
&& !sessionShouldEnd())
{
auto chunkResp = fltxReadResponse(1000);
if (chunkResp.received && chunkResp.code == 0
&& chunkResp.messageId == StageLinQ::kFltxRespChunk && !chunkResp.chunkData.empty())
{
// Placed at the offset the device gives, compared without
// the sum overflowing uint32 (AUDIT WIRE-2: offset + size
// wrapped and the memcpy wrote past the buffer). A chunk
// that runs past the declared size keeps the part that fits:
// chrisle's FileTransfer.ts has seen devices overrun the
// file size on the final chunk.
const uint32_t offset = chunkResp.chunkOffset;
if (offset < fileSize)
{
const uint32_t n = (uint32_t)juce::jmin((size_t)(fileSize - offset),
chunkResp.chunkData.size());
std::memcpy(fileData.data() + offset, chunkResp.chunkData.data(), n);
bytesReceived += n;
}
lastChunkTime = juce::Time::getMillisecondCounterHiRes();
continue;
}
if (chunkResp.messageId == StageLinQ::kFltxRespDisconnect || !fltxConnected())
break;
if (juce::Time::getMillisecondCounterHiRes() - lastChunkTime > 5000.0)
break;
}
// Signal transfer complete
fltxWrite(StageLinQ::buildFltxComplete());
if (bytesReceived < fileSize)
{
DBG("StageLinQ DB: Incomplete download: " + juce::String(bytesReceived)
+ "/" + juce::String(fileSize) + " -- discarding (truncated SQLite is unusable)");
return {};
}
return fileData;
}
//==========================================================================
// fltx TCP I/O
//==========================================================================
bool fltxWrite(const std::vector<uint8_t>& data)
{
std::lock_guard<std::mutex> lock(sockMutex);
if (!ftSocket || !ftSocket->isConnected()) return false;
int written = ftSocket->write(data.data(), (int)data.size());
return written == (int)data.size();
}
bool fltxConnected()
{
std::lock_guard<std::mutex> lock(sockMutex);
return ftSocket != nullptr && ftSocket->isConnected();
}
void closeFtSocket()
{
std::lock_guard<std::mutex> lock(sockMutex);
if (ftSocket)
{
ftSocket->close();
ftSocket.reset();
}
}
//--------------------------------------------------------------------------
// Wait for the reply to a request: the first message with that ID.
// Anything else on the connection is skipped, as chrisle's
// waitForMessage() does. A PRIME 4+ sends message 0x8 (the string "1")
// as soon as the connection opens and a code != 0 message every 4 s
// (#23 capture); the first of those was taken for the reply to the
// source request, so STC concluded "no sources" and never asked for the
// database (AUDIT SLQ-1). Returns an empty response on timeout, on the
// device's disconnect message (0x9) and when the socket is gone.
//--------------------------------------------------------------------------
FltxResponse fltxWaitFor(uint32_t wantedId, int timeoutMs)
{
const double deadline = juce::Time::getMillisecondCounterHiRes() + timeoutMs;
while (!sessionShouldEnd())
{
const double left = deadline - juce::Time::getMillisecondCounterHiRes();
if (left <= 0.0) break;
auto resp = fltxReadResponse((int)std::ceil(left));
if (!resp.received || resp.messageId == StageLinQ::kFltxRespDisconnect)
break;
if (resp.code == 0 && resp.messageId == wantedId)
return resp;
}
return {};
}
//--------------------------------------------------------------------------
// Read the next complete message (received = false on timeout, or when
// the socket is gone). What is already buffered is parsed before the
// socket is waited on. A failed read or the peer's close closes the
// socket: JUCE's isConnected() stays true after a FIN.
//--------------------------------------------------------------------------
FltxResponse fltxReadResponse(int timeoutMs)
{
FltxResponse resp;
double deadline = juce::Time::getMillisecondCounterHiRes() + timeoutMs;
while (!sessionShouldEnd())
{
// Try to parse a complete message
while (fltxReadBuf.size() >= 4)
{
uint32_t bodyLen = StageLinQ::readU32BE(fltxReadBuf.data());
if (bodyLen == 0)
{
// Service announcement or empty frame -- skip the 4-byte header
fltxReadBuf.erase(fltxReadBuf.begin(), fltxReadBuf.begin() + 4);
continue;
}
if (bodyLen > 1048576)
{
// Malformed data -- discard first byte and try to resync
fltxReadBuf.erase(fltxReadBuf.begin());
continue;
}
if (fltxReadBuf.size() < bodyLen + 4)
break; // incomplete, read more
resp = parseFltxBody(fltxReadBuf.data() + 4, bodyLen);
resp.received = true;
fltxReadBuf.erase(fltxReadBuf.begin(), fltxReadBuf.begin() + 4 + bodyLen);
// Device sent FileTransfer disconnect -- close socket to
// prevent stale reads. chrisle changelog: "Handle Shutdown
// msg (0x9) from FileTransfer svc".
if (resp.messageId == StageLinQ::kFltxRespDisconnect)
closeFtSocket();
return resp;
}
const double left = deadline - juce::Time::getMillisecondCounterHiRes();
if (left <= 0.0) break;
std::lock_guard<std::mutex> lock(sockMutex);
if (!ftSocket || !ftSocket->isConnected()) break;
const int ready = ftSocket->waitUntilReady(true, juce::jmin(100, (int)std::ceil(left)));
if (ready != 0)
{
uint8_t tmp[8192];
int bytesRead = ready > 0 ? ftSocket->read(tmp, sizeof(tmp), false) : -1;
if (bytesRead <= 0)
{
ftSocket->close(); // closed by the device, or failed
break;
}
fltxReadBuf.insert(fltxReadBuf.end(), tmp, tmp + bytesRead);
}
}
return resp;
}
//--------------------------------------------------------------------------
// Once the database is open nothing more is asked of the device, but it
// keeps sending its code != 0 message every 4 s. Read and drop what
// comes so the socket's receive buffer never fills: before, nothing read
// the connection again, and in a few hours the device's sends would have
// blocked. A failed read or the device's close closes the socket.
//--------------------------------------------------------------------------
void drainFltx()
{
std::lock_guard<std::mutex> lock(sockMutex);
if (!ftSocket || !ftSocket->isConnected()) return;
const int ready = ftSocket->waitUntilReady(true, 0);
if (ready == 0) return;
uint8_t tmp[4096];
if (ready < 0 || ftSocket->read(tmp, sizeof(tmp), false) <= 0)
ftSocket->close();
}
FltxResponse parseFltxBody(const uint8_t* body, uint32_t bodyLen)
{
FltxResponse resp;
if (bodyLen < 8) return resp;
// Verify fltx magic
if (std::memcmp(body, StageLinQ::kFltxMagic, 4) != 0) return resp;
uint32_t code = StageLinQ::readU32BE(body + 4);
// code > 0: the device's periodic message ("timecode" in chrisle's
// FileTransfer.ts: fltx, code, 0x7D2, 0), not a reply -- the caller
// skips it. A PRIME 4+ sends one every 4 s (#23 capture).
resp.code = code;
if (code > 0) return resp;