-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAppSettings.h
More file actions
1582 lines (1387 loc) · 65.5 KB
/
AppSettings.h
File metadata and controls
1582 lines (1387 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <string>
//==============================================================================
// TrackMap -- maps tracks (by artist|title) to timecode offsets and triggers
//==============================================================================
/// A single entry mapping a track (identified by artist + title) to a
/// timecode offset that will be applied when that track is detected as playing.
//==============================================================================
// CuePoint -- trigger at a specific playhead position within a track
//==============================================================================
struct CuePoint
{
uint32_t positionMs = 0; // playhead position in ms from track start
juce::String name; // user label ("BREAK", "DROP", "LIGHTS ON", etc.)
// Trigger config (same structure as TrackMapEntry track-change triggers)
int midiChannel = 0; // 0-15 (displayed as 1-16)
int midiNoteNum = -1; // -1 = disabled
int midiNoteVel = 127;
int midiCCNum = -1; // -1 = disabled
int midiCCVal = 127;
juce::String oscAddress; // empty = no OSC
juce::String oscArgs;
int artnetCh = 0; // 0 = disabled, 1-512
int artnetVal = 255;
// --- Query helpers ---
bool hasMidiTrigger() const { return midiNoteNum >= 0 || midiCCNum >= 0; }
bool hasOscTrigger() const { return oscAddress.isNotEmpty(); }
bool hasArtnetTrigger() const { return artnetCh > 0; }
bool hasAnyTrigger() const { return hasMidiTrigger() || hasOscTrigger() || hasArtnetTrigger(); }
// --- Serialization ---
juce::var toVar() const
{
auto* obj = new juce::DynamicObject();
obj->setProperty("positionMs", (int)positionMs);
if (name.isNotEmpty())
obj->setProperty("name", name);
if (midiNoteNum >= 0 || midiCCNum >= 0)
{
obj->setProperty("midiChannel", midiChannel);
obj->setProperty("midiNoteNum", midiNoteNum);
obj->setProperty("midiNoteVel", midiNoteVel);
obj->setProperty("midiCCNum", midiCCNum);
obj->setProperty("midiCCVal", midiCCVal);
}
if (oscAddress.isNotEmpty())
{
obj->setProperty("oscAddress", oscAddress);
if (oscArgs.isNotEmpty())
obj->setProperty("oscArgs", oscArgs);
}
if (artnetCh > 0)
{
obj->setProperty("artnetCh", artnetCh);
obj->setProperty("artnetVal", artnetVal);
}
return juce::var(obj);
}
void fromVar(const juce::var& v)
{
auto* obj = v.getDynamicObject();
if (!obj) return;
auto getInt = [&](const char* key, int def) {
auto val = obj->getProperty(key);
return val.isVoid() ? def : (int)val;
};
auto getString = [&](const char* key, const juce::String& def = {}) {
auto val = obj->getProperty(key);
return val.isVoid() ? def : val.toString();
};
positionMs = (uint32_t)juce::jmax(0, getInt("positionMs", 0));
name = getString("name");
midiChannel = juce::jlimit(0, 15, getInt("midiChannel", 0));
midiNoteNum = juce::jlimit(-1, 127, getInt("midiNoteNum", -1));
midiNoteVel = juce::jlimit(0, 127, getInt("midiNoteVel", 127));
midiCCNum = juce::jlimit(-1, 127, getInt("midiCCNum", -1));
midiCCVal = juce::jlimit(0, 127, getInt("midiCCVal", 127));
oscAddress = getString("oscAddress");
oscArgs = getString("oscArgs");
artnetCh = juce::jlimit(0, 512, getInt("artnetCh", 0));
artnetVal = juce::jlimit(0, 255, getInt("artnetVal", 255));
}
/// Format positionMs as "MM:SS.mmm" for display
static juce::String formatPositionMs(uint32_t ms)
{
int totalSec = (int)(ms / 1000);
int mins = totalSec / 60;
int secs = totalSec % 60;
int millis = (int)(ms % 1000);
return juce::String::formatted("%02d:%02d.%03d", mins, secs, millis);
}
};
//==============================================================================
// TrackMapEntry -- per-track config: offset, triggers, cue points
//==============================================================================
struct TrackMapEntry
{
juce::String artist;
juce::String title;
int durationSec = 0; // track duration in seconds (0 = unknown/legacy)
juce::String timecodeOffset = "00:00:00:00"; // HH:MM:SS:FF
juce::String notes;
// Sort order (0 = default/alphabetical, >0 = explicit position from playlist import)
int sortOrder = 0;
// MIDI triggers (independent -- any combination can fire simultaneously)
int midiChannel = 0; // 0-15 (displayed as 1-16), shared across all MIDI types
int midiNoteNum = -1; // Note On: note number (-1 = disabled, 0-127)
int midiNoteVel = 127; // Note On: velocity (0-127)
int midiCCNum = -1; // CC: controller number (-1 = disabled, 0-127)
int midiCCVal = 127; // CC: value (0-127)
// OSC trigger (per-track: what to send when this track becomes active)
juce::String oscAddress; // e.g. "/cue/1/go", empty = no OSC trigger
juce::String oscArgs; // typed args, e.g. "i:42 s:hello f:3.14"
// Art-Net DMX trigger (per-track: one-shot DMX value on track change)
int artnetCh = 0; // DMX channel (0 = disabled, 1-512)
int artnetVal = 255; // DMX value (0-255)
// BPM multiplier (per-track: applied to MIDI Clock, Ableton Link, OSC BPM forward)
// 0 = off (pass-through), 1 = x2, 2 = x4, -1 = /2, -2 = /4
int bpmMultiplier = 0;
// Cue points -- triggers at specific playhead positions within the track.
// Sorted by positionMs ascending for efficient linear scan during playback.
std::vector<CuePoint> cuePoints;
//------------------------------------------------------------------
// Key generation -- case-insensitive artist|title[|duration]
//------------------------------------------------------------------
static std::string makeKey(const juce::String& a, const juce::String& t, int dur = 0)
{
auto base = (a.toLowerCase().trim() + "|" + t.toLowerCase().trim()).toStdString();
if (dur > 0)
return base + "|" + std::to_string(dur);
return base;
}
std::string key() const { return makeKey(artist, title, durationSec); }
bool hasValidKey() const { return title.isNotEmpty(); }
//------------------------------------------------------------------
// Trigger queries
//------------------------------------------------------------------
bool hasMidiTrigger() const { return midiNoteNum >= 0 || midiCCNum >= 0; }
bool hasOscTrigger() const { return oscAddress.isNotEmpty(); }
bool hasArtnetTrigger() const { return artnetCh > 0; }
bool hasAnyTrigger() const { return hasMidiTrigger() || hasOscTrigger() || hasArtnetTrigger(); }
bool hasCuePoints() const { return !cuePoints.empty(); }
/// Sort cue points by position (call after adding/editing cues)
void sortCuePoints()
{
std::sort(cuePoints.begin(), cuePoints.end(),
[](const CuePoint& a, const CuePoint& b) { return a.positionMs < b.positionMs; });
}
//------------------------------------------------------------------
juce::var toVar() const
{
auto* obj = new juce::DynamicObject();
obj->setProperty("artist", artist);
obj->setProperty("title", title);
if (durationSec > 0)
obj->setProperty("durationSec", durationSec);
obj->setProperty("timecodeOffset", timecodeOffset);
obj->setProperty("notes", notes);
if (sortOrder > 0)
obj->setProperty("sortOrder", sortOrder);
// MIDI triggers (independent)
obj->setProperty("midiChannel", midiChannel);
obj->setProperty("midiNoteNum", midiNoteNum);
obj->setProperty("midiNoteVel", midiNoteVel);
obj->setProperty("midiCCNum", midiCCNum);
obj->setProperty("midiCCVal", midiCCVal);
// OSC trigger
if (oscAddress.isNotEmpty())
{
obj->setProperty("oscAddress", oscAddress);
if (oscArgs.isNotEmpty())
obj->setProperty("oscArgs", oscArgs);
}
// Art-Net DMX trigger
if (artnetCh > 0)
{
obj->setProperty("artnetCh", artnetCh);
obj->setProperty("artnetVal", artnetVal);
}
// BPM multiplier (0 = off, only write if set)
if (bpmMultiplier != 0)
obj->setProperty("bpmMultiplier", bpmMultiplier);
// Cue points (only write if present)
if (!cuePoints.empty())
{
juce::Array<juce::var> cueArr;
for (auto& cue : cuePoints)
cueArr.add(cue.toVar());
obj->setProperty("cuePoints", cueArr);
}
return juce::var(obj);
}
void fromVar(const juce::var& v)
{
auto* obj = v.getDynamicObject();
if (!obj) return;
auto getString = [&](const char* key, const juce::String& def = {}) {
auto val = obj->getProperty(key);
return val.isVoid() ? def : val.toString();
};
auto getInt = [&](const char* key, int def) {
auto val = obj->getProperty(key);
return val.isVoid() ? def : (int)val;
};
artist = getString("artist");
title = getString("title");
durationSec = juce::jmax(0, getInt("durationSec", 0));
notes = getString("notes");
sortOrder = juce::jmax(0, getInt("sortOrder", 0));
// Legacy migration: if entry has trackId but no title, generate a placeholder
// so imported v1.5 entries don't vanish (user can edit them later).
if (title.isEmpty())
{
auto idVal = obj->getProperty("trackId");
if (!idVal.isVoid() && (juce::int64)idVal != 0)
title = "Track #" + juce::String((juce::int64)idVal);
}
// Validate timecodeOffset: must parse as valid HH:MM:SS:FF
{
juce::String rawOffset = getString("timecodeOffset", "00:00:00:00");
int h, m, s, f;
if (parseTimecodeString(rawOffset, h, m, s, f))
timecodeOffset = rawOffset;
else
timecodeOffset = "00:00:00:00"; // reset malformed offsets
}
// MIDI triggers (independent fields, v1.5+)
auto newNoteField = obj->getProperty("midiNoteNum");
if (!newNoteField.isVoid())
{
midiChannel = juce::jlimit(0, 15, getInt("midiChannel", 0));
midiNoteNum = juce::jlimit(-1, 127, getInt("midiNoteNum", -1));
midiNoteVel = juce::jlimit(0, 127, getInt("midiNoteVel", 127));
midiCCNum = juce::jlimit(-1, 127, getInt("midiCCNum", -1));
midiCCVal = juce::jlimit(0, 127, getInt("midiCCVal", 127));
}
else
{
// Legacy migration from midiMsgType (v1.4 and earlier)
int legacyType = juce::jlimit(0, 3, getInt("midiMsgType", 0));
midiChannel = juce::jlimit(0, 15, getInt("midiChannel", 0));
int v1 = juce::jlimit(0, 127, getInt("midiValue1", 0));
int v2 = juce::jlimit(0, 127, getInt("midiValue2", 127));
midiNoteNum = -1; midiNoteVel = 127;
midiCCNum = -1; midiCCVal = 127;
switch (legacyType)
{
case 1: midiNoteNum = v1; midiNoteVel = v2; break;
case 3: midiCCNum = v1; midiCCVal = v2; break;
default: break;
}
}
// OSC trigger
oscAddress = getString("oscAddress");
oscArgs = getString("oscArgs");
// Art-Net DMX trigger
artnetCh = juce::jlimit(0, 512, getInt("artnetCh", 0));
artnetVal = juce::jlimit(0, 255, getInt("artnetVal", 255));
// BPM multiplier
{
int raw = getInt("bpmMultiplier", 0);
bpmMultiplier = (raw == 1 || raw == 2 || raw == -1 || raw == -2) ? raw : 0;
}
// Cue points
cuePoints.clear();
auto* cueArr = obj->getProperty("cuePoints").getArray();
if (cueArr)
{
for (auto& item : *cueArr)
{
CuePoint cp;
cp.fromVar(item);
cuePoints.push_back(std::move(cp));
}
// Ensure sorted by position
std::sort(cuePoints.begin(), cuePoints.end(),
[](const CuePoint& a, const CuePoint& b) { return a.positionMs < b.positionMs; });
}
}
//------------------------------------------------------------------
// Timecode offset parsing/formatting utilities
//------------------------------------------------------------------
/// Parse "HH:MM:SS:FF" or "HH:MM:SS.FF" -> individual fields.
/// Returns false if format is invalid.
static bool parseTimecodeString(const juce::String& s,
int& h, int& m, int& sec, int& f)
{
// Accept both ':' and '.' as separators for the frame field
auto normalized = s.replace(".", ":");
auto parts = juce::StringArray::fromTokens(normalized, ":", "");
if (parts.size() != 4) return false;
h = parts[0].getIntValue();
m = parts[1].getIntValue();
sec = parts[2].getIntValue();
f = parts[3].getIntValue();
return h >= 0 && h <= 23
&& m >= 0 && m <= 59
&& sec >= 0 && sec <= 59
&& f >= 0 && f <= 29;
}
/// Format fields -> "HH:MM:SS:FF"
static juce::String formatTimecodeString(int h, int m, int s, int f)
{
return juce::String::formatted("%02d:%02d:%02d:%02d",
juce::jlimit(0, 23, h),
juce::jlimit(0, 59, m),
juce::jlimit(0, 59, s),
juce::jlimit(0, 29, f));
}
};
//==============================================================================
// TrackMap -- O(1) lookup by artist|title, persisted as separate JSON file
//==============================================================================
class TrackMap
{
public:
//------------------------------------------------------------------
// File location
//------------------------------------------------------------------
static juce::File getTrackMapFile()
{
auto dir = juce::File::getSpecialLocation(juce::File::userApplicationDataDirectory)
.getChildFile("SuperTimecodeConverter");
dir.createDirectory();
return dir.getChildFile("trackmap.json");
}
//------------------------------------------------------------------
// Persistence
//------------------------------------------------------------------
void save() const
{
auto* root = new juce::DynamicObject();
root->setProperty("version", 2); // v2 = artist|title keyed
juce::Array<juce::var> arr;
for (auto& [k, entry] : entries)
arr.add(entry.toVar());
root->setProperty("tracks", arr);
juce::var jsonVar(root);
getTrackMapFile().replaceWithText(juce::JSON::toString(jsonVar));
}
bool load()
{
auto file = getTrackMapFile();
if (!file.existsAsFile()) return false;
auto parsed = juce::JSON::parse(file.loadFileAsString());
auto* obj = parsed.getDynamicObject();
if (!obj) return false;
entries.clear();
auto* arr = obj->getProperty("tracks").getArray();
if (arr)
{
for (auto& item : *arr)
{
TrackMapEntry e;
e.fromVar(item);
if (e.hasValidKey())
entries[e.key()] = std::move(e);
}
}
++generation;
return true;
}
//------------------------------------------------------------------
// Lookup -- single hash lookup by artist|title[|duration]
//------------------------------------------------------------------
/// Find entry by artist + title + optional duration.
const TrackMapEntry* find(const juce::String& artist, const juce::String& title,
int dur = 0) const
{
auto it = entries.find(TrackMapEntry::makeKey(artist, title, dur));
return (it != entries.end()) ? &it->second : nullptr;
}
/// Mutable find (for editing in-place)
TrackMapEntry* find(const juce::String& artist, const juce::String& title,
int dur = 0)
{
auto it = entries.find(TrackMapEntry::makeKey(artist, title, dur));
return (it != entries.end()) ? &it->second : nullptr;
}
/// Check if an artist+title[+duration] exists in the map
bool contains(const juce::String& artist, const juce::String& title,
int dur = 0) const
{
return entries.count(TrackMapEntry::makeKey(artist, title, dur)) > 0;
}
/// Find by artist+title, ignoring duration. Used as a last-resort fallback
/// when the caller's duration doesn't match the entry's saved duration.
const TrackMapEntry* findIgnoringDuration(const juce::String& artist,
const juce::String& title) const
{
auto base = TrackMapEntry::makeKey(artist, title, 0); // key without duration
// Exact match (entry saved without duration)
auto it = entries.find(base);
if (it != entries.end()) return &it->second;
// Prefix match (entry saved with some duration: "base|NNN")
auto prefix = base + "|";
for (auto& [k, v] : entries)
if (k.size() > prefix.size() && k.substr(0, prefix.size()) == prefix)
return &v;
return nullptr;
}
/// Mutable version of findIgnoringDuration
TrackMapEntry* findIgnoringDuration(const juce::String& artist,
const juce::String& title)
{
auto base = TrackMapEntry::makeKey(artist, title, 0);
auto it = entries.find(base);
if (it != entries.end()) return &it->second;
auto prefix = base + "|";
for (auto& [k, v] : entries)
if (k.size() > prefix.size() && k.substr(0, prefix.size()) == prefix)
return &v;
return nullptr;
}
//------------------------------------------------------------------
// Mutation
//------------------------------------------------------------------
/// Add or update an entry (key = artist|title[|duration])
void addOrUpdate(const TrackMapEntry& entry)
{
if (entry.hasValidKey())
{
entries[entry.key()] = entry;
++generation;
}
}
/// Remove by artist+title+optional duration
bool remove(const juce::String& artist, const juce::String& title,
int dur = 0)
{
bool erased = entries.erase(TrackMapEntry::makeKey(artist, title, dur)) > 0;
if (erased) ++generation;
return erased;
}
/// Clear all entries
void clear() { entries.clear(); ++generation; }
/// Apply playlist order: reorder existing tracks, add missing ones.
/// Does NOT touch cues, triggers, offsets, or notes of existing entries.
/// Tracks not in the playlist have their sortOrder reset to 0 (appear after playlist).
void applyPlaylistOrder(const std::vector<TrackMapEntry>& playlist)
{
// Reset all existing sortOrders
for (auto& [k, entry] : entries)
entry.sortOrder = 0;
// Apply playlist positions: update sortOrder on existing, add new
int pos = 1;
for (auto& pe : playlist)
{
if (!pe.hasValidKey()) continue;
// Try exact key (artist|title|duration) first, then fallback
// to artist|title only — duration from XML may differ from CDJ
auto key = pe.key();
auto it = entries.find(key);
if (it != entries.end())
{
it->second.sortOrder = pos;
}
else if (auto* existing = findIgnoringDuration(pe.artist, pe.title))
{
existing->sortOrder = pos;
}
else
{
// New entry — add with playlist position
TrackMapEntry newEntry = pe;
newEntry.sortOrder = pos;
entries[key] = std::move(newEntry);
}
++pos;
}
++generation;
}
//------------------------------------------------------------------
// Iteration & info
//------------------------------------------------------------------
size_t size() const { return entries.size(); }
bool empty() const { return entries.empty(); }
/// Get all entries as a sorted vector (by artist then title) for UI display
std::vector<TrackMapEntry> getAllSorted() const
{
std::vector<TrackMapEntry> result;
result.reserve(entries.size());
for (auto& [k, entry] : entries)
result.push_back(entry);
std::sort(result.begin(), result.end(),
[](const TrackMapEntry& a, const TrackMapEntry& b) {
int cmp = a.artist.compareIgnoreCase(b.artist);
return cmp != 0 ? cmp < 0 : a.title.compareIgnoreCase(b.title) < 0;
});
return result;
}
/// Lightweight variant returning const pointers -- avoids copying strings.
/// IMPORTANT: Pointers are invalidated by ANY mutation of the TrackMap
std::vector<const TrackMapEntry*> getAllSortedPtrs() const
{
std::vector<const TrackMapEntry*> result;
result.reserve(entries.size());
for (auto& [k, entry] : entries)
result.push_back(&entry);
// Sort by sortOrder first (0 = unordered, sorts after explicit positions).
// Within the same sortOrder (or both 0), sort alphabetically by artist/title.
std::sort(result.begin(), result.end(),
[](const TrackMapEntry* a, const TrackMapEntry* b) {
// Both have explicit order → compare by order
if (a->sortOrder > 0 && b->sortOrder > 0)
return a->sortOrder < b->sortOrder;
// Only one has explicit order → it comes first
if (a->sortOrder > 0) return true;
if (b->sortOrder > 0) return false;
// Neither has order → alphabetical
int cmp = a->artist.compareIgnoreCase(b->artist);
return cmp != 0 ? cmp < 0 : a->title.compareIgnoreCase(b->title) < 0;
});
return result;
}
//------------------------------------------------------------------
// Import / Export
//------------------------------------------------------------------
bool exportToFile(const juce::File& file) const
{
auto* root = new juce::DynamicObject();
root->setProperty("version", 2);
juce::Array<juce::var> arr;
for (auto& [k, entry] : entries)
arr.add(entry.toVar());
root->setProperty("tracks", arr);
juce::var jsonVar(root);
return file.replaceWithText(juce::JSON::toString(jsonVar));
}
/// Import from a user-chosen file -- merges with existing entries.
int importFromFile(const juce::File& file)
{
if (!file.existsAsFile()) return 0;
auto parsed = juce::JSON::parse(file.loadFileAsString());
auto* obj = parsed.getDynamicObject();
if (!obj) return 0;
auto* arr = obj->getProperty("tracks").getArray();
if (!arr) return 0;
int count = 0;
for (auto& item : *arr)
{
TrackMapEntry e;
e.fromVar(item);
if (e.hasValidKey())
{
entries[e.key()] = std::move(e);
++count;
}
}
if (count > 0) ++generation;
return count;
}
//------------------------------------------------------------------
// Direct access to the map (for advanced iteration)
//------------------------------------------------------------------
const std::unordered_map<std::string, TrackMapEntry>& getEntries() const { return entries; }
uint64_t getGeneration() const { return generation; }
//------------------------------------------------------------------
// rekordbox XML import -- parse <DJ_PLAYLISTS> into TrackMapEntry list.
// Returns entries with artist, title, durationSec populated.
// Offsets and triggers are left at defaults (user configures later).
// Artwork and waveform will be fetched from the CDJ on first play.
//------------------------------------------------------------------
static std::vector<TrackMapEntry> parseRekordboxXml(const juce::File& file)
{
return parseRekordboxXml(file, "");
}
/// Parse rekordbox XML export. If playlistName is non-empty, only return
/// tracks from that playlist in playlist order. Otherwise return all tracks.
static std::vector<TrackMapEntry> parseRekordboxXml(const juce::File& file,
const juce::String& playlistName)
{
std::vector<TrackMapEntry> result;
auto xml = juce::XmlDocument::parse(file);
if (!xml || xml->getTagName() != "DJ_PLAYLISTS") return result;
auto* collection = xml->getChildByName("COLLECTION");
if (!collection) return result;
// Build TrackID → entry map from COLLECTION
std::unordered_map<int, TrackMapEntry> trackById;
for (auto* track = collection->getChildByName("TRACK");
track != nullptr;
track = track->getNextElementWithTagName("TRACK"))
{
juce::String title = track->getStringAttribute("Name").trim();
juce::String artist = track->getStringAttribute("Artist").trim();
int duration = track->getIntAttribute("TotalTime", 0);
int trackId = track->getIntAttribute("TrackID", 0);
if (title.isEmpty() || trackId <= 0) continue;
TrackMapEntry e;
e.title = title;
e.artist = artist;
e.durationSec = duration;
trackById[trackId] = std::move(e);
}
// If a playlist is requested, filter and order by playlist
if (playlistName.isNotEmpty())
{
auto* playlists = xml->getChildByName("PLAYLISTS");
if (!playlists) return result;
// Traverse by full path (e.g. "Shows / Saturday") to handle
// duplicate playlist names in different folders.
// Path segments skip ROOT (same as listRekordboxPlaylists).
juce::XmlElement* playlistNode = nullptr;
{
// Split path into segments on the " / " SUBSTRING.
// (Do NOT use addTokens — it treats the second arg as a set
// of break CHARACTERS, which would split on every space.)
juce::StringArray segments;
juce::String remaining = playlistName;
int pos = remaining.indexOf(" / ");
while (pos >= 0)
{
segments.add(remaining.substring(0, pos));
remaining = remaining.substring(pos + 3);
pos = remaining.indexOf(" / ");
}
segments.add(remaining);
// Drop any empty segments (shouldn't happen but defensive)
for (int i = segments.size() - 1; i >= 0; --i)
if (segments[i].isEmpty()) segments.remove(i);
// Start from ROOT node (first Type=0 child of PLAYLISTS)
juce::XmlElement* current = nullptr;
for (auto* child = playlists->getFirstChildElement();
child != nullptr; child = child->getNextElement())
{
if (child->getTagName() == "NODE"
&& child->getIntAttribute("Type", -1) == 0)
{ current = child; break; }
}
// Walk path segments: folders first, last segment is the playlist
for (int si = 0; current != nullptr && si < segments.size(); ++si)
{
bool isLast = (si == segments.size() - 1);
int wantType = isLast ? 1 : 0; // 1=playlist, 0=folder
juce::XmlElement* found = nullptr;
for (auto* child = current->getFirstChildElement();
child != nullptr; child = child->getNextElement())
{
if (child->getTagName() == "NODE"
&& child->getStringAttribute("Name") == segments[si]
&& child->getIntAttribute("Type", -1) == wantType)
{ found = child; break; }
}
current = found;
}
playlistNode = current;
}
if (!playlistNode) return result;
// Collect tracks in playlist order
std::unordered_set<std::string> seen;
for (auto* tr = playlistNode->getChildByName("TRACK");
tr != nullptr;
tr = tr->getNextElementWithTagName("TRACK"))
{
int key = tr->getIntAttribute("Key", 0);
auto it = trackById.find(key);
if (it != trackById.end())
{
auto k = it->second.key();
if (!seen.count(k))
{
seen.insert(k);
result.push_back(it->second);
}
}
}
return result;
}
// No playlist specified — return all tracks from COLLECTION
std::unordered_set<std::string> seen;
for (auto& [id, entry] : trackById)
{
auto k = entry.key();
if (seen.count(k)) continue;
seen.insert(k);
result.push_back(std::move(entry));
}
return result;
}
/// List available playlist names in a rekordbox XML file
static juce::StringArray listRekordboxPlaylists(const juce::File& file)
{
juce::StringArray result;
auto xml = juce::XmlDocument::parse(file);
if (!xml || xml->getTagName() != "DJ_PLAYLISTS") return result;
auto* playlists = xml->getChildByName("PLAYLISTS");
if (!playlists) return result;
// Recursive scan for Type=1 (playlist) nodes with entries.
// ROOT is always the top-level folder in rekordbox — skip it in the path.
std::function<void(juce::XmlElement*, const juce::String&)> scan =
[&](juce::XmlElement* node, const juce::String& path)
{
for (auto* child = node->getFirstChildElement();
child != nullptr; child = child->getNextElement())
{
if (child->getTagName() != "NODE") continue;
juce::String name = child->getStringAttribute("Name");
int type = child->getIntAttribute("Type", -1);
if (type == 1) // playlist
{
int entries = child->getIntAttribute("Entries", 0);
if (entries > 0)
result.add(path.isEmpty() ? name : path + " / " + name);
}
else if (type == 0) // folder
{
// Skip ROOT — it's always the top-level node in rekordbox XML
juce::String childPath = name.equalsIgnoreCase("ROOT") ? path
: (path.isEmpty() ? name : path + " / " + name);
scan(child, childPath);
}
}
};
scan(playlists, "");
return result;
}
private:
std::unordered_map<std::string, TrackMapEntry> entries;
uint64_t generation = 0;
};
//==============================================================================
// Generator preset -- named timecode range for the internal generator
//==============================================================================
struct GeneratorPreset
{
juce::String name; // unique key, e.g. "INTRO"
juce::String startTC = "00:00:00:00"; // HH:MM:SS:FF
juce::String stopTC = "00:00:00:00"; // HH:MM:SS:FF (0 = freerun)
std::string key() const { return name.toLowerCase().trim().toStdString(); }
bool hasValidKey() const { return name.trim().isNotEmpty(); }
juce::var toVar() const
{
auto* obj = new juce::DynamicObject();
obj->setProperty("name", name);
obj->setProperty("startTC", startTC);
obj->setProperty("stopTC", stopTC);
return juce::var(obj);
}
void fromVar(const juce::var& v)
{
auto* obj = v.getDynamicObject();
if (!obj) return;
name = obj->getProperty("name").toString();
startTC = obj->getProperty("startTC").toString();
stopTC = obj->getProperty("stopTC").toString();
if (startTC.isEmpty()) startTC = "00:00:00:00";
if (stopTC.isEmpty()) stopTC = "00:00:00:00";
}
};
//==============================================================================
// Generator preset map -- persistent collection of named presets
//==============================================================================
class GeneratorPresetMap
{
public:
static juce::File getPresetFile()
{
auto dir = juce::File::getSpecialLocation(juce::File::userApplicationDataDirectory)
.getChildFile("SuperTimecodeConverter");
dir.createDirectory();
return dir.getChildFile("generator_presets.json");
}
void save() const
{
auto* root = new juce::DynamicObject();
root->setProperty("version", 1);
juce::Array<juce::var> arr;
for (auto& [k, preset] : entries)
arr.add(preset.toVar());
root->setProperty("presets", arr);
juce::var jsonVar(root);
getPresetFile().replaceWithText(juce::JSON::toString(jsonVar));
}
bool load()
{
auto file = getPresetFile();
if (!file.existsAsFile()) return false;
auto parsed = juce::JSON::parse(file.loadFileAsString());
auto* obj = parsed.getDynamicObject();
if (!obj) return false;
entries.clear();
auto* arr = obj->getProperty("presets").getArray();
if (arr)
{
for (auto& item : *arr)
{
GeneratorPreset p;
p.fromVar(item);
if (p.hasValidKey())
entries[p.key()] = std::move(p);
}
}
return true;
}
const GeneratorPreset* find(const juce::String& name) const
{
auto it = entries.find(name.toLowerCase().trim().toStdString());
return (it != entries.end()) ? &it->second : nullptr;
}
GeneratorPreset* find(const juce::String& name)
{
auto it = entries.find(name.toLowerCase().trim().toStdString());
return (it != entries.end()) ? &it->second : nullptr;
}
void addOrUpdate(const GeneratorPreset& preset)
{
if (preset.hasValidKey())
entries[preset.key()] = preset;
}
bool remove(const juce::String& name)
{
return entries.erase(name.toLowerCase().trim().toStdString()) > 0;
}
void clear() { entries.clear(); }
size_t size() const { return entries.size(); }
bool empty() const { return entries.empty(); }
std::vector<GeneratorPreset> getAllSorted() const
{
std::vector<GeneratorPreset> result;
result.reserve(entries.size());
for (auto& [k, p] : entries)
result.push_back(p);
std::sort(result.begin(), result.end(),
[](const GeneratorPreset& a, const GeneratorPreset& b) {
return a.name.compareIgnoreCase(b.name) < 0;
});
return result;
}
private:
std::unordered_map<std::string, GeneratorPreset> entries;
};
//==============================================================================
// Per-engine settings
//==============================================================================
struct EngineSettings
{
juce::String engineName = ""; // empty = default "ENGINE N"
// Input
juce::String inputSource = "SystemTime";
juce::String midiInputDevice = "";
int artnetInputInterface = 0;
int hippotizerInputInterface = 0;
int hippotizerTcChannel = 0; // 0=TC1, 1=TC2
// Generator (internal timecode source)
bool generatorClockMode = true; // true = wall clock, false = transport
double generatorStartMs = 0.0; // start TC in ms from midnight
double generatorStopMs = 0.0; // stop TC in ms (0 = freerun)
// Pro DJ Link
int proDJLinkPlayer = 1;
bool trackMapEnabled = false;
bool midiClockEnabled = false;
juce::String oscBpmAddr = "/composition/tempocontroller/tempo";
juce::String oscBpmCmd; // e.g. "Master 3.x at %BPM%" — if set, sends string instead of float
bool oscBpmForward = false;
bool oscMixerForward = false;
bool midiMixerForward = false;
int midiMixerCCChannel = 1; // 1-16 (CC messages)
int midiMixerNoteChannel = 1; // 1-16 (Note messages)
bool artnetMixerForward = false;
int artnetMixerUniverse = 0; // 0-32767
int artnetTriggerUniverse = 1; // 0-32767 (separate from mixer, default 1)
int artnetDmxInterface = -1; // -1 = All Interfaces (Broadcast), 0+ = specific NIC
bool linkEnabled = false;
juce::String audioInputDevice = "";
juce::String audioInputType = "";
int audioInputChannel = 0;
// Output
bool mtcOutEnabled = false;
bool artnetOutEnabled = false;
bool ltcOutEnabled = false;
bool thruOutEnabled = false; // only meaningful for engine 0
bool tcnetOutEnabled = false; // TCNet timecode layer output