-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStageLinQDbClient.h
More file actions
1390 lines (1181 loc) · 51.1 KB
/
StageLinQDbClient.h
File metadata and controls
1390 lines (1181 loc) · 51.1 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 kFltxRespDisconnect = 9;
static constexpr int kFltxChunkSize = 4096;
//==========================================================================
// 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
{
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: connect to FileTransfer service at given IP:port
//--------------------------------------------------------------------------
bool start(const juce::String& ip, uint16_t fileTransferPort,
const uint8_t tkn[StageLinQ::kTokenLen])
{
if (isRunningFlag.load()) return true;
deviceIp = ip;
ftPort = fileTransferPort;
std::memcpy(token, tkn, StageLinQ::kTokenLen);
fltxReadBuf.clear(); // clear stale data from any previous session
isRunningFlag.store(true);
startThread(juce::Thread::Priority::normal);
return true;
}
void stop()
{
if (!isRunningFlag.load()) return;
isRunningFlag.store(false);
signalThreadShouldExit();
{
std::lock_guard<std::mutex> lock(sockMutex);
if (ftSocket)
{
ftSocket->close();
ftSocket.reset();
}
}
stopThread(5000);
closeDatabase();
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
//==========================================================================
void run() override
{
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");
isRunningFlag.store(false);
return;
}
// 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);
}
}
juce::Thread::sleep(500); // per chrisle/StageLinq: delay before requests
// --- Get source locations ---
juce::StringArray sources = fetchSources();
if (sources.isEmpty())
{
DBG("StageLinQ DB: No sources found on device");
isRunningFlag.store(false);
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");
isRunningFlag.store(false);
return;
}
// --- Open SQLite database ---
if (!openDatabase(dbFile))
{
DBG("StageLinQ DB: Failed to open database");
isRunningFlag.store(false);
return;
}
dbReady.store(true);
DBG("StageLinQ DB: Database ready (" + dbFile.getFullPathName() + ")");
// --- Process metadata requests ---
while (!threadShouldExit() && isRunningFlag.load())
{
juce::StringArray requests;
{
std::lock_guard<std::mutex> lock(requestMutex);
requests = pendingRequests;
pendingRequests.clear();
}
for (auto& networkPath : requests)
{
if (threadShouldExit()) break;
processTrackRequest(networkPath);
}
juce::Thread::sleep(100);
}
closeDatabase();
isRunningFlag.store(false);
}
//==========================================================================
// FileTransfer protocol: fetch sources
//==========================================================================
juce::StringArray fetchSources()
{
auto frame = StageLinQ::buildFltxSources();
if (!fltxWrite(frame)) return {};
// Read response with timeout
auto resp = fltxReadResponse(3000);
if (resp.messageId == StageLinQ::kFltxRespSourceLocations)
return resp.sources;
return {};
}
//==========================================================================
// 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 (threadShouldExit()) 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 temp file
auto tempDir = juce::File::getSpecialLocation(
juce::File::tempDirectory).getChildFile("STC_Denon");
tempDir.createDirectory();
auto tempFile = tempDir.getChildFile("m.db");
tempFile.replaceWithData(data.data(), data.size());
DBG("StageLinQ DB: Downloaded " + juce::String((int)data.size()) + " bytes to " + tempFile.getFullPathName());
return tempFile;
}
}
return {};
}
//==========================================================================
// FileTransfer protocol: get file size
//==========================================================================
uint32_t fetchFileStat(const juce::String& path)
{
auto frame = StageLinQ::buildFltxStat(path);
if (!fltxWrite(frame)) return 0;
auto resp = fltxReadResponse(2000);
if (resp.messageId == StageLinQ::kFltxRespFileStat)
return resp.fileSize;
return 0;
}
//==========================================================================
// 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 = fltxReadResponse(3000);
if (resp.messageId != StageLinQ::kFltxRespTransferId || resp.txFileSize == 0)
return {};
uint32_t fileSize = resp.txFileSize;
uint32_t txId = resp.txId;
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
std::vector<uint8_t> fileData(fileSize, 0);
uint32_t bytesReceived = 0;
double deadline = juce::Time::getMillisecondCounterHiRes() + 30000.0; // 30s timeout
while (bytesReceived < fileSize
&& juce::Time::getMillisecondCounterHiRes() < deadline
&& !threadShouldExit())
{
auto chunkResp = fltxReadResponse(5000);
if (chunkResp.messageId == StageLinQ::kFltxRespChunk && !chunkResp.chunkData.empty())
{
uint32_t offset = chunkResp.chunkOffset;
uint32_t size = chunkResp.chunkSize;
if (offset + size <= fileSize)
{
std::memcpy(fileData.data() + offset, chunkResp.chunkData.data(), size);
bytesReceived += size;
}
}
else if (chunkResp.messageId == StageLinQ::kFltxRespEndOfMessage)
{
break;
}
else if (chunkResp.messageId == 0)
{
// Timeout or error
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();
}
FltxResponse fltxReadResponse(int timeoutMs)
{
FltxResponse resp;
double deadline = juce::Time::getMillisecondCounterHiRes() + timeoutMs;
while (juce::Time::getMillisecondCounterHiRes() < deadline && !threadShouldExit())
{
{
std::lock_guard<std::mutex> lock(sockMutex);
if (!ftSocket || !ftSocket->isConnected()) return resp;
if (ftSocket->waitUntilReady(true, 100))
{
uint8_t tmp[8192];
int bytesRead = ftSocket->read(tmp, sizeof(tmp), false);
if (bytesRead <= 0) return resp;
fltxReadBuf.insert(fltxReadBuf.end(), tmp, tmp + bytesRead);
}
}
// Try to parse a complete message
if (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)
{
resp = parseFltxBody(fltxReadBuf.data() + 4, bodyLen);
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)
{
std::lock_guard<std::mutex> lock2(sockMutex);
if (ftSocket)
{
ftSocket->close();
ftSocket.reset();
}
}
return resp;
}
}
}
return resp;
}
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);
// If code > 0, it's a timecode message (ignored)
if (code > 0) return resp;
// code == 0: read message ID
if (bodyLen < 12) return resp;
uint32_t msgId = StageLinQ::readU32BE(body + 8);
resp.messageId = msgId;
switch (msgId)
{
case StageLinQ::kFltxRespSourceLocations:
{
// count[4] + strings... + 0x01 0x01 0x01
if (bodyLen < 16) break;
uint32_t count = StageLinQ::readU32BE(body + 12);
int pos = 16;
for (uint32_t i = 0; i < count && pos < (int)bodyLen; ++i)
{
juce::String src;
pos = StageLinQ::readNetworkString(body, (int)bodyLen, pos, src);
if (pos < 0) break;
resp.sources.add(src);
}
break;
}
case StageLinQ::kFltxRespFileStat:
{
// 53 bytes payload, last 4 = file size
if (bodyLen >= 12 + 53)
resp.fileSize = StageLinQ::readU32BE(body + 12 + 49);
break;
}
case StageLinQ::kFltxRespTransferId:
{
// 0x0[4] + filesize[4] + txid[4]
if (bodyLen >= 24)
{
resp.txFileSize = StageLinQ::readU32BE(body + 16);
resp.txId = StageLinQ::readU32BE(body + 20);
}
break;
}
case StageLinQ::kFltxRespChunk:
{
// 0x0[4] + offset[4] + chunksize[4] + data
if (bodyLen >= 24)
{
resp.chunkOffset = StageLinQ::readU32BE(body + 16);
resp.chunkSize = StageLinQ::readU32BE(body + 20);
if (24 + resp.chunkSize <= bodyLen)
{
resp.chunkData.assign(body + 24, body + 24 + resp.chunkSize);
}
}
break;
}
case StageLinQ::kFltxRespEndOfMessage:
break;
case StageLinQ::kFltxRespDisconnect:
DBG("StageLinQ DB: Device sent FileTransfer disconnect (0x9)");
break;
default:
DBG("StageLinQ DB: Unknown fltx response " + juce::String(msgId));
break;
}
return resp;
}
//==========================================================================
// SQLite database operations
//==========================================================================
bool openDatabase(const juce::File& dbFile)
{
closeDatabase();
int rc = sqlite3_open_v2(dbFile.getFullPathName().toRawUTF8(),
&db, SQLITE_OPEN_READONLY, nullptr);
if (rc != SQLITE_OK)
{
DBG("StageLinQ DB: SQLite open error: " + juce::String(sqlite3_errmsg(db)));
db = nullptr;
return false;
}
// Count tracks for logging
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db, "SELECT COUNT(*) FROM Track", -1, &stmt, nullptr) == SQLITE_OK)
{
if (sqlite3_step(stmt) == SQLITE_ROW)
{
DBG("StageLinQ DB: " + juce::String(sqlite3_column_int(stmt, 0)) + " tracks in database");
}
sqlite3_finalize(stmt);
}
return true;
}
void closeDatabase()
{
if (db)
{
sqlite3_close(db);
db = nullptr;
}
dbReady.store(false);
}
//==========================================================================
// Process a track metadata request
//==========================================================================
void processTrackRequest(const juce::String& networkPath)
{
if (!db) return;
auto trackPath = parseNetworkPathToDbPath(networkPath);
if (trackPath.isEmpty()) return;
// Check cache (quick, under lock)
{
std::lock_guard<std::mutex> lock(cacheMutex);
if (trackCache.count(trackPath.toStdString()) > 0) return;
}
// --- All DB queries OUTSIDE the lock (may take time) ---
// Query Track table
DenonTrackMeta meta = queryTrack(trackPath);
if (!meta.valid) return;
// Query artwork (no lock held during I/O)
juce::Image artImg;
if (meta.albumArtId > 0)
artImg = queryArtwork(meta.albumArtId);
// Query overview waveform
auto wf = queryOverviewWaveform(trackPath);
// Query performance data (cues, loops, beat grid)
auto perf = queryPerformanceData(trackPath);
// --- Insert results into caches (lock once) ---
{
std::lock_guard<std::mutex> lock(cacheMutex);
trackCache[trackPath.toStdString()] = meta;
if (meta.albumArtId > 0 && artImg.isValid()
&& artworkCache.count(meta.albumArtId) == 0)
artworkCache[meta.albumArtId] = artImg;
if (wf.valid && waveformCache.count(trackPath.toStdString()) == 0)
waveformCache[trackPath.toStdString()] = std::move(wf);
if (perf.valid && perfCache.count(trackPath.toStdString()) == 0)
perfCache[trackPath.toStdString()] = std::move(perf);
}
DBG("StageLinQ DB: Loaded metadata for " + meta.artist + " - " + meta.title
+ " (art=" + juce::String(meta.albumArtId) + ")");
}
//==========================================================================
// SQLite query: Track table
//==========================================================================
DenonTrackMeta queryTrack(const juce::String& trackPath)
{
DenonTrackMeta meta;
if (!db) return meta;
// Streaming tracks (Beatsource/Tidal) are queried by "uri" column
// instead of "path" (matching chrisle/StageLinq DbConnection.ts)
bool isStreaming = trackPath.startsWith("streaming://");
// Engine DJ schema v1.x uses "idAlbumArt", v2.x uses "albumArtId".
// We download v2 first (Database2/m.db), falling back to v1.
// Try v2 column name first, fall back to v1 on failure.
juce::String whereCol = isStreaming ? "uri" : "path";
juce::String sqlV2Str = "SELECT title, artist, album, genre, key, bpm, length, albumArtId "
"FROM Track WHERE " + whereCol + " = ? LIMIT 1";
juce::String sqlV1Str = "SELECT title, artist, album, genre, key, bpm, length, idAlbumArt "
"FROM Track WHERE " + whereCol + " = ? LIMIT 1";
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db, sqlV2Str.toRawUTF8(), -1, &stmt, nullptr) != SQLITE_OK)
{
// v2 column not found -- try v1
if (sqlite3_prepare_v2(db, sqlV1Str.toRawUTF8(), -1, &stmt, nullptr) != SQLITE_OK)
return meta;
}
sqlite3_bind_text(stmt, 1, trackPath.toRawUTF8(), -1, SQLITE_TRANSIENT);
if (sqlite3_step(stmt) == SQLITE_ROW)
{
// sqlite3_column_text returns NULL for SQL NULL -- must check
auto safeText = [](sqlite3_stmt* s, int col) -> juce::String {
const char* p = (const char*)sqlite3_column_text(s, col);
return p ? juce::String::fromUTF8(p) : juce::String();
};
meta.title = safeText(stmt, 0);
meta.artist = safeText(stmt, 1);
meta.album = safeText(stmt, 2);
meta.genre = safeText(stmt, 3);
// Key: stored as integer in Engine DJ (0-23 = musical key index)
// Convert to string using musicalKeyToString()
int keyType = sqlite3_column_type(stmt, 4);
if (keyType == SQLITE_INTEGER)
meta.key = musicalKeyToString(sqlite3_column_int(stmt, 4));
else if (keyType == SQLITE_TEXT)
{
const char* kp = (const char*)sqlite3_column_text(stmt, 4);
if (kp) meta.key = juce::String::fromUTF8(kp);
}
meta.bpm = sqlite3_column_double(stmt, 5);
meta.length = sqlite3_column_double(stmt, 6);
meta.albumArtId = sqlite3_column_int(stmt, 7);
meta.valid = true;
}
sqlite3_finalize(stmt);
return meta;
}
//==========================================================================
// SQLite query: AlbumArt table -> juce::Image
//==========================================================================
juce::Image queryArtwork(int albumArtId)
{
if (!db || albumArtId <= 0) return {};
const char* sql = "SELECT albumArt FROM AlbumArt WHERE id = ? AND albumArt IS NOT NULL LIMIT 1";
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) != SQLITE_OK) return {};
sqlite3_bind_int(stmt, 1, albumArtId);
juce::Image result;
if (sqlite3_step(stmt) == SQLITE_ROW)
{
const void* blob = sqlite3_column_blob(stmt, 0);
int blobSize = sqlite3_column_bytes(stmt, 0);
if (blob && blobSize > 0)
{
// AlbumArt BLOBs are standard JPEG/PNG images
juce::MemoryInputStream stream(blob, (size_t)blobSize, false);
auto format = juce::ImageFileFormat::findImageFormatForStream(stream);
if (format)
{
stream.setPosition(0);
result = format->decodeImage(stream);
}
}
}
sqlite3_finalize(stmt);
return result;
}
//==========================================================================
// SQLite query: Track.overviewWaveFormData -> DenonWaveformData
//
// BLOB format (from libdjinterop, LGPL, by xsco):
// [uncompressed_size:i32be][zlib_data...]
//
// After zlib decompression:
// numEntries : int64_be (8 bytes)
// numEntries : int64_be (8 bytes) -- duplicate