-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathartwork_manager.cpp
More file actions
1652 lines (1405 loc) · 67.4 KB
/
artwork_manager.cpp
File metadata and controls
1652 lines (1405 loc) · 67.4 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
#include "stdafx.h"
#include "artwork_manager.h"
#include "preferences.h"
#include <winhttp.h>
#include <shlwapi.h>
#include <shlobj.h>
#include <thread>
#include <chrono>
#include <algorithm>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// Normalize diacritics/accented characters to ASCII equivalents (UTF-8 aware)
static std::string normalize_diacritics(const std::string& s) {
std::string result;
result.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
unsigned char c = static_cast<unsigned char>(s[i]);
// Check for UTF-8 two-byte sequences starting with 0xC3 (Latin-1 Supplement)
if (c == 0xC3 && i + 1 < s.size()) {
unsigned char next = static_cast<unsigned char>(s[i + 1]);
char replacement = 0;
// Uppercase variants (0xC3 0x80-0x9F)
if (next >= 0x80 && next <= 0x85) replacement = 'A'; // À Á Â Ã Ä Å
else if (next == 0x86) { result += "AE"; i++; continue; } // Æ
else if (next == 0x87) replacement = 'C'; // Ç
else if (next >= 0x88 && next <= 0x8B) replacement = 'E'; // È É Ê Ë
else if (next >= 0x8C && next <= 0x8F) replacement = 'I'; // Ì Í Î Ï
else if (next == 0x90) replacement = 'D'; // Ð
else if (next == 0x91) replacement = 'N'; // Ñ
else if (next >= 0x92 && next <= 0x96) replacement = 'O'; // Ò Ó Ô Õ Ö
else if (next == 0x98) replacement = 'O'; // Ø
else if (next >= 0x99 && next <= 0x9C) replacement = 'U'; // Ù Ú Û Ü
else if (next == 0x9D) replacement = 'Y'; // Ý
// Lowercase variants (0xC3 0xA0-0xBF)
else if (next >= 0xA0 && next <= 0xA5) replacement = 'a'; // à á â ã ä å
else if (next == 0xA6) { result += "ae"; i++; continue; } // æ
else if (next == 0xA7) replacement = 'c'; // ç
else if (next >= 0xA8 && next <= 0xAB) replacement = 'e'; // è é ê ë
else if (next >= 0xAC && next <= 0xAF) replacement = 'i'; // ì í î ï
else if (next == 0xB0) replacement = 'd'; // ð
else if (next == 0xB1) replacement = 'n'; // ñ
else if (next >= 0xB2 && next <= 0xB6) replacement = 'o'; // ò ó ô õ ö
else if (next == 0xB8) replacement = 'o'; // ø
else if (next >= 0xB9 && next <= 0xBC) replacement = 'u'; // ù ú û ü
else if (next == 0xBD || next == 0xBF) replacement = 'y'; // ý ÿ
else if (next == 0x9F) { result += "ss"; i++; continue; } // ß (German eszett)
if (replacement) {
result += replacement;
i++; // Skip the second byte
continue;
}
}
// Check for UTF-8 two-byte sequences starting with 0xC5 (Latin Extended-A)
if (c == 0xC5 && i + 1 < s.size()) {
unsigned char next = static_cast<unsigned char>(s[i + 1]);
char replacement = 0;
if (next == 0x92 || next == 0x93) { // Œ œ
result += (next == 0x92) ? "OE" : "oe";
i++;
continue;
}
else if (next == 0xA0 || next == 0xA1) replacement = (next == 0xA0) ? 'S' : 's'; // Š š
else if (next == 0xBD || next == 0xBE) replacement = (next == 0xBD) ? 'Z' : 'z'; // Ž ž
if (replacement) {
result += replacement;
i++;
continue;
}
}
// Pass through other characters unchanged
result += s[i];
}
return result;
}
// Normalize string for fuzzy matching: removes diacritics, punctuation, normalizes "AND"/"&", lowercases
static std::string normalize_for_matching(const std::string& s) {
// First normalize diacritics (ö→o, é→e, etc.)
std::string diacritic_normalized = normalize_diacritics(s);
std::string result;
result.reserve(diacritic_normalized.size());
for (size_t i = 0; i < diacritic_normalized.size(); ++i) {
char c = diacritic_normalized[i];
// Skip punctuation (periods, commas, apostrophes, etc.)
if (c == '.' || c == ',' || c == '\'' || c == '!' || c == '?' || c == '-') {
continue;
}
// Convert to lowercase
result += std::tolower(static_cast<unsigned char>(c));
}
// Normalize " and " to " & " for consistent comparison
// Process the result to handle "and" vs "&"
std::string normalized;
normalized.reserve(result.size());
for (size_t i = 0; i < result.size(); ++i) {
// Check for " and " pattern (with spaces)
if (i + 4 < result.size() &&
result[i] == ' ' &&
result[i+1] == 'a' &&
result[i+2] == 'n' &&
result[i+3] == 'd' &&
result[i+4] == ' ') {
normalized += ' '; // Replace " and " with single space (remove the word entirely)
i += 4; // Skip past " and " (loop will add 1 more)
continue;
}
// Check for " & " pattern
if (i + 2 < result.size() &&
result[i] == ' ' &&
result[i+1] == '&' &&
result[i+2] == ' ') {
normalized += ' '; // Replace " & " with single space
i += 2; // Skip past " & "
continue;
}
normalized += result[i];
}
// Collapse multiple spaces into one
result.clear();
bool last_was_space = false;
for (char c : normalized) {
if (c == ' ') {
if (!last_was_space) {
result += c;
last_was_space = true;
}
} else {
result += c;
last_was_space = false;
}
}
// Trim leading/trailing spaces
size_t start = result.find_first_not_of(' ');
if (start == std::string::npos) return "";
size_t end = result.find_last_not_of(' ');
return result.substr(start, end - start + 1);
}
// Case-insensitive string comparison helper for matching artist/track names
static bool strings_equal_ignore_case(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(a[i])) !=
std::tolower(static_cast<unsigned char>(b[i]))) {
return false;
}
}
return true;
}
// Fuzzy string comparison that normalizes before comparing
static bool strings_match_fuzzy(const std::string& a, const std::string& b) {
// First try exact case-insensitive match (fast path)
if (a.size() == b.size() && strings_equal_ignore_case(a, b)) {
return true;
}
// Normalize both strings and compare
std::string norm_a = normalize_for_matching(a);
std::string norm_b = normalize_for_matching(b);
return norm_a == norm_b;
}
// Helper to strip "The " prefix from artist names for fuzzy matching
static std::string strip_the_prefix(const std::string& s) {
if (s.size() > 4) {
// Check for "The " prefix (case-insensitive)
if ((s[0] == 'T' || s[0] == 't') &&
(s[1] == 'H' || s[1] == 'h') &&
(s[2] == 'E' || s[2] == 'e') &&
s[3] == ' ') {
return s.substr(4);
}
}
return s;
}
// Fuzzy artist comparison: handles case, punctuation, "The " prefix, and "AND"/"&" differences
static bool artists_match(const std::string& a, const std::string& b) {
// First try exact case-insensitive match (fast path)
if (strings_equal_ignore_case(a, b)) return true;
// Try fuzzy match (handles punctuation like "T. Rex" vs "T Rex", and "AND" vs "&")
if (strings_match_fuzzy(a, b)) return true;
// Try matching after stripping "The " prefix from both
std::string a_stripped = strip_the_prefix(a);
std::string b_stripped = strip_the_prefix(b);
if (strings_equal_ignore_case(a_stripped, b_stripped)) return true;
// Try fuzzy match on stripped versions too
return strings_match_fuzzy(a_stripped, b_stripped);
}
#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "shlwapi.lib")
// External configuration variables
extern cfg_bool cfg_enable_itunes;
extern cfg_bool cfg_enable_discogs;
extern cfg_bool cfg_enable_lastfm;
extern cfg_bool cfg_enable_deezer;
extern cfg_bool cfg_enable_musicbrainz;
extern cfg_string cfg_itunes_key;
extern cfg_string cfg_discogs_key;
extern cfg_string cfg_discogs_consumer_key;
extern cfg_string cfg_discogs_consumer_secret;
extern cfg_string cfg_lastfm_key;
extern cfg_int cfg_http_timeout;
extern cfg_int cfg_retry_count;
extern cfg_bool cfg_enable_disk_cache;
extern cfg_bool cfg_single_file_cache;
// Static member initialization
std::atomic<bool> artwork_manager::initialized_(false);
void artwork_manager::initialize() {
if (initialized_.exchange(true)) return; // Already initialized
async_io_manager::instance().initialize(4); // 4 thread pool workers
}
void artwork_manager::shutdown() {
if (!initialized_.exchange(false)) return; // Not initialized
async_io_manager::instance().shutdown();
}
void artwork_manager::get_artwork_async(metadb_handle_ptr track, artwork_callback callback) {
ASSERT_MAIN_THREAD();
// DEBUG: Track artwork loading request
{
metadb_info_container::ptr info_container = track->get_info_ref();
const file_info* info = &info_container->info();
pfc::string8 artist = info->meta_get("ARTIST", 0) ? info->meta_get("ARTIST", 0) : "Unknown Artist";
pfc::string8 track_name = info->meta_get("TITLE", 0) ? info->meta_get("TITLE", 0) : "Unknown Track";
pfc::string8 file_path = track->get_path();
}
if (!initialized_) {
initialize();
}
try {
// Start the fully asynchronous pipeline
search_artwork_pipeline(track, callback);
} catch (const std::exception& e) {
artwork_result result;
result.success = false;
result.error_message = e.what();
callback(result);
}
}
void artwork_manager::get_artwork_async_with_metadata(const char* artist, const char* track, artwork_callback callback) {
ASSERT_MAIN_THREAD();
if (!initialized_) {
initialize();
}
try {
// Use explicit metadata instead of track metadata
pfc::string8 artist_str = artist ? artist : "Unknown Artist";
pfc::string8 track_str = track ? track : "Unknown Track";
pfc::string8 cache_key = cfg_single_file_cache ? pfc::string8("current") : generate_cache_key(artist_str, track_str);
// In single-file cache mode, skip cache reads (key is always "current" so it would
// return the previous track's artwork). Go directly to API search, still write to cache.
if (cfg_single_file_cache) {
search_apis_async_metadata(artist_str, track_str, cache_key, callback);
} else {
// Start async pipeline: Cache -> APIs (skip local files since we don't have a track)
check_cache_async_metadata(cache_key, artist_str, track_str, callback);
}
} catch (const std::exception& e) {
artwork_result result;
result.success = false;
result.error_message = e.what();
callback(result);
}
}
void artwork_manager::search_artwork_pipeline(metadb_handle_ptr track, artwork_callback callback) {
ASSERT_MAIN_THREAD();
// Extract metadata and path on main thread (this is fast)
metadb_info_container::ptr info_container = track->get_info_ref();
const file_info* info = &info_container->info();
pfc::string8 artist = info->meta_get("ARTIST", 0) ? info->meta_get("ARTIST", 0) : "Unknown Artist";
pfc::string8 track_name = info->meta_get("TITLE", 0) ? info->meta_get("TITLE", 0) : "Unknown Track";
pfc::string8 file_path = track->get_path();
pfc::string8 cache_key = cfg_single_file_cache ? pfc::string8("current") : generate_cache_key(artist, track_name);
// CACHE SKIP FOR INTERNET STREAMS: For internet streams, metadata is often wrong initially
// (belongs to previous track), causing wrong cached artwork to be returned.
// Skip cache reads and go directly to local (tagged) artwork search.
// Exception: In single-file cache mode, we still WRITE results to "current.cache"
// so external consumers (e.g., JScript Panel 3 Thumbs) can pick up the artwork.
const double length = track->get_length();
bool is_internet_stream = strstr(file_path.c_str(), "://") &&
!(strstr(file_path.c_str(), "file://") == file_path.c_str());
if (is_internet_stream) {
pfc::string8 stream_cache_key = cfg_single_file_cache ? cache_key : pfc::string8("");
if (cfg_skip_local_artwork) {
// Skip local artwork entirely, go directly to API search
if (artist != "Unknown Artist" && track_name != "Unknown Track") {
search_apis_async(artist, track_name, stream_cache_key, callback);
}
} else {
// For internet streams, skip cache but still check for tagged artwork first
// This prevents stale artwork from being returned when track metadata changes
find_local_artwork_async(track, [artist, track_name, stream_cache_key, callback](const artwork_result& result) {
if (result.success) {
// Tagged artwork found - cache it in single-file mode for external consumers
if (cfg_enable_disk_cache && !stream_cache_key.is_empty()) {
async_io_manager::instance().cache_set_async(stream_cache_key, result.data);
}
callback(result);
} else {
// No tagged artwork - fall back to API search
if (artist != "Unknown Artist" && track_name != "Unknown Track") {
search_apis_async(artist, track_name, stream_cache_key, callback);
}
}
});
}
} else if (cfg_single_file_cache) {
// In single-file cache mode, skip cache reads (key is always "current" so it would
// return the previous track's artwork). Go directly to local -> APIs, still write to cache.
search_local_async(file_path, cache_key, track, callback);
} else {
// For local files, use normal cache -> local -> APIs pipeline
check_cache_async(cache_key, track, callback);
}
}
void artwork_manager::check_cache_async(const pfc::string8& cache_key, metadb_handle_ptr track, artwork_callback callback) {
async_io_manager::instance().cache_get_async(cache_key,
[cache_key, track, callback](bool success, const pfc::array_t<t_uint8>& data, const pfc::string8& error) {
if (success && data.get_size() > 0) {
// Cache hit - validate and return
validate_and_complete_result(data, callback);
} else {
// Cache miss - continue to local search
pfc::string8 file_path = track->get_path();
search_local_async(file_path, cache_key, track, callback);
}
});
}
void artwork_manager::check_cache_async_metadata(const pfc::string8& cache_key, const pfc::string8& artist, const pfc::string8& track, artwork_callback callback) {
// Check cache first, then fall back to API search on miss
async_io_manager::instance().cache_get_async(cache_key,
[cache_key, artist, track, callback](bool success, const pfc::array_t<t_uint8>& data, const pfc::string8& error) {
if (success && data.get_size() > 0) {
// Cache hit - validate and return
validate_and_complete_result(data, callback);
} else {
// Cache miss - skip local search and go directly to APIs
search_apis_async_metadata(artist, track, cache_key, callback);
}
});
}
void artwork_manager::search_apis_async_metadata(const pfc::string8& artist, const pfc::string8& track, const pfc::string8& cache_key, artwork_callback callback) {
// Use the existing search_apis_async function
search_apis_async(artist, track, cache_key, callback);
}
void artwork_manager::search_local_async(const pfc::string8& file_path, const pfc::string8& cache_key, metadb_handle_ptr track, artwork_callback callback) {
// If user wants to skip local artwork, go directly to API search
if (cfg_skip_local_artwork) {
metadb_info_container::ptr info_container = track->get_info_ref();
const file_info* info = &info_container->info();
pfc::string8 artist = info->meta_get("ARTIST", 0) ? info->meta_get("ARTIST", 0) : "Unknown Artist";
pfc::string8 track_name = info->meta_get("TITLE", 0) ? info->meta_get("TITLE", 0) : "Unknown Track";
search_apis_async(artist, track_name, cache_key, callback);
return;
}
// ALWAYS try to find tagged artwork first, regardless of local/internet file type
// Internet streams (like YouTube videos) can have embedded artwork too
find_local_artwork_async(track, [cache_key, track, callback](const artwork_result& result) {
if (result.success) {
// Local artwork found - in single-file cache mode, write to current.cache
// so external consumers (e.g., JScript Panel 3 Thumbs) see the correct artwork.
// In normal cache mode, skip caching since local files are already on disk
// and caching causes stale images when external tools overwrite the file.
if (cfg_single_file_cache && cfg_enable_disk_cache) {
async_io_manager::instance().cache_set_async(cache_key, result.data);
}
callback(result);
} else {
// Local search failed - continue to API search
metadb_info_container::ptr info_container = track->get_info_ref();
const file_info* info = &info_container->info();
pfc::string8 artist = info->meta_get("ARTIST", 0) ? info->meta_get("ARTIST", 0) : "Unknown Artist";
pfc::string8 track_name = info->meta_get("TITLE", 0) ? info->meta_get("TITLE", 0) : "Unknown Track";
search_apis_async(artist, track_name, cache_key, callback);
}
});
}
void artwork_manager::search_apis_async(const pfc::string8& artist, const pfc::string8& track, const pfc::string8& cache_key, artwork_callback callback) {
// Get the API search order from user preferences
auto api_order = get_api_search_order();
// Helper function to search with the ordered APIs
search_apis_by_priority(artist, track, cache_key, callback, api_order, 0);
}
void artwork_manager::search_apis_by_priority(const pfc::string8& artist, const pfc::string8& track, const pfc::string8& cache_key, artwork_callback callback, const std::vector<ApiType>& api_order, size_t index) {
if (index >= api_order.size()) {
// No more APIs to try
artwork_result final_result;
final_result.success = false;
final_result.error_message = "No artwork found from any source";
callback(final_result);
return;
}
ApiType current_api = api_order[index];
// Check if this API is enabled and has required keys
bool api_enabled = false;
switch (current_api) {
case ApiType::iTunes:
api_enabled = cfg_enable_itunes;
break;
case ApiType::Deezer:
api_enabled = cfg_enable_deezer;
break;
case ApiType::LastFm:
api_enabled = cfg_enable_lastfm && !cfg_lastfm_key.is_empty();
break;
case ApiType::MusicBrainz:
api_enabled = cfg_enable_musicbrainz;
break;
case ApiType::Discogs:
api_enabled = cfg_enable_discogs &&
(!cfg_discogs_key.is_empty() ||
(!cfg_discogs_consumer_key.is_empty() && !cfg_discogs_consumer_secret.is_empty()));
break;
}
if (!api_enabled) {
// Skip this API and try the next one
search_apis_by_priority(artist, track, cache_key, callback, api_order, index + 1);
return;
}
// Create a callback that will either return success or try the next API
auto api_callback = [artist, track, cache_key, callback, api_order, index](const artwork_result& result) {
pfc::string8 api_name;
switch (api_order[index]) {
case ApiType::iTunes: api_name = "iTunes"; break;
case ApiType::Deezer: api_name = "Deezer"; break;
case ApiType::LastFm: api_name = "Last.fm"; break;
case ApiType::MusicBrainz: api_name = "MusicBrainz"; break;
case ApiType::Discogs: api_name = "Discogs"; break;
}
if (result.success) {
// Cache the result if cache_key is not empty (empty means internet stream) and disk cache is enabled
if (cfg_enable_disk_cache && !cache_key.is_empty()) {
async_io_manager::instance().cache_set_async(cache_key, result.data);
}
callback(result);
} else {
console::printf("foo_artwork: API FAILED - %s failed for '%s - %s' (error: %s)",
api_name.c_str(), artist.c_str(), track.c_str(), result.error_message.c_str());
// This API failed, try the next one
search_apis_by_priority(artist, track, cache_key, callback, api_order, index + 1);
}
};
// Call the appropriate API search function
switch (current_api) {
case ApiType::iTunes:
search_itunes_api_async(artist, track, api_callback);
break;
case ApiType::Deezer:
search_deezer_api_async(artist, track, api_callback);
break;
case ApiType::LastFm:
search_lastfm_api_async(artist, track, api_callback);
break;
case ApiType::MusicBrainz:
search_musicbrainz_api_async(artist, track, api_callback);
break;
case ApiType::Discogs:
search_discogs_api_async(artist, track, api_callback);
break;
}
}
void artwork_manager::find_local_artwork_async(metadb_handle_ptr track, artwork_callback callback) {
// Use album_art_manager_v2 from SDK exclusively - no custom logic
async_io_manager::instance().submit_task([track, callback]() {
artwork_result result;
result.success = false;
try {
if (!track.is_valid()) {
result.error_message = "Invalid metadb handle";
async_io_manager::instance().post_to_main_thread([callback, result]() {
callback(result);
});
return;
}
// Try multiple artwork IDs in priority order to find any available tagged artwork
const GUID artwork_ids[] = {
album_art_ids::cover_front, // Front cover (most common)
album_art_ids::disc, // Disc/media artwork
album_art_ids::artist, // Artist image
album_art_ids::icon, // Icon artwork
album_art_ids::cover_back // Back cover (least preferred)
};
const char* artwork_names[] = {
"Front Cover",
"Disc/Media",
"Artist Image",
"Icon",
"Back Cover"
};
static_api_ptr_t<album_art_manager_v2> aam;
// Try each artwork ID until we find one
for (int i = 0; i < 5; i++) {
try {
auto extractor = aam->open(pfc::list_single_ref_t<metadb_handle_ptr>(track),
pfc::list_single_ref_t<GUID>(artwork_ids[i]),
fb2k::noAbort);
auto art_data = extractor->query(artwork_ids[i], fb2k::noAbort);
if (art_data.is_valid() && art_data->get_size() > 0) {
result.data.set_size(art_data->get_size());
memcpy(result.data.get_ptr(), art_data->get_ptr(), art_data->get_size());
result.mime_type = detect_mime_type(result.data.get_ptr(), result.data.get_size());
// Check if the tagged artwork format is supported
if (is_supported_image_format(result.mime_type)) {
result.success = true;
result.source = "Local artwork";
async_io_manager::instance().post_to_main_thread([callback, result]() {
callback(result);
});
return;
} else {
// Tagged artwork format not supported, continue checking other artwork types
continue;
}
}
} catch (...) {
// Continue to next artwork ID if this one fails
continue;
}
}
} catch (const std::exception& e) {
result.error_message = "SDK artwork search exception";
} catch (...) {
result.error_message = "SDK artwork search failed with unknown exception";
}
// No artwork found via SDK
result.error_message = "No artwork found via SDK";
async_io_manager::instance().post_to_main_thread([callback, result]() {
callback(result);
});
});
}
void artwork_manager::search_itunes_api_async(const char* artist, const char* track, artwork_callback callback) {
// iTunes Search API doesn't require an API key
// First try searching for the track as a song
pfc::string8 url = "https://itunes.apple.com/search?term=";
url << url_encode(artist) << "+" << url_encode(track);
url << "&entity=song&limit=5"; // Increased limit for better matches
// Copy parameters to avoid lambda capture corruption
pfc::string8 artist_str = artist;
pfc::string8 track_str = track;
// Make async HTTP request
async_io_manager::instance().http_get_async(url, [callback, artist_str, track_str](bool success, const pfc::string8& response, const pfc::string8& error) {
if (!success) {
artwork_result result;
result.success = false;
result.error_message = "iTunes API request failed: ";
result.error_message << error;
callback(result);
return;
}
// Parse JSON response to extract artwork URL
pfc::string8 artwork_url;
if (!parse_itunes_json(artist_str, track_str, response, artwork_url)) {
artwork_result result;
result.success = false;
result.error_message = "No artwork found in itunes response";
callback(result);
return;
}
// Download the artwork image
async_io_manager::instance().http_get_binary_async(artwork_url, [callback, artwork_url](bool success, const pfc::array_t<t_uint8>& data, const pfc::string8& error) {
artwork_result result;
if (success && data.get_size() > 0) {
result.success = true;
result.data = data;
result.mime_type = detect_mime_type(data.get_ptr(), data.get_size());
result.source = "iTunes"; // Set source for OSD display
} else {
result.success = false;
result.error_message = "Failed to download iTunes artwork: ";
result.error_message << error;
}
callback(result);
});
});
}
void artwork_manager::search_discogs_api_async(const char* artist, const char* track, artwork_callback callback) {
// Check if we have either a personal token OR consumer key+secret
bool has_token = !cfg_discogs_key.is_empty();
bool has_consumer_creds = !cfg_discogs_consumer_key.is_empty() && !cfg_discogs_consumer_secret.is_empty();
if (!has_token && !has_consumer_creds) {
async_io_manager::instance().post_to_main_thread([callback]() {
artwork_result result;
result.success = false;
result.error_message = "Discogs API authentication not configured";
callback(result);
});
return;
}
// Build Discogs API URL - search for artist + track (not album)
pfc::string8 search_query = artist;
search_query << " " << track;
pfc::string8 url = "https://api.discogs.com/database/search?q=";
url << url_encode(search_query);
url << "&type=release";
// Add authentication - prefer personal token over consumer credentials
if (has_token) {
url << "&token=" << url_encode(cfg_discogs_key.get_ptr());
} else {
url << "&key=" << url_encode(cfg_discogs_consumer_key.get_ptr());
url << "&secret=" << url_encode(cfg_discogs_consumer_secret.get_ptr());
}
// Copy parameters to avoid lambda capture issues
pfc::string8 artist_str = artist;
pfc::string8 track_str = track;
// Make async HTTP request
async_io_manager::instance().http_get_async(url, [callback, artist_str, track_str](bool success, const pfc::string8& response, const pfc::string8& error) {
if (!success) {
artwork_result result;
result.success = false;
result.error_message = "Discogs API request failed: ";
result.error_message << error;
callback(result);
return;
}
// Parse JSON response to extract artwork URL
pfc::string8 artwork_url;
if (!parse_discogs_json(artist_str, track_str, response, artwork_url)) {
artwork_result result;
result.success = false;
result.error_message = "No artwork found in Discogs response";
callback(result);
return;
}
// Download the artwork image
async_io_manager::instance().http_get_binary_async(artwork_url, [callback, artwork_url](bool success, const pfc::array_t<t_uint8>& data, const pfc::string8& error) {
artwork_result result;
if (success && data.get_size() > 0) {
result.success = true;
result.data = data;
result.mime_type = detect_mime_type(data.get_ptr(), data.get_size());
result.source = "Discogs"; // Set source for OSD display
} else {
result.success = false;
result.error_message = "Failed to download Discogs artwork: ";
result.error_message << error;
}
callback(result);
});
});
}
void artwork_manager::search_lastfm_api_async(const char* artist, const char* title, artwork_callback callback) {
if (cfg_lastfm_key.is_empty()) {
async_io_manager::instance().post_to_main_thread([callback]() {
artwork_result result;
result.success = false;
result.error_message = "Last.fm API key not configured";
callback(result);
});
return;
}
// Build Last.fm API URL
pfc::string8 url = "http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=";
url << url_encode(cfg_lastfm_key.get_ptr());
url << "&artist=" << url_encode(artist);
url << "&track=" << url_encode(title);
url << "&autocorrect=1&format=json";
// Make async HTTP request
async_io_manager::instance().http_get_async(url, [callback](bool success, const pfc::string8& response, const pfc::string8& error) {
if (!success) {
artwork_result result;
result.success = false;
result.error_message = "Last.fm API request failed: ";
result.error_message << error;
callback(result);
return;
}
// Parse JSON response to extract artwork URL
pfc::string8 artwork_url;
if (!parse_lastfm_json(response, artwork_url)) {
artwork_result result;
result.success = false;
result.error_message = "No artwork found in Last.fm response";
callback(result);
return;
}
// Download the artwork image
async_io_manager::instance().http_get_binary_async(artwork_url, [callback](bool success, const pfc::array_t<t_uint8>& data, const pfc::string8& error) {
artwork_result result;
if (success && data.get_size() > 0) {
result.success = true;
result.data = data;
result.mime_type = detect_mime_type(data.get_ptr(), data.get_size());
result.source = "Last.fm"; // Set source for OSD display
} else {
result.success = false;
result.error_message = "Failed to download Last.fm artwork: ";
result.error_message << error;
}
callback(result);
});
});
}
void artwork_manager::perform_deezer_fallback_search(const char* artist, const char* track, artwork_callback callback) {
// Copy parameters to ensure they remain valid throughout async operations
pfc::string8 artist_copy = artist ? artist : "";
pfc::string8 track_copy = track ? track : "";
pfc::string8 search_query;
pfc::string8 search_artist = "artist:\"";
// Build search query: "artist"
search_query += search_artist;
search_query += artist;
search_query += "\"";
// Strategy 1: Try artist only
if (!artist_copy.is_empty()) {
pfc::string8 artist_only_url = "https://api.deezer.com/search?q=";
artist_only_url << artwork_manager::url_encode(search_query) << "&limit=5";
async_io_manager::instance().http_get_async(artist_only_url, [artist_copy, track_copy, callback](bool success, const pfc::string8& response, const pfc::string8& error) {
if (success) {
pfc::string8 artwork_url;
if (artwork_manager::parse_deezer_json(artist_copy, track_copy, response, artwork_url)) {
// Download artwork
async_io_manager::instance().http_get_binary_async(artwork_url, [callback](bool dl_success, const pfc::array_t<t_uint8>& data, const pfc::string8& dl_error) {
artwork_result result;
if (dl_success && data.get_size() > 0) {
result.success = true;
result.data = data;
result.mime_type = artwork_manager::detect_mime_type(data.get_ptr(), data.get_size());
result.source = "Deezer";
} else {
result.success = false;
result.error_message = "Failed to download Deezer artwork";
}
callback(result);
});
return;
}
}
// Skip track-only search as requested - only use artist fallback
artwork_result final_result;
final_result.success = false;
final_result.error_message = "No artwork found in Deezer (artist search failed)";
callback(final_result);
});
} else {
// No artist available - skip track-only search as requested
artwork_result result;
result.success = false;
result.error_message = "No artist available for Deezer search";
callback(result);
}
}
void artwork_manager::search_deezer_api_async(const char* artist, const char* track, artwork_callback callback) {
// Deezer API doesn't require authentication
pfc::string8 search_query;
pfc::string8 search_track = "track:\"";
pfc::string8 search_artist = "artist:\"";
// Build search query: "track"
// NOTE: Metadata cleaner (is valid for search) rule 1 stops it from being used
if (!artist || strlen(artist) == 0) {
search_query += search_track;
search_query += track;
search_query += "\"";
} else {
// Build search query: "artist track"
search_query += search_artist;
search_query += artist;
search_query += "\"";
search_query += " ";
search_query += search_track;
search_query += track;
search_query += "\"";
}
pfc::string8 url = "https://api.deezer.com/search?q=";
url << url_encode(search_query) << "&limit=10";
// Copy parameters to avoid lambda capture corruption
pfc::string8 artist_str = artist;
pfc::string8 track_str = track;
// Make async HTTP request
try {
async_io_manager::instance().http_get_async(url, [artist_str, track_str, callback](bool success, const pfc::string8& response, const pfc::string8& error) {
if (!success) {
artwork_result result;
result.success = false;
result.error_message = "Deezer API request failed: ";
result.error_message << error;
callback(result);
return;
}
// Parse JSON response to extract artwork URL
pfc::string8 artwork_url;
if (!artwork_manager::parse_deezer_json(artist_str, track_str, response, artwork_url)) {
// Try fallback search strategies
artwork_manager::perform_deezer_fallback_search(artist_str, track_str, callback);
return;
}
// Download the artwork image
async_io_manager::instance().http_get_binary_async(artwork_url, [callback](bool success, const pfc::array_t<t_uint8>& data, const pfc::string8& error) {
artwork_result result;
if (success && data.get_size() > 0) {
result.success = true;
result.data = data;
result.mime_type = artwork_manager::detect_mime_type(data.get_ptr(), data.get_size());
result.source = "Deezer"; // Set source for OSD display
} else {
result.success = false;
result.error_message = "Failed to download Deezer artwork: ";
result.error_message << error;
}
callback(result);
});
});
} catch (const std::exception& e) {
artwork_result result;
result.success = false;
result.error_message = "Exception in Deezer HTTP request: ";
result.error_message += e.what();
callback(result);
} catch (...) {
artwork_result result;
result.success = false;
result.error_message = "Unknown exception in Deezer HTTP request";
callback(result);
}
}
void artwork_manager::download_image_async(const char* url, artwork_callback callback) {
// This would be called by API implementations after parsing JSON responses
// For now, placeholder implementation
async_io_manager::instance().post_to_main_thread([callback]() {
artwork_result result;
result.success = false;
result.error_message = "Image download not implemented";
callback(result);
});
}
void artwork_manager::validate_and_complete_result(const pfc::array_t<t_uint8>& data, artwork_callback callback) {
if (data.get_size() == 0) {
artwork_result result;
result.success = false;
result.error_message = "Empty data";
async_io_manager::instance().post_to_main_thread([callback, result]() {
callback(result);
});
return;
}
if (!is_valid_image_data(data.get_ptr(), data.get_size())) {
artwork_result result;
result.success = false;
result.error_message = "Invalid image data";
async_io_manager::instance().post_to_main_thread([callback, result]() {
callback(result);
});
return;
}
artwork_result result;
result.data = data;
result.mime_type = detect_mime_type(data.get_ptr(), data.get_size());
result.success = true;
result.source = "Cache"; // Set source for cached artwork
async_io_manager::instance().post_to_main_thread([callback, result]() {
callback(result);
});
}
bool artwork_manager::is_valid_image_data(const t_uint8* data, size_t size) {
if (size < 4) return false;
// Check for common image format signatures
// JPEG
if (data[0] == 0xFF && data[1] == 0xD8) return true;
// PNG
if (data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') return true;
// GIF
if (size >= 6 && memcmp(data, "GIF87a", 6) == 0) return true;
if (size >= 6 && memcmp(data, "GIF89a", 6) == 0) return true;
// BMP
if (data[0] == 'B' && data[1] == 'M') return true;