-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathrekordboxfeature.cpp
1414 lines (1185 loc) · 56.9 KB
/
rekordboxfeature.cpp
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
// rekordboxfeature.cpp
// Created 05/24/2019 by Evan Dekker
#include <QMap>
#include <QMessageBox>
#include <QSettings>
#include <QStandardPaths>
#include <QtDebug>
#include "library/rekordbox/rekordbox_anlz.h"
#include "library/rekordbox/rekordbox_pdb.h"
#include "library/rekordbox/rekordboxfeature.h"
#include <mp3guessenc.h>
#include "engine/engine.h"
#include "library/dao/trackschema.h"
#include "library/library.h"
#include "library/librarytablemodel.h"
#include "library/missingtablemodel.h"
#include "library/queryutil.h"
#include "library/trackcollection.h"
#include "library/trackcollectionmanager.h"
#include "library/treeitem.h"
#include "track/beatfactory.h"
#include "track/cue.h"
#include "track/keyfactory.h"
#include "util/color/color.h"
#include "util/db/dbconnectionpooled.h"
#include "util/db/dbconnectionpooler.h"
#include "util/file.h"
#include "util/sandbox.h"
#include "waveform/waveform.h"
#include "widget/wlibrary.h"
#include "widget/wlibrarytextbrowser.h"
#define IS_RECORDBOX_DEVICE "::isRecordboxDevice::"
#define IS_NOT_RECORDBOX_DEVICE "::isNotRecordboxDevice::"
namespace {
const QString kRekordboxLibraryTable = QStringLiteral("rekordbox_library");
const QString kRekordboxPlaylistsTable = QStringLiteral("rekordbox_playlists");
const QString kRekordboxPlaylistTracksTable = QStringLiteral("rekordbox_playlist_tracks");
const QString kPdbPath = QStringLiteral("PIONEER/rekordbox/export.pdb");
const QString kPLaylistPathDelimiter = QStringLiteral("-->");
constexpr double kLongestPosition = 999999999.0;
enum class TrackColor : uint8_t {
Pink = 1,
Red,
Orange,
Yellow,
Green,
Aqua,
Blue,
Purple
};
constexpr mixxx::RgbColor kTrackColorPink(0xF870F8);
constexpr mixxx::RgbColor kTrackColorRed(0xF870900);
constexpr mixxx::RgbColor kTrackColorOrange(0xF8A030);
constexpr mixxx::RgbColor kTrackColorYellow(0xF8E331);
constexpr mixxx::RgbColor kTrackColorGreen(0x1EE000);
constexpr mixxx::RgbColor kTrackColorAqua(0x16C0F8);
constexpr mixxx::RgbColor kTrackColorBlue(0x0150F8);
constexpr mixxx::RgbColor kTrackColorPurple(0x9808F8);
struct memory_cue_t {
double position;
QString comment;
mixxx::RgbColor::optional_t color;
};
bool createLibraryTable(QSqlDatabase& database, const QString& tableName) {
qDebug() << "Creating Rekordbox library table: " << tableName;
QSqlQuery query(database);
query.prepare(
"CREATE TABLE IF NOT EXISTS " + tableName +
" ("
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
" rb_id INTEGER,"
" artist TEXT,"
" title TEXT,"
" album TEXT,"
" year INTEGER,"
" genre TEXT,"
" tracknumber TEXT,"
" location TEXT UNIQUE,"
" comment TEXT,"
" duration INTEGER,"
" bitrate TEXT,"
" bpm FLOAT,"
" key TEXT,"
" rating INTEGER,"
" analyze_path TEXT UNIQUE,"
" device TEXT,"
" color INTEGER"
");");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
return true;
}
bool createPlaylistsTable(QSqlDatabase& database, const QString& tableName) {
qDebug() << "Creating Rekordbox playlists table: " << tableName;
QSqlQuery query(database);
query.prepare(
"CREATE TABLE IF NOT EXISTS " + tableName +
" ("
" id INTEGER PRIMARY KEY,"
" name TEXT UNIQUE"
");");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
return true;
}
bool createPlaylistTracksTable(QSqlDatabase& database, const QString& tableName) {
qDebug() << "Creating Rekordbox playlist tracks table: " << tableName;
QSqlQuery query(database);
query.prepare(
"CREATE TABLE IF NOT EXISTS " + tableName +
" ("
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
" playlist_id INTEGER REFERENCES rekordbox_playlists(id),"
" track_id INTEGER REFERENCES rekordbox_library(id),"
" position INTEGER"
");");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
return true;
}
bool dropTable(QSqlDatabase& database, QString tableName) {
qDebug() << "Dropping Rekordbox table: " << tableName;
QSqlQuery query(database);
query.prepare("DROP TABLE IF EXISTS " + tableName);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
return true;
}
// This function is executed in a separate thread other than the main thread
QList<TreeItem*> findRekordboxDevices() {
QThread* thisThread = QThread::currentThread();
thisThread->setPriority(QThread::LowPriority);
QList<TreeItem*> foundDevices;
#if defined(__WINDOWS__)
// Repopulate drive list
QFileInfoList drives = QDir::drives();
// show drive letters
foreach (QFileInfo drive, drives) {
// Using drive.filePath() instead of drive.canonicalPath() as it
// freezes interface too much if there is a network share mounted
// (drive letter assigned) but unavailable
//
// drive.canonicalPath() make a system call to the underlying filesystem
// introducing delay if it is unreadable.
// drive.filePath() doesn't make any access to the filesystem and consequently
// shorten the delay
QFileInfo rbDBFileInfo(drive.filePath() + kPdbPath);
if (rbDBFileInfo.exists() && rbDBFileInfo.isFile()) {
QString displayPath = drive.filePath();
if (displayPath.endsWith("/")) {
displayPath.chop(1);
}
QList<QString> data;
data << drive.filePath();
data << IS_RECORDBOX_DEVICE;
TreeItem* foundDevice = new TreeItem(
std::move(displayPath),
QVariant(data));
foundDevices << foundDevice;
}
}
#elif defined(__LINUX__)
// To get devices on Linux, we look for directories under /media and
// /run/media/$USER.
QFileInfoList devices;
// Add folders under /media to devices.
devices += QDir(QStringLiteral("/media")).entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot);
// Add folders under /media/$USER to devices.
QDir mediaUserDir(QStringLiteral("/media/") + QString::fromLocal8Bit(qgetenv("USER")));
devices += mediaUserDir.entryInfoList(
QDir::AllDirs | QDir::NoDotAndDotDot);
// Add folders under /run/media/$USER to devices.
QDir runMediaUserDir(QStringLiteral("/run/media/") + QString::fromLocal8Bit(qgetenv("USER")));
devices += runMediaUserDir.entryInfoList(
QDir::AllDirs | QDir::NoDotAndDotDot);
foreach (QFileInfo device, devices) {
QFileInfo rbDBFileInfo(device.filePath() + QStringLiteral("/") + kPdbPath);
if (rbDBFileInfo.exists() && rbDBFileInfo.isFile()) {
QList<QString> data;
data << device.filePath();
data << IS_RECORDBOX_DEVICE;
TreeItem* foundDevice = new TreeItem(
device.fileName(),
QVariant(data));
foundDevices << foundDevice;
}
}
#else // __APPLE__
QFileInfoList devices = QDir(QStringLiteral("/Volumes")).entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot);
foreach (QFileInfo device, devices) {
QFileInfo rbDBFileInfo(device.filePath() + QStringLiteral("/") + kPdbPath);
if (rbDBFileInfo.exists() && rbDBFileInfo.isFile()) {
QList<QString> data;
data << device.filePath();
data << IS_RECORDBOX_DEVICE;
auto* foundDevice = new TreeItem(
device.fileName(),
QVariant(data));
foundDevices << foundDevice;
}
}
#endif
return foundDevices;
}
template<typename Base, typename T>
inline bool instanceof (const T* ptr) {
return dynamic_cast<const Base*>(ptr) != nullptr;
}
QString toUnicode(std::string toConvert) {
return QTextCodec::codecForName("UTF-16BE")->toUnicode(QByteArray(toConvert.c_str(), toConvert.length()));
}
// Functions getText and parseDeviceDB are roughly based on the following Java file:
// https://github.com/Deep-Symmetry/crate-digger/commit/f09fa9fc097a2a428c43245ddd542ac1370c1adc
// getText is needed because the strings in the PDB file "have a variety of obscure representations".
QString getText(rekordbox_pdb_t::device_sql_string_t* deviceString) {
if (instanceof <rekordbox_pdb_t::device_sql_short_ascii_t>(deviceString->body())) {
rekordbox_pdb_t::device_sql_short_ascii_t* shortAsciiString =
static_cast<rekordbox_pdb_t::device_sql_short_ascii_t*>(deviceString->body());
return QString::fromStdString(shortAsciiString->text());
} else if (instanceof <rekordbox_pdb_t::device_sql_long_ascii_t>(deviceString->body())) {
rekordbox_pdb_t::device_sql_long_ascii_t* longAsciiString =
static_cast<rekordbox_pdb_t::device_sql_long_ascii_t*>(deviceString->body());
return QString::fromStdString(longAsciiString->text());
} else if (instanceof <rekordbox_pdb_t::device_sql_long_utf16be_t>(deviceString->body())) {
rekordbox_pdb_t::device_sql_long_utf16be_t* longUtf16beString =
static_cast<rekordbox_pdb_t::device_sql_long_utf16be_t*>(deviceString->body());
return toUnicode(longUtf16beString->text());
}
return QString();
}
int createDevicePlaylist(QSqlDatabase& database, QString devicePath) {
int playlistID = -1;
QSqlQuery queryInsertIntoDevicePlaylist(database);
queryInsertIntoDevicePlaylist.prepare(
"INSERT INTO " + kRekordboxPlaylistsTable +
" (name) "
"VALUES (:name)");
queryInsertIntoDevicePlaylist.bindValue(":name", devicePath);
if (!queryInsertIntoDevicePlaylist.exec()) {
LOG_FAILED_QUERY(queryInsertIntoDevicePlaylist)
<< "devicePath: " << devicePath;
return playlistID;
}
QSqlQuery idQuery(database);
idQuery.prepare("select id from " + kRekordboxPlaylistsTable + " where name=:path");
idQuery.bindValue(":path", devicePath);
if (!idQuery.exec()) {
LOG_FAILED_QUERY(idQuery)
<< "devicePath: " << devicePath;
return playlistID;
}
while (idQuery.next()) {
playlistID = idQuery.value(idQuery.record().indexOf("id")).toInt();
}
return playlistID;
}
void insertTrack(
QSqlDatabase& database,
rekordbox_pdb_t::track_row_t* track,
QSqlQuery& query,
QSqlQuery& queryInsertIntoDevicePlaylistTracks,
QMap<uint32_t, QString>& artistsMap,
QMap<uint32_t, QString>& albumsMap,
QMap<uint32_t, QString>& genresMap,
QMap<uint32_t, QString>& keysMap,
QString devicePath,
QString device,
int audioFilesCount) {
int rbID = static_cast<int>(track->id());
QString title = getText(track->title());
QString artist = artistsMap[track->artist_id()];
QString album = albumsMap[track->album_id()];
QString year = QString::number(track->year());
QString genre = genresMap[track->genre_id()];
QString location = devicePath + getText(track->file_path());
float bpm = static_cast<float>(track->tempo() / 100.0);
int bitrate = static_cast<int>(track->bitrate());
QString key = keysMap[track->key_id()];
int playtime = static_cast<int>(track->duration());
int rating = static_cast<int>(track->rating());
QString comment = getText(track->comment());
QString tracknumber = QString::number(track->track_number());
QString anlzPath = devicePath + getText(track->analyze_path());
mixxx::RgbColor::optional_t color = mixxx::RgbColor::nullopt();
switch (static_cast<TrackColor>(track->color_id())) {
case TrackColor::Pink:
color = kTrackColorPink;
break;
case TrackColor::Red:
color = kTrackColorRed;
break;
case TrackColor::Orange:
color = kTrackColorOrange;
break;
case TrackColor::Yellow:
color = kTrackColorYellow;
break;
case TrackColor::Green:
color = kTrackColorGreen;
break;
case TrackColor::Aqua:
color = kTrackColorAqua;
break;
case TrackColor::Blue:
color = kTrackColorBlue;
break;
case TrackColor::Purple:
color = kTrackColorPurple;
break;
default:
break;
}
query.bindValue(":rb_id", rbID);
query.bindValue(":artist", artist);
query.bindValue(":title", title);
query.bindValue(":album", album);
query.bindValue(":genre", genre);
query.bindValue(":year", year);
query.bindValue(":duration", playtime);
query.bindValue(":location", location);
query.bindValue(":rating", rating);
query.bindValue(":comment", comment);
query.bindValue(":tracknumber", tracknumber);
query.bindValue(":key", key);
query.bindValue(":bpm", bpm);
query.bindValue(":bitrate", bitrate);
query.bindValue(":analyze_path", anlzPath);
query.bindValue(":device", device);
query.bindValue(":color", mixxx::RgbColor::toQVariant(color));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
}
int trackID = -1;
QSqlQuery finderQuery(database);
finderQuery.prepare("select id from " + kRekordboxLibraryTable + " where rb_id=:rb_id and device=:device");
finderQuery.bindValue(":rb_id", rbID);
finderQuery.bindValue(":device", device);
if (!finderQuery.exec()) {
LOG_FAILED_QUERY(finderQuery)
<< "rbID:" << rbID;
}
if (finderQuery.next()) {
trackID = finderQuery.value(finderQuery.record().indexOf("id")).toInt();
}
// Insert into device all tracks playlist
queryInsertIntoDevicePlaylistTracks.bindValue(":track_id", trackID);
queryInsertIntoDevicePlaylistTracks.bindValue(":position", audioFilesCount);
if (!queryInsertIntoDevicePlaylistTracks.exec()) {
LOG_FAILED_QUERY(queryInsertIntoDevicePlaylistTracks)
<< "trackID:" << trackID
<< "position:" << audioFilesCount;
}
}
void buildPlaylistTree(
QSqlDatabase& database,
TreeItem* parent,
uint32_t parentID,
QMap<uint32_t, QString>& playlistNameMap,
QMap<uint32_t, bool>& playlistIsFolderMap,
QMap<uint32_t, QMap<uint32_t, uint32_t>>& playlistTreeMap,
QMap<uint32_t, QMap<uint32_t, uint32_t>>& playlistTrackMap,
QString playlistPath,
QString device);
QString parseDeviceDB(mixxx::DbConnectionPoolPtr dbConnectionPool, TreeItem* deviceItem) {
QString device = deviceItem->getLabel();
QString devicePath = deviceItem->getData().toList()[0].toString();
qDebug() << "parseDeviceDB device: " << device << " devicePath: " << devicePath;
QString dbPath = devicePath + QStringLiteral("/") + kPdbPath;
if (!QFile(dbPath).exists()) {
return devicePath;
}
// The pooler limits the lifetime all thread-local connections,
// that should be closed immediately before exiting this function.
const mixxx::DbConnectionPooler dbConnectionPooler(dbConnectionPool);
QSqlDatabase database = mixxx::DbConnectionPooled(dbConnectionPool);
//Open the database connection in this thread.
VERIFY_OR_DEBUG_ASSERT(database.isOpen()) {
qDebug() << "Failed to open database for Rekordbox parser."
<< database.lastError();
return QString();
}
//Give thread a low priority
QThread* thisThread = QThread::currentThread();
thisThread->setPriority(QThread::LowPriority);
ScopedTransaction transaction(database);
QSqlQuery query(database);
query.prepare(
"INSERT INTO " + kRekordboxLibraryTable +
" (rb_id, artist, title, album, year,"
"genre,comment,tracknumber,bpm, bitrate,duration, location,"
"rating,key,analyze_path,device,color) VALUES (:rb_id, :artist, :title, :album, :year,:genre,"
":comment, :tracknumber,:bpm, :bitrate,:duration, :location,"
":rating,:key,:analyze_path,:device,:color)");
int audioFilesCount = 0;
// Create a playlist for all the tracks on a device
int playlistID = createDevicePlaylist(database, devicePath);
QSqlQuery queryInsertIntoDevicePlaylistTracks(database);
queryInsertIntoDevicePlaylistTracks.prepare(
"INSERT INTO " + kRekordboxPlaylistTracksTable +
" (playlist_id, track_id, position) "
"VALUES (:playlist_id, :track_id, :position)");
queryInsertIntoDevicePlaylistTracks.bindValue(":playlist_id", playlistID);
std::ifstream ifs(dbPath.toStdString(), std::ifstream::binary);
kaitai::kstream ks(&ifs);
rekordbox_pdb_t reckordboxDB = rekordbox_pdb_t(&ks);
// There are other types of tables (eg. COLOR), these are the only ones we are
// interested at the moment. Perhaps when/if
// https://bugs.launchpad.net/mixxx/+bug/1100882
// is completed, this can be revisted.
// Attempt was made to also recover HISTORY
// playlists (which are found on removable Rekordbox devices), however
// they didn't appear to contain valid row_ref_t structures.
const int totalTables = 8;
rekordbox_pdb_t::page_type_t tableOrder[totalTables] = {
rekordbox_pdb_t::PAGE_TYPE_KEYS,
rekordbox_pdb_t::PAGE_TYPE_GENRES,
rekordbox_pdb_t::PAGE_TYPE_ARTISTS,
rekordbox_pdb_t::PAGE_TYPE_ALBUMS,
rekordbox_pdb_t::PAGE_TYPE_PLAYLIST_ENTRIES,
rekordbox_pdb_t::PAGE_TYPE_TRACKS,
rekordbox_pdb_t::PAGE_TYPE_PLAYLIST_TREE,
rekordbox_pdb_t::PAGE_TYPE_HISTORY};
QMap<uint32_t, QString> keysMap;
QMap<uint32_t, QString> genresMap;
QMap<uint32_t, QString> artistsMap;
QMap<uint32_t, QString> albumsMap;
QMap<uint32_t, QString> playlistNameMap;
QMap<uint32_t, bool> playlistIsFolderMap;
QMap<uint32_t, QMap<uint32_t, uint32_t>> playlistTreeMap;
QMap<uint32_t, QMap<uint32_t, uint32_t>> playlistTrackMap;
bool folderOrPlaylistFound = false;
for (int tableOrderIndex = 0; tableOrderIndex < totalTables; tableOrderIndex++) {
for (
std::vector<rekordbox_pdb_t::table_t*>::iterator table = reckordboxDB.tables()->begin();
table != reckordboxDB.tables()->end();
++table) {
if ((*table)->type() == tableOrder[tableOrderIndex]) {
uint16_t lastIndex = (*table)->last_page()->index();
rekordbox_pdb_t::page_ref_t* currentRef = (*table)->first_page();
while (true) {
rekordbox_pdb_t::page_t* page = currentRef->body();
if (page->is_data_page()) {
for (
std::vector<rekordbox_pdb_t::row_group_t*>::iterator rowGroup = page->row_groups()->begin();
rowGroup != page->row_groups()->end();
++rowGroup) {
for (
std::vector<rekordbox_pdb_t::row_ref_t*>::iterator rowRef = (*rowGroup)->rows()->begin();
rowRef != (*rowGroup)->rows()->end();
++rowRef) {
if ((*rowRef)->present()) {
switch (tableOrder[tableOrderIndex]) {
case rekordbox_pdb_t::PAGE_TYPE_KEYS: {
// Key found, update map
rekordbox_pdb_t::key_row_t* key =
static_cast<rekordbox_pdb_t::key_row_t*>((*rowRef)->body());
keysMap[key->id()] = getText(key->name());
} break;
case rekordbox_pdb_t::PAGE_TYPE_GENRES: {
// Genre found, update map
rekordbox_pdb_t::genre_row_t* genre =
static_cast<rekordbox_pdb_t::genre_row_t*>((*rowRef)->body());
genresMap[genre->id()] = getText(genre->name());
} break;
case rekordbox_pdb_t::PAGE_TYPE_ARTISTS: {
// Artist found, update map
rekordbox_pdb_t::artist_row_t* artist =
static_cast<rekordbox_pdb_t::artist_row_t*>((*rowRef)->body());
artistsMap[artist->id()] = getText(artist->name());
} break;
case rekordbox_pdb_t::PAGE_TYPE_ALBUMS: {
// Album found, update map
rekordbox_pdb_t::album_row_t* album =
static_cast<rekordbox_pdb_t::album_row_t*>((*rowRef)->body());
albumsMap[album->id()] = getText(album->name());
} break;
case rekordbox_pdb_t::PAGE_TYPE_PLAYLIST_ENTRIES: {
// Playlist to track mapping found, update map
rekordbox_pdb_t::playlist_entry_row_t* playlistEntry =
static_cast<rekordbox_pdb_t::playlist_entry_row_t*>((*rowRef)->body());
playlistTrackMap[playlistEntry->playlist_id()][playlistEntry->entry_index()] =
playlistEntry->track_id();
} break;
case rekordbox_pdb_t::PAGE_TYPE_TRACKS: {
// Track found, insert into database
insertTrack(
database, static_cast<rekordbox_pdb_t::track_row_t*>((*rowRef)->body()), query, queryInsertIntoDevicePlaylistTracks, artistsMap, albumsMap, genresMap, keysMap, devicePath, device, audioFilesCount);
audioFilesCount++;
} break;
case rekordbox_pdb_t::PAGE_TYPE_PLAYLIST_TREE: {
// Playlist tree node found, update map
rekordbox_pdb_t::playlist_tree_row_t* playlistTree =
static_cast<rekordbox_pdb_t::playlist_tree_row_t*>((*rowRef)->body());
playlistNameMap[playlistTree->id()] = getText(playlistTree->name());
playlistIsFolderMap[playlistTree->id()] = playlistTree->is_folder();
playlistTreeMap[playlistTree->parent_id()][playlistTree->sort_order()] = playlistTree->id();
folderOrPlaylistFound = true;
} break;
default:
break;
}
}
}
}
}
if (currentRef->index() == lastIndex) {
break;
} else {
currentRef = page->next_page();
}
}
}
}
}
if (audioFilesCount > 0 || folderOrPlaylistFound) {
// If we have found anything, recursively build playlist/folder TreeItem children
// for the original device TreeItem
buildPlaylistTree(database, deviceItem, 0, playlistNameMap, playlistIsFolderMap, playlistTreeMap, playlistTrackMap, devicePath, device);
}
qDebug() << "Found: " << audioFilesCount << " audio files in Rekordbox device " << device;
transaction.commit();
return devicePath;
}
void buildPlaylistTree(
QSqlDatabase& database,
TreeItem* parent,
uint32_t parentID,
QMap<uint32_t, QString>& playlistNameMap,
QMap<uint32_t, bool>& playlistIsFolderMap,
QMap<uint32_t, QMap<uint32_t, uint32_t>>& playlistTreeMap,
QMap<uint32_t, QMap<uint32_t, uint32_t>>& playlistTrackMap,
QString playlistPath,
QString device) {
for (uint32_t childIndex = 0; childIndex < (uint32_t)playlistTreeMap[parentID].size(); childIndex++) {
uint32_t childID = playlistTreeMap[parentID][childIndex];
QString playlistItemName = playlistNameMap[childID];
QString currentPath = playlistPath + kPLaylistPathDelimiter + playlistItemName;
QList<QString> data;
data << currentPath;
data << IS_NOT_RECORDBOX_DEVICE;
TreeItem* child = parent->appendChild(playlistItemName, QVariant(data));
// Create a playlist for this child
QSqlQuery queryInsertIntoPlaylist(database);
queryInsertIntoPlaylist.prepare(
"INSERT INTO " + kRekordboxPlaylistsTable +
" (name) "
"VALUES (:name)");
queryInsertIntoPlaylist.bindValue(":name", currentPath);
if (!queryInsertIntoPlaylist.exec()) {
LOG_FAILED_QUERY(queryInsertIntoPlaylist)
<< "currentPath" << currentPath;
return;
}
QSqlQuery idQuery(database);
idQuery.prepare("select id from " + kRekordboxPlaylistsTable + " where name=:path");
idQuery.bindValue(":path", currentPath);
if (!idQuery.exec()) {
LOG_FAILED_QUERY(idQuery)
<< "currentPath" << currentPath;
return;
}
int playlistID = -1;
while (idQuery.next()) {
playlistID = idQuery.value(idQuery.record().indexOf("id")).toInt();
}
QSqlQuery queryInsertIntoPlaylistTracks(database);
queryInsertIntoPlaylistTracks.prepare(
"INSERT INTO " + kRekordboxPlaylistTracksTable +
" (playlist_id, track_id, position) "
"VALUES (:playlist_id, :track_id, :position)");
if (playlistTrackMap.count(childID)) {
// Add playlist tracks for children
for (uint32_t trackIndex = 1; trackIndex <= static_cast<uint32_t>(playlistTrackMap[childID].size()); trackIndex++) {
uint32_t rbTrackID = playlistTrackMap[childID][trackIndex];
int trackID = -1;
QSqlQuery finderQuery(database);
finderQuery.prepare("select id from " + kRekordboxLibraryTable + " where rb_id=:rb_id and device=:device");
finderQuery.bindValue(":rb_id", rbTrackID);
finderQuery.bindValue(":device", device);
if (!finderQuery.exec()) {
LOG_FAILED_QUERY(finderQuery)
<< "rbTrackID:" << rbTrackID
<< "device:" << device;
return;
}
if (finderQuery.next()) {
trackID = finderQuery.value(finderQuery.record().indexOf("id")).toInt();
}
queryInsertIntoPlaylistTracks.bindValue(":playlist_id", playlistID);
queryInsertIntoPlaylistTracks.bindValue(":track_id", trackID);
queryInsertIntoPlaylistTracks.bindValue(":position", static_cast<int>(trackIndex));
if (!queryInsertIntoPlaylistTracks.exec()) {
LOG_FAILED_QUERY(queryInsertIntoPlaylistTracks)
<< "playlistID:" << playlistID
<< "trackID:" << trackID
<< "trackIndex:" << trackIndex;
return;
}
}
}
if (playlistIsFolderMap[childID]) {
// If this child is a folder (playlists are only leaf nodes), build playlist tree for it
buildPlaylistTree(database, child, childID, playlistNameMap, playlistIsFolderMap, playlistTreeMap, playlistTrackMap, currentPath, device);
}
}
}
void clearDeviceTables(QSqlDatabase& database, TreeItem* child) {
ScopedTransaction transaction(database);
int trackID = -1;
int playlistID = -1;
QSqlQuery tracksQuery(database);
tracksQuery.prepare("select id from " + kRekordboxLibraryTable + " where device=:device");
tracksQuery.bindValue(":device", child->getLabel());
QSqlQuery deletePlaylistsQuery(database);
deletePlaylistsQuery.prepare("delete from " + kRekordboxPlaylistsTable + " where id=:id");
QSqlQuery deletePlaylistTracksQuery(database);
deletePlaylistTracksQuery.prepare("delete from " + kRekordboxPlaylistTracksTable + " where playlist_id=:playlist_id");
if (!tracksQuery.exec()) {
LOG_FAILED_QUERY(tracksQuery)
<< "device:" << child->getLabel();
}
while (tracksQuery.next()) {
trackID = tracksQuery.value(tracksQuery.record().indexOf("id")).toInt();
QSqlQuery playlistTracksQuery(database);
playlistTracksQuery.prepare("select playlist_id from " + kRekordboxPlaylistTracksTable + " where track_id=:track_id");
playlistTracksQuery.bindValue(":track_id", trackID);
if (!playlistTracksQuery.exec()) {
LOG_FAILED_QUERY(playlistTracksQuery)
<< "trackID:" << trackID;
}
while (playlistTracksQuery.next()) {
playlistID = playlistTracksQuery.value(playlistTracksQuery.record().indexOf("playlist_id")).toInt();
deletePlaylistsQuery.bindValue(":id", playlistID);
if (!deletePlaylistsQuery.exec()) {
LOG_FAILED_QUERY(deletePlaylistsQuery)
<< "playlistID:" << playlistID;
}
deletePlaylistTracksQuery.bindValue(":playlist_id", playlistID);
if (!deletePlaylistTracksQuery.exec()) {
LOG_FAILED_QUERY(deletePlaylistTracksQuery)
<< "playlistID:" << playlistID;
}
}
}
QSqlQuery deleteTracksQuery(database);
deleteTracksQuery.prepare("delete from " + kRekordboxLibraryTable + " where device=:device");
deleteTracksQuery.bindValue(":device", child->getLabel());
if (!deleteTracksQuery.exec()) {
LOG_FAILED_QUERY(deleteTracksQuery)
<< "device:" << child->getLabel();
}
transaction.commit();
}
void setHotCue(TrackPointer track, double position, int id, QString label, mixxx::RgbColor::optional_t color) {
CuePointer pCue;
bool hotCueFound = false;
for (const CuePointer& trackCue : track->getCuePoints()) {
if (trackCue->getHotCue() == id) {
pCue = trackCue;
hotCueFound = true;
break;
}
}
if (!hotCueFound) {
pCue = CuePointer(track->createAndAddCue());
}
pCue->setType(mixxx::CueType::HotCue);
pCue->setStartPosition(position);
pCue->setHotCue(id);
pCue->setLabel(label);
if (color) {
pCue->setColor(*color);
}
}
void readAnalyze(TrackPointer track, double sampleRate, int timingOffset, bool ignoreBeatsAndLegacyCues, QString anlzPath) {
if (!QFile(anlzPath).exists()) {
return;
}
qDebug() << "Rekordbox ANLZ path:" << anlzPath << " for: " << track->getTitle();
std::ifstream ifs(anlzPath.toStdString(), std::ifstream::binary);
kaitai::kstream ks(&ifs);
rekordbox_anlz_t anlz = rekordbox_anlz_t(&ks);
double sampleRateKhz = sampleRate / 1000.0;
double samples = sampleRateKhz * mixxx::kEngineChannelCount;
QList<memory_cue_t> memoryCues;
int lastHotCueIndex = 0;
double cueLoopStartPosition = kLongestPosition;
double cueLoopEndPosition = kLongestPosition;
for (std::vector<rekordbox_anlz_t::tagged_section_t*>::iterator section = anlz.sections()->begin(); section != anlz.sections()->end(); ++section) {
switch ((*section)->fourcc()) {
case rekordbox_anlz_t::SECTION_TAGS_BEAT_GRID: {
if (ignoreBeatsAndLegacyCues) {
break;
}
rekordbox_anlz_t::beat_grid_tag_t* beatGridTag = static_cast<rekordbox_anlz_t::beat_grid_tag_t*>((*section)->body());
QVector<double> beats;
for (std::vector<rekordbox_anlz_t::beat_grid_beat_t*>::iterator beat = beatGridTag->beats()->begin(); beat != beatGridTag->beats()->end(); ++beat) {
int time = static_cast<int>((*beat)->time()) - timingOffset;
// Ensure no offset times are less than 1
if (time < 1) {
time = 1;
}
beats << (sampleRateKhz * static_cast<double>(time));
}
QHash<QString, QString> extraVersionInfo;
BeatsPointer pBeats = BeatFactory::makePreferredBeats(
*track, beats, extraVersionInfo, false, false, sampleRate, 0, 0, 0);
track->setBeats(pBeats);
} break;
case rekordbox_anlz_t::SECTION_TAGS_CUES: {
if (ignoreBeatsAndLegacyCues) {
break;
}
rekordbox_anlz_t::cue_tag_t* cuesTag = static_cast<rekordbox_anlz_t::cue_tag_t*>((*section)->body());
for (std::vector<rekordbox_anlz_t::cue_entry_t*>::iterator cueEntry = cuesTag->cues()->begin(); cueEntry != cuesTag->cues()->end(); ++cueEntry) {
int time = static_cast<int>((*cueEntry)->time()) - timingOffset;
// Ensure no offset times are less than 1
if (time < 1) {
time = 1;
}
double position = samples * static_cast<double>(time);
switch (cuesTag->type()) {
case rekordbox_anlz_t::CUE_LIST_TYPE_MEMORY_CUES: {
switch ((*cueEntry)->type()) {
case rekordbox_anlz_t::CUE_ENTRY_TYPE_MEMORY_CUE: {
memory_cue_t memoryCue;
memoryCue.position = position;
memoryCue.color = mixxx::RgbColor::nullopt();
memoryCues << memoryCue;
} break;
case rekordbox_anlz_t::CUE_ENTRY_TYPE_LOOP: {
// As Mixxx can only have 1 saved loop, use the first occurance of a memory loop relative to the start of the track
if (position < cueLoopStartPosition) {
cueLoopStartPosition = position;
int endTime = static_cast<int>((*cueEntry)->loop_time()) - timingOffset;
// Ensure no offset times are less than 1
if (endTime < 1) {
endTime = 1;
}
cueLoopEndPosition = samples * static_cast<double>(endTime);
}
} break;
}
} break;
case rekordbox_anlz_t::CUE_LIST_TYPE_HOT_CUES: {
int hotCueIndex = static_cast<int>((*cueEntry)->hot_cue() - 1);
if (hotCueIndex > lastHotCueIndex) {
lastHotCueIndex = hotCueIndex;
}
setHotCue(track, position, hotCueIndex, QString(), mixxx::RgbColor::nullopt());
} break;
}
}
} break;
case rekordbox_anlz_t::SECTION_TAGS_CUES_2: {
rekordbox_anlz_t::cue_extended_tag_t* cuesExtendedTag = static_cast<rekordbox_anlz_t::cue_extended_tag_t*>((*section)->body());
for (std::vector<rekordbox_anlz_t::cue_extended_entry_t*>::iterator cueExtendedEntry = cuesExtendedTag->cues()->begin(); cueExtendedEntry != cuesExtendedTag->cues()->end(); ++cueExtendedEntry) {
int time = static_cast<int>((*cueExtendedEntry)->time()) - timingOffset;
// Ensure no offset times are less than 1
if (time < 1) {
time = 1;
}
double position = samples * static_cast<double>(time);
switch (cuesExtendedTag->type()) {
case rekordbox_anlz_t::CUE_LIST_TYPE_MEMORY_CUES: {
switch ((*cueExtendedEntry)->type()) {
case rekordbox_anlz_t::CUE_ENTRY_TYPE_MEMORY_CUE: {
memory_cue_t memoryCue;
memoryCue.position = position;
memoryCue.comment = toUnicode((*cueExtendedEntry)->comment());
memoryCue.color = mixxx::RgbColor(qRgb(static_cast<int>((*cueExtendedEntry)->color_red()), static_cast<int>((*cueExtendedEntry)->color_green()), static_cast<int>((*cueExtendedEntry)->color_blue())));
memoryCues << memoryCue;
} break;
case rekordbox_anlz_t::CUE_ENTRY_TYPE_LOOP: {
// As Mixxx can only have 1 saved loop, use the first occurance of a memory loop relative to the start of the track
if (position < cueLoopStartPosition) {
cueLoopStartPosition = position;
int endTime = static_cast<int>((*cueExtendedEntry)->loop_time()) - timingOffset;
// Ensure no offset times are less than 1
if (endTime < 1) {
endTime = 1;
}
cueLoopEndPosition = samples * static_cast<double>(endTime);
}
} break;
}
} break;
case rekordbox_anlz_t::CUE_LIST_TYPE_HOT_CUES: {
int hotCueIndex = static_cast<int>((*cueExtendedEntry)->hot_cue() - 1);
if (hotCueIndex > lastHotCueIndex) {
lastHotCueIndex = hotCueIndex;
}
setHotCue(track, position, hotCueIndex, toUnicode((*cueExtendedEntry)->comment()), mixxx::RgbColor(qRgb(static_cast<int>((*cueExtendedEntry)->color_red()), static_cast<int>((*cueExtendedEntry)->color_green()), static_cast<int>((*cueExtendedEntry)->color_blue()))));
} break;
}
}
} break;
default:
break;
}
}
if (memoryCues.size() > 0) {
std::sort(memoryCues.begin(), memoryCues.end(), [](const memory_cue_t& a, const memory_cue_t& b) -> bool {
return a.position < b.position;
});
// Set first chronological memory cue as Mixxx MainCue
memory_cue_t firstCue = memoryCues[0];
track->setCuePoint(CuePosition(firstCue.position));
CuePointer pLoadCue = track->findCueByType(mixxx::CueType::MainCue);
pLoadCue->setLabel(firstCue.comment);
// Add remaining memory cues as hot cues (after actual found hotcues) as Mixxx can only have 1 cue
for (int memoryCueIndex = 1; memoryCueIndex < memoryCues.size(); memoryCueIndex++) {
memory_cue_t memoryCue = memoryCues[memoryCueIndex];
setHotCue(track, memoryCue.position, lastHotCueIndex + memoryCueIndex, memoryCue.comment, memoryCue.color);
}
}
if (cueLoopStartPosition < kLongestPosition) {
CuePointer pCue(track->createAndAddCue());
pCue->setStartPosition(cueLoopStartPosition);
pCue->setEndPosition(cueLoopEndPosition);
pCue->setType(mixxx::CueType::Loop);
}
}
} // anonymous namespace
RekordboxPlaylistModel::RekordboxPlaylistModel(QObject* parent,
TrackCollectionManager* trackCollectionManager,
QSharedPointer<BaseTrackCache> trackSource)
: BaseExternalPlaylistModel(parent, trackCollectionManager, "mixxx.db.model.rekordbox.playlistmodel", kRekordboxPlaylistsTable, kRekordboxPlaylistTracksTable, trackSource) {
}
void RekordboxPlaylistModel::initSortColumnMapping() {
// Add a bijective mapping between the SortColumnIds and column indices
for (int i = 0; i < TrackModel::SortColumnId::NUM_SORTCOLUMNIDS; ++i) {
m_columnIndexBySortColumnId[i] = -1;