-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsdk_main.cpp
More file actions
8149 lines (6760 loc) · 325 KB
/
Copy pathsdk_main.cpp
File metadata and controls
8149 lines (6760 loc) · 325 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 "metadata_cleaner.h"
#include "preferences.h"
#include "webp_decoder.h"
#include <algorithm>
#include <thread>
#include <vector>
#include <mutex>
#include <regex>
#include <shlobj.h>
// CUI support is now defined in stdafx.h
static class debug_init {
public:
debug_init() {
#ifdef _DEBUG
#ifdef COLUMNS_UI_AVAILABLE
#else
#endif
#endif
}
} g_debug_init;
#ifdef COLUMNS_UI_AVAILABLE
#pragma message("Compiling with Columns UI support")
// CUI panel will register itself via static initialization in artwork_panel_cui.cpp
#include "artwork_panel_cui.h"
static class cui_debug_init {
public:
cui_debug_init() {
#ifdef _DEBUG
#endif
}
} g_cui_debug;
#else
#pragma message("Columns UI support NOT available")
#endif
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
// Configuration variable GUIDs
static constexpr GUID guid_cfg_enable_itunes = { 0x12345678, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
static constexpr GUID guid_cfg_enable_discogs = { 0x12345679, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf1 } };
static constexpr GUID guid_cfg_enable_lastfm = { 0x1234567a, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf2 } };
static constexpr GUID guid_cfg_enable_deezer = { 0x1234567b, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf3 } };
static constexpr GUID guid_cfg_enable_musicbrainz = { 0x12345681, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf9 } };
static constexpr GUID guid_cfg_discogs_key = { 0x1234567c, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf4 } };
static constexpr GUID guid_cfg_discogs_consumer_key = { 0x1234567e, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf6 } };
static constexpr GUID guid_cfg_discogs_consumer_secret = { 0x1234567f, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf7 } };
static constexpr GUID guid_cfg_lastfm_key = { 0x1234567d, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf5 } };
static constexpr GUID guid_cfg_fill_mode = { 0x12345680, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf8 } };
static constexpr GUID guid_cfg_priority_1 = { 0x12345682, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfa } };
static constexpr GUID guid_cfg_priority_2 = { 0x12345683, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfb } };
static constexpr GUID guid_cfg_priority_3 = { 0x12345684, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfc } };
static constexpr GUID guid_cfg_priority_4 = { 0x12345685, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfd } };
static constexpr GUID guid_cfg_priority_5 = { 0x12345686, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfe } };
static constexpr GUID guid_cfg_show_osd = { 0x12345688, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf8 } };
static constexpr GUID guid_cfg_enable_custom_logos = { 0x12345689, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf9 } };
static constexpr GUID guid_cfg_logos_folder = { 0x1234568a, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfa } };
static constexpr GUID guid_cfg_clear_panel_when_not_playing = { 0x1234568b, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfb } };
static constexpr GUID guid_cfg_use_noart_image = { 0x1234568c, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfc } };
static constexpr GUID guid_cfg_infobar = { 0x59b0b41b, 0x2d12, 0x4965, { 0xaa, 0x4a, 0xb5, 0x80, 0x5, 0x55, 0x2e, 0xf7 } };
static constexpr GUID guid_cfg_http_timeout = { 0x1234568d, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfd } };
static constexpr GUID guid_cfg_retry_count = { 0x1234568e, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xfe } };
static constexpr GUID guid_cfg_enable_disk_cache = { 0x1234568f, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xff } };
static constexpr GUID guid_cfg_cache_folder = { 0x12345691, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xdf, 0x00 } };
static constexpr GUID guid_cfg_skip_local_artwork = { 0x12345692, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xdf, 0x01 } };
static constexpr GUID guid_cfg_single_file_cache = { 0x12345693, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xdf, 0x02 } };
// Configuration variables with default values
cfg_bool cfg_enable_itunes(guid_cfg_enable_itunes, false);
cfg_bool cfg_enable_discogs(guid_cfg_enable_discogs, false);
cfg_bool cfg_enable_lastfm(guid_cfg_enable_lastfm, false);
cfg_bool cfg_enable_deezer(guid_cfg_enable_deezer, true);
cfg_bool cfg_enable_musicbrainz(guid_cfg_enable_musicbrainz, false);
cfg_string cfg_discogs_key(guid_cfg_discogs_key, "");
cfg_string cfg_discogs_consumer_key(guid_cfg_discogs_consumer_key, "");
cfg_string cfg_discogs_consumer_secret(guid_cfg_discogs_consumer_secret, "");
cfg_string cfg_lastfm_key(guid_cfg_lastfm_key, "");
cfg_bool cfg_fill_mode(guid_cfg_fill_mode, false); // true = fill window (crop), false = fit window (letterbox)
// API Priority order (0=iTunes, 1=Deezer, 2=Last.fm, 3=MusicBrainz, 4=Discogs)
// Default order: Deezer > iTunes > Last.fm > MusicBrainz > Discogs
// NEW SIMPLE PRIORITY SYSTEM
// Each variable represents a search position (1st, 2nd, 3rd, etc.)
// Values: 0=iTunes, 1=Deezer, 2=Last.fm, 3=MusicBrainz, 4=Discogs
cfg_int cfg_search_order_1(guid_cfg_priority_1, 1); // 1st choice: Deezer (default)
cfg_int cfg_search_order_2(guid_cfg_priority_2, 0); // 2nd choice: iTunes (default)
cfg_int cfg_search_order_3(guid_cfg_priority_3, 2); // 3rd choice: Last.fm (default)
cfg_int cfg_search_order_4(guid_cfg_priority_4, 3); // 4th choice: MusicBrainz (default)
cfg_int cfg_search_order_5(guid_cfg_priority_5, 4); // 5th choice: Discogs (default)
// OSD display setting (default enabled)
cfg_bool cfg_show_osd(guid_cfg_show_osd, true);
// Custom Station Logos settings
cfg_bool cfg_enable_custom_logos(guid_cfg_enable_custom_logos, true); // Enable custom station logos (default enabled)
cfg_string cfg_logos_folder(guid_cfg_logos_folder, ""); // Custom logos folder path (empty = use default)
// Miscellaneous settings
cfg_bool cfg_clear_panel_when_not_playing(guid_cfg_clear_panel_when_not_playing, false); // Clear panel when not playing (default disabled)
cfg_bool cfg_use_noart_image(guid_cfg_use_noart_image, false); // Use noart image when clearing panel (default disabled)
cfg_bool cfg_infobar(guid_cfg_infobar, false); // DUI infobar (default disabled)
// Network settings
cfg_int cfg_http_timeout(guid_cfg_http_timeout, 15); // HTTP timeout in seconds (default 15)
cfg_int cfg_retry_count(guid_cfg_retry_count, 2); // Number of retries for failed requests (default 2)
// Disk cache setting
cfg_bool cfg_enable_disk_cache(guid_cfg_enable_disk_cache, true); // Enable disk caching (default enabled)
cfg_string cfg_cache_folder(guid_cfg_cache_folder, ""); // Custom cache folder path (empty = use default)
// Skip local artwork setting
cfg_bool cfg_skip_local_artwork(guid_cfg_skip_local_artwork, false); // Always skip local artwork (default disabled)
// Single file cache mode - only keep current track's artwork in cache folder
cfg_bool cfg_single_file_cache(guid_cfg_single_file_cache, false); // Single file cache mode (default disabled)
//=============================================================================
// Event-Driven Artwork System
//=============================================================================
// Artwork event types
enum class ArtworkEventType {
ARTWORK_LOADED, // New artwork loaded successfully
ARTWORK_LOADING, // Search started
ARTWORK_FAILED, // Search failed
ARTWORK_CLEARED // Artwork cleared
};
// Artwork event data
struct ArtworkEvent {
ArtworkEventType type;
HBITMAP bitmap;
std::string source;
std::string artist;
std::string title;
ArtworkEvent(ArtworkEventType t, HBITMAP bmp = nullptr, const std::string& src = "",
const std::string& art = "", const std::string& ttl = "")
: type(t), bitmap(bmp), source(src), artist(art), title(ttl) {}
};
// Artwork event listener interface
class IArtworkEventListener {
public:
virtual ~IArtworkEventListener() = default;
virtual void on_artwork_event(const ArtworkEvent& event) = 0;
};
// Artwork event manager (singleton)
class ArtworkEventManager {
private:
std::vector<IArtworkEventListener*> m_listeners;
std::mutex m_listeners_mutex;
static std::unique_ptr<ArtworkEventManager> s_instance;
public:
static ArtworkEventManager& get() {
if (!s_instance) {
s_instance = std::make_unique<ArtworkEventManager>();
}
return *s_instance;
}
void subscribe(IArtworkEventListener* listener) {
std::lock_guard<std::mutex> lock(m_listeners_mutex);
m_listeners.push_back(listener);
}
void unsubscribe(IArtworkEventListener* listener) {
std::lock_guard<std::mutex> lock(m_listeners_mutex);
m_listeners.erase(std::remove(m_listeners.begin(), m_listeners.end(), listener), m_listeners.end());
}
void notify(const ArtworkEvent& event) {
std::lock_guard<std::mutex> lock(m_listeners_mutex);
for (auto* listener : m_listeners) {
try {
listener->on_artwork_event(event);
} catch (...) {
// Continue notifying other listeners even if one fails
}
}
}
};
std::unique_ptr<ArtworkEventManager> ArtworkEventManager::s_instance;
//=============================================================================
// Per-Request HTTP Management System
//=============================================================================
// HTTP request manager for individual APIs
class HttpRequestManager {
private:
std::string m_api_name;
std::mutex m_request_mutex;
std::atomic<bool> m_request_active{false};
public:
HttpRequestManager(const std::string& api_name) : m_api_name(api_name) {}
// RAII lock for HTTP requests
class RequestLock {
private:
HttpRequestManager* m_manager;
std::unique_lock<std::mutex> m_lock;
bool m_acquired;
public:
RequestLock(HttpRequestManager* manager)
: m_manager(manager), m_lock(manager->m_request_mutex), m_acquired(true) {
manager->m_request_active = true;
}
~RequestLock() {
if (m_acquired && m_manager) {
m_manager->m_request_active = false;
}
}
bool is_acquired() const { return m_acquired; }
};
bool is_busy() const { return m_request_active.load(); }
RequestLock acquire_lock() {
return RequestLock(this);
}
};
// API-specific request managers
static HttpRequestManager g_itunes_request_manager("iTunes");
static HttpRequestManager g_deezer_request_manager("Deezer");
static HttpRequestManager g_lastfm_request_manager("Last.fm");
static HttpRequestManager g_musicbrainz_request_manager("MusicBrainz");
static HttpRequestManager g_discogs_request_manager("Discogs");
// Helper function to get request manager by API name
HttpRequestManager* get_request_manager_for_api(const std::string& api_name) {
if (api_name.find("iTunes") != std::string::npos) return &g_itunes_request_manager;
if (api_name.find("Deezer") != std::string::npos) return &g_deezer_request_manager;
if (api_name.find("Last.fm") != std::string::npos || api_name.find("lastfm") != std::string::npos) return &g_lastfm_request_manager;
if (api_name.find("MusicBrainz") != std::string::npos || api_name.find("musicbrainz") != std::string::npos) return &g_musicbrainz_request_manager;
if (api_name.find("Discogs") != std::string::npos) return &g_discogs_request_manager;
return &g_deezer_request_manager; // Default fallback
}
// Forward declarations
class artwork_ui_element;
// Global variables for CUI panel communication
std::wstring g_current_artwork_path;
bool g_artwork_loading = false;
HBITMAP g_shared_artwork_bitmap = NULL;
// Artwork source tracking
pfc::string8 g_current_artwork_source;
// Global reference to main UI element for artwork sharing
static artwork_ui_element* g_main_ui_element = nullptr;
// Component's DLL instance handle
HINSTANCE g_hIns = NULL;
// DLL entry point
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH: {
// Debug: Component loading notification
#ifdef _DEBUG
#ifdef _DEBUG
#endif
// Also try creating a file to verify this code runs
FILE* f = fopen("c:\\temp\\artwork_debug.txt", "a");
if (f) {
fprintf(f, "DLL loaded at %s\n", __TIMESTAMP__);
fclose(f);
}
#endif
g_hIns = hModule;
DisableThreadLibraryCalls(hModule);
break;
}
case DLL_PROCESS_DETACH:
#ifdef _DEBUG
#ifdef _DEBUG
#endif
#endif
break;
}
return TRUE;
}
// Component version declaration using the proper SDK macro
#ifdef COLUMNS_UI_AVAILABLE
DECLARE_COMPONENT_VERSION(
"Artwork Display",
"1.5.52",
"Cover artwork display component for foobar2000.\n"
"Features:\n"
"- Local artwork search (Cover.jpg, folder.jpg, etc.)\n"
"- Online API fallback (iTunes, Discogs, Last.fm)\n"
"- Smart metadata cleaning for better API results\n"
"- Configurable preferences\n"
"- Columns UI panel support\n"
"- On-screen display for artwork source\n\n"
"Author: jame25\n"
"Build date: " __DATE__ "\n\n"
"This component displays cover artwork for the currently playing track.\n"
"Includes Columns UI panel integration."
);
#else
DECLARE_COMPONENT_VERSION(
"Artwork Display",
"1.5.52",
"Cover artwork display component for foobar2000.\n"
"Features:\n"
"- Local artwork search (Cover.jpg, folder.jpg, etc.)\n"
"- Online API fallback (iTunes, Discogs, Last.fm)\n"
"- Smart metadata cleaning for better API results\n"
"- Configurable preferences\n"
"- On-screen display for artwork source\n\n"
"Author: jame25\n"
"Build date: " __DATE__ "\n\n"
"This component displays cover artwork for the currently playing track."
);
#endif
// Validate component compatibility using the proper SDK macro
VALIDATE_COMPONENT_FILENAME("foo_artwork.dll");
// Old artwork_manager class removed - now using async version from artwork_manager.h
// Global list to track artwork UI elements
static pfc::list_t<artwork_ui_element*> g_artwork_ui_elements;
// Note: g_current_artwork_source already declared above
// Helper to convert UTF-8 pfc::string8 to wide string for Unicode Windows APIs
static std::wstring utf8_to_wide(const pfc::string8& utf8_str) {
if (utf8_str.is_empty()) return L"";
int len = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, nullptr, 0);
if (len <= 0) return L"";
std::wstring result(len, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, &result[0], len);
// Remove null terminator from string length
if (!result.empty() && result.back() == L'\0') {
result.pop_back();
}
return result;
}
// Helper to check if file exists using Wide API for Unicode path support
static BOOL path_file_exists_utf8(const pfc::string8& utf8_path) {
std::wstring wide_path = utf8_to_wide(utf8_path);
return PathFileExistsW(wide_path.c_str());
}
// Function to create AppData directory structure for logos and cache
void create_appdata_directories() {
try {
// Get foobar2000 profile path (returns file:// URL)
pfc::string8 profile_url = core_api::get_profile_path();
// Convert file:// URL to native Windows path using SDK function
pfc::string8 profile_path;
if (!foobar2000_io::extract_native_path(profile_url.c_str(), profile_path)) {
// Fallback: manual conversion if SDK function fails
if (strstr(profile_url.c_str(), "file://") == profile_url.c_str()) {
const char* path_start = profile_url.c_str() + 7; // Skip "file://"
// Skip leading slash if present (file:///C:/... -> C:/...)
if (*path_start == '/') path_start++;
profile_path = path_start;
// Replace forward slashes with backslashes for Windows
for (size_t i = 0; i < profile_path.length(); i++) {
if (profile_path[i] == '/') {
profile_path.set_char(i, '\\');
}
}
} else {
profile_path = profile_url;
}
}
// Build directory paths
pfc::string8 artwork_data_dir = profile_path;
artwork_data_dir << "\\foo_artwork_data\\";
pfc::string8 logos_dir = artwork_data_dir;
logos_dir << "logos\\";
pfc::string8 cache_dir = artwork_data_dir;
cache_dir << "_cache\\";
// Create directories (use Wide API for Unicode path support)
std::wstring wide_artwork_dir = utf8_to_wide(artwork_data_dir);
std::wstring wide_logos_dir = utf8_to_wide(logos_dir);
std::wstring wide_cache_dir = utf8_to_wide(cache_dir);
SHCreateDirectoryExW(NULL, wide_artwork_dir.c_str(), NULL);
SHCreateDirectoryExW(NULL, wide_logos_dir.c_str(), NULL);
SHCreateDirectoryExW(NULL, wide_cache_dir.c_str(), NULL);
} catch (...) {
// Silently ignore errors - directories may already exist
}
}
// Function to extract domain from stream URL for logo matching
pfc::string8 extract_domain_from_stream_url(metadb_handle_ptr track) {
// CRASH FIX: Add comprehensive safety checks
try {
if (!track.is_valid()) return "";
pfc::string8 path = track->get_path();
// Safety: Check path length to prevent buffer overruns
if (path.is_empty() || path.length() > 2048) return "";
// Check if it's an internet stream
if (!(strstr(path.c_str(), "://") && !strstr(path.c_str(), "file://"))) {
return "";
}
// Extract domain from URL (e.g., "http://somafm.com/stream" -> "somafm.com")
const char* start = strstr(path.c_str(), "://");
if (!start) return "";
start += 3; // Skip "://"
// Safety: Ensure we don't go past end of string
if (start >= path.c_str() + path.length()) return "";
const char* end = strchr(start, '/');
if (!end) end = start + strlen(start);
const char* port = strchr(start, ':');
if (port && port < end) end = port;
// Safety: Validate domain length
if (end > start && (end - start) > 0 && (end - start) < 256) {
return pfc::string8(start, end - start);
}
return "";
} catch (...) {
// Any exception in domain extraction should not crash the player
return "";
}
}
// Function to extract full host+path from stream URL for specific logo matching
// e.g., "https://ice1.somafm.com/indiepop-128-aac" -> "https---ice1.somafm.com-indiepop-128-aac"
pfc::string8 extract_full_path_from_stream_url(metadb_handle_ptr track) {
if (!track.is_valid()) return "";
pfc::string8 path = track->get_path();
// Check mtag file internet streams
const double length = track->get_length();
if (strstr(path.c_str(), "://")) {
// Has protocol - check if it's a local file protocol and is mtag without duration
if ((strstr(path.c_str(), "file://") == path.c_str()) && (!strstr(path.c_str(), ".tags")) && (!length <= 0)) {
return "";
}
// Any other protocol (http://, https://, etc.) = internet stream - continue processing
} else {
// No protocol - check length as fallback for other stream types
double length = track->get_length();
if (length > 0) {
return ""; // Has length but no protocol = local file
}
}
// Replace illegal characters for filename compatibility
//$replace(%path%,/,-,\-,|,-,:,-,*,x,",'',<,_,>_,?,_)
//$replace(%path%,$char(47),$char(45),$char(92),$char(45),$char(448),$char(45),$char(58),$char(45),$char(42),$char(140),$char(34),$char(39)$char(39),$char(60),$char(95),$char(62),$char(95),$char(63),$char(95))
//Usable also with other artwork readers defining in artwork sources eg C:\Users\xxx\foobar2000\profile\foo_artwork_data\logos\$replace(%path%,$char(47),$char(45),$char(92),$char(45),$char(448),$char(45),$char(58),$char(45),$char(42),$char(140),$char(34),$char(39)$char(39),$char(60),$char(95),$char(62),$char(95),$char(63),$char(95)).*
pfc::string8 result = path;
for (size_t i = 0; i < result.length(); i++) {
if (result[i] == '/') {result.set_char(i, '-');}
else if (result[i] == '\\') {result.set_char(i, '-');}
else if (result[i] == '|') {result.set_char(i, '-');}
else if (result[i] == ':') {result.set_char(i, '-');}
else if (result[i] == '*') {result.set_char(i, 'x');}
else if (result[i] == '"') { result.set_char(i, '\'\''); }
else if (result[i] == '<') { result.set_char(i, '_'); }
else if (result[i] == '>') { result.set_char(i, '_'); }
else if (result[i] == '?') { result.set_char(i, '_'); }
}
return result;
}
// Function to extract station name from metadata for logo matching
pfc::string8 extract_station_name_from_metadata(metadb_handle_ptr track) {
if (!track.is_valid()) return "";
// Get metadata
file_info_impl info;
if (!track->get_info(info)) return "";
// Get artist and title
const char* artist = info.meta_get("ARTIST", 0);
const char* title = info.meta_get("TITLE", 0);
// If no artist (empty or just "?") but we have a title, assume title contains station name
if ((!artist || strlen(artist) == 0 || strcmp(artist, "?") == 0) && title && strlen(title) > 0) {
// Look for pattern "? - StationName" or just "StationName"
const char* dash = strstr(title, " - ");
if (dash) {
// Skip "? - " and return the station name part
return pfc::string8(dash + 3);
} else {
// No dash, assume the whole title is the station name
return pfc::string8(title);
}
}
return "";
}
// CRASH FIX: Helper function to safely create GDI+ bitmap from file
HBITMAP safe_load_gdiplus_bitmap(const std::wstring& wide_path) {
Gdiplus::Bitmap* bitmap = nullptr;
try {
// First check if file is accessible and has reasonable size
HANDLE hFile = CreateFileW(wide_path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
LARGE_INTEGER fileSize;
if (GetFileSizeEx(hFile, &fileSize)) {
// Reject files that are too large (>50MB) or too small (<100 bytes) to prevent memory issues
if (fileSize.QuadPart > 100 && fileSize.QuadPart < 50*1024*1024) {
CloseHandle(hFile);
// Now safely create bitmap
bitmap = new Gdiplus::Bitmap(wide_path.c_str());
if (bitmap) {
Gdiplus::Status last_status = bitmap->GetLastStatus();
if (last_status == Gdiplus::Ok) {
// Additional validation - check bitmap dimensions
UINT width = bitmap->GetWidth();
UINT height = bitmap->GetHeight();
if (width > 0 && height > 0 && width <= 4096 && height <= 4096) {
// Debug: Check GDI+ bitmap pixel format before conversion
Gdiplus::PixelFormat format = bitmap->GetPixelFormat();
HBITMAP gdi_bitmap = nullptr;
// Use alpha-preserving method for 32-bit ARGB images
if (format == PixelFormat32bppARGB) {
// Create DIB section that preserves alpha channel
HDC screen_dc = GetDC(NULL);
if (screen_dc) {
BITMAPINFO bmi = {};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -(LONG)height; // Top-down DIB
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
void* pixel_data = nullptr;
gdi_bitmap = CreateDIBSection(screen_dc, &bmi, DIB_RGB_COLORS, &pixel_data, NULL, 0);
if (gdi_bitmap && pixel_data) {
// Lock bitmap bits and copy with alpha preservation
Gdiplus::Rect rect(0, 0, width, height);
Gdiplus::BitmapData bitmapData;
if (bitmap->LockBits(&rect, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, &bitmapData) == Gdiplus::Ok) {
// Calculate stride for DIB section
int stride = ((width * 32 + 31) / 32) * 4;
// Copy pixel data row by row to preserve alpha
BYTE* src = (BYTE*)bitmapData.Scan0;
BYTE* dst = (BYTE*)pixel_data;
for (UINT y = 0; y < height; y++) {
memcpy(dst + y * stride, src + y * bitmapData.Stride, width * 4);
}
bitmap->UnlockBits(&bitmapData);
} else {
DeleteObject(gdi_bitmap);
gdi_bitmap = nullptr;
}
}
ReleaseDC(NULL, screen_dc);
}
} else {
// Use standard method for non-alpha images
Gdiplus::Status status = bitmap->GetHBITMAP(NULL, &gdi_bitmap);
if (status != Gdiplus::Ok) {
gdi_bitmap = nullptr;
}
}
if (gdi_bitmap) {
// Debug: Check resulting HBITMAP
BITMAP bm;
GetObject(gdi_bitmap, sizeof(BITMAP), &bm);
delete bitmap;
return gdi_bitmap;
}
}
}
}
} else {
CloseHandle(hFile);
}
} else {
CloseHandle(hFile);
}
}
} catch (...) {
// Handle any GDI+ or file system exceptions
}
// Always clean up bitmap pointer on failure
if (bitmap) {
delete bitmap;
bitmap = nullptr;
}
return NULL;
}
// Helper function to try loading a logo with a specific identifier
HBITMAP try_load_station_logo(const pfc::string8& identifier, const pfc::string8& logos_dir) {
if (identifier.is_empty()) return NULL;
// Simple safe version without __try (to avoid object unwinding issues)
try {
// Try common image extensions
const char* extensions[] = { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
for (const char* ext : extensions) {
pfc::string8 logo_path = logos_dir + identifier + ext;
// Additional safety check for path length
if (logo_path.length() > MAX_PATH - 1) {
continue; // Skip if path is too long
}
if (path_file_exists_utf8(logo_path.get_ptr())) {
// Use Win32 API to load image instead of GDI+ to avoid crashes
std::wstring wide_path;
wide_path.resize(logo_path.length() + 1);
int result = MultiByteToWideChar(CP_UTF8, 0, logo_path.c_str(), -1, &wide_path[0], (int)wide_path.size());
if (result == 0) {
continue; // Skip if conversion failed
}
// For BMP files, try Win32 LoadImage first (safest)
if (_stricmp(ext, ".bmp") == 0) {
HBITMAP hBitmap = (HBITMAP)LoadImageW(
NULL,
wide_path.c_str(),
IMAGE_BITMAP,
0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION
);
if (hBitmap) {
return hBitmap;
}
}
// CRASH FIX: Use safe helper function for GDI+ bitmap loading
HBITMAP gdi_bitmap = safe_load_gdiplus_bitmap(wide_path);
if (gdi_bitmap) {
return gdi_bitmap;
}
}
}
} catch (...) {
// Handle any top-level exceptions
}
return NULL;
}
// Function to load station logo with full path fallback to domain-only
HBITMAP load_station_logo(metadb_handle_ptr track) {
if (!track.is_valid()) return NULL;
// Check if custom station logos are enabled
if (!cfg_enable_custom_logos) {
return NULL;
}
try {
pfc::string8 logos_dir;
char appdata_buffer[MAX_PATH];
HRESULT hr = E_FAIL; // Initialize to prevent compiler warning
// Use custom folder path if specified, otherwise use default
if (!cfg_logos_folder.is_empty()) {
logos_dir = cfg_logos_folder.get_ptr();
// Ensure path ends with backslash
if (!logos_dir.is_empty() && logos_dir[logos_dir.length() - 1] != '\\') {
logos_dir += "\\";
}
} else {
// CRASH FIX: Try APPDATA path first (safe in DUI), fall back to profile path if it fails (CUI compatibility)
try {
hr = SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdata_buffer);
if (SUCCEEDED(hr)) {
logos_dir = pfc::string8(appdata_buffer) + "\\foobar2000-v2\\foo_artwork_data\\logos\\";
} else {
throw std::exception(); // Force fallback to profile path
}
} catch (...) {
// Fallback to profile path (CUI-safe)
try {
pfc::string8 profile_url = core_api::get_profile_path();
pfc::string8 profile_path;
if (strstr(profile_url.c_str(), "file://") == profile_url.c_str()) {
profile_path = profile_url.c_str() + 7;
for (size_t i = 0; i < profile_path.length(); i++) {
if (profile_path[i] == '/') {
profile_path.set_char(i, '\\');
}
}
} else {
profile_path = profile_url;
}
logos_dir = profile_path + "\\foo_artwork_data\\logos\\";
} catch (...) {
// Ultimate fallback: use relative path
logos_dir = "foo_artwork_data\\logos\\";
}
}
}
// Try 1: Full host+path matching (most specific)
pfc::string8 full_path = extract_full_path_from_stream_url(track);
if (!full_path.is_empty()) {
HBITMAP result = try_load_station_logo(full_path, logos_dir);
if (result) return result;
}
// Try 2: Domain-only matching (fallback for backward compatibility)
pfc::string8 domain = extract_domain_from_stream_url(track);
if (!domain.is_empty()) {
HBITMAP result = try_load_station_logo(domain, logos_dir);
if (result) return result;
// Additional check: Try relative path "foo_artwork_data\logos\" in case user put it there
pfc::string8 relative_logos_dir = "foo_artwork_data\\logos\\";
result = try_load_station_logo(domain, relative_logos_dir);
if (result) return result;
}
} catch (...) {
// Silently fail - this is just a fallback feature
}
return NULL;
}
// New function to load station logo directly as GDI+ bitmap (preserves alpha)
Gdiplus::Bitmap* try_load_station_logo_gdiplus(const pfc::string8& identifier, const pfc::string8& logos_dir) {
if (identifier.is_empty()) return nullptr;
try {
// Try PNG first (most likely to have alpha)
pfc::string8 png_path = logos_dir + identifier + ".png";
if (path_file_exists_utf8(png_path.get_ptr())) {
// Convert to wide string for GDI+
std::wstring wide_path;
wide_path.resize(png_path.length() + 1);
int result = MultiByteToWideChar(CP_UTF8, 0, png_path.c_str(), -1, &wide_path[0], (int)wide_path.size());
if (result > 0) {
// Load directly with GDI+ to preserve alpha
Gdiplus::Bitmap* bitmap = new Gdiplus::Bitmap(wide_path.c_str());
if (bitmap && bitmap->GetLastStatus() == Gdiplus::Ok) {
return bitmap;
} else {
delete bitmap;
}
}
}
// Try other formats (fallback)
const char* extensions[] = { ".jpg", ".jpeg", ".gif", ".bmp" };
for (const char* ext : extensions) {
pfc::string8 logo_path = logos_dir + identifier + ext;
if (path_file_exists_utf8(logo_path.get_ptr())) {
// Convert to wide string
std::wstring wide_path;
wide_path.resize(logo_path.length() + 1);
int result = MultiByteToWideChar(CP_UTF8, 0, logo_path.c_str(), -1, &wide_path[0], (int)wide_path.size());
if (result > 0) {
Gdiplus::Bitmap* bitmap = new Gdiplus::Bitmap(wide_path.c_str());
if (bitmap && bitmap->GetLastStatus() == Gdiplus::Ok) {
return bitmap;
} else {
delete bitmap;
}
}
}
}
} catch (...) {
// Silently handle exceptions
}
return nullptr;
}
// Function to load station logo directly as GDI+ bitmap (preserves alpha)
Gdiplus::Bitmap* load_station_logo_gdiplus(metadb_handle_ptr track) {
// Check if custom station logos are enabled
if (!cfg_enable_custom_logos) {
return nullptr;
}
if (!track.is_valid()) return nullptr;
// Get the directory path (using same logic as existing functions)
pfc::string8 profile_url = core_api::get_profile_path();
pfc::string8 profile_path;
if (profile_url.startsWith("file://")) {
profile_path = profile_url.c_str() + 7; // Skip "file://"
for (size_t i = 0; i < profile_path.length(); i++) {
if (profile_path[i] == '/') {
profile_path.set_char(i, '\\');
}
}
} else {
profile_path = profile_url;
}
pfc::string8 logos_dir = profile_path + "\\foo_artwork_data\\logos\\";
try {
// Get stream URL or path
const char* url = track->get_path();
if (!url || strlen(url) == 0) return nullptr;
// Extract domain and full path using existing functions
pfc::string8 full_path = extract_full_path_from_stream_url(track);
pfc::string8 domain = extract_domain_from_stream_url(track);
// Try full path first
if (!full_path.is_empty()) {
Gdiplus::Bitmap* result = try_load_station_logo_gdiplus(full_path, logos_dir);
if (result) {
return result;
}
}
// Try domain fallback
if (!domain.is_empty()) {
Gdiplus::Bitmap* result = try_load_station_logo_gdiplus(domain, logos_dir);
if (result) {
return result;
}
}
} catch (...) {
// Silently handle exceptions
}
return nullptr;
}
// New function to load noart logo directly as GDI+ bitmap (preserves alpha)
std::unique_ptr<Gdiplus::Bitmap> try_load_noart_logo_gdiplus(const pfc::string8& identifier, const pfc::string8& logos_dir) {
if (identifier.is_empty()) return nullptr;
try {
// Try PNG first (most likely to have alpha)
const char* extensions[] = { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
for (const char* ext : extensions) {
pfc::string8 noart_path = logos_dir + identifier + "-noart" + ext;
if (path_file_exists_utf8(noart_path.get_ptr())) {
// Convert to wide string for GDI+
std::wstring wide_path;
wide_path.resize(noart_path.length() + 1);
int result = MultiByteToWideChar(CP_UTF8, 0, noart_path.c_str(), -1, &wide_path[0], (int)wide_path.size());
if (result > 0) {
// Load directly with GDI+ to preserve alpha
auto bitmap = std::make_unique<Gdiplus::Bitmap>(wide_path.c_str());
if (bitmap && bitmap->GetLastStatus() == Gdiplus::Ok) {
return bitmap;
}
}
}
}
} catch (...) {
// Silently handle exceptions
}
return nullptr;
}
// Function to load noart logo directly as GDI+ bitmap (preserves alpha)
std::unique_ptr<Gdiplus::Bitmap> load_noart_logo_gdiplus(metadb_handle_ptr track) {
// Check if custom station logos are enabled
if (!cfg_enable_custom_logos) {
return nullptr;
}
if (!track.is_valid()) return nullptr;
// Get the directory path (using same logic as existing functions)
pfc::string8 profile_url = core_api::get_profile_path();
pfc::string8 profile_path;
if (profile_url.startsWith("file://")) {
profile_path = profile_url.c_str() + 7; // Skip "file://"
for (size_t i = 0; i < profile_path.length(); i++) {
if (profile_path[i] == '/') {
profile_path.set_char(i, '\\');
}
}
} else {
profile_path = profile_url;
}
pfc::string8 logos_dir = profile_path + "\\foo_artwork_data\\logos\\";
try {
// Extract domain and full path using existing functions
pfc::string8 full_path = extract_full_path_from_stream_url(track);
pfc::string8 domain = extract_domain_from_stream_url(track);
// Try full path first
if (!full_path.is_empty()) {
auto result = try_load_noart_logo_gdiplus(full_path, logos_dir);
if (result) {
return result;
}
}
// Try domain fallback
if (!domain.is_empty()) {
auto result = try_load_noart_logo_gdiplus(domain, logos_dir);
if (result) {
return result;
}
}
} catch (...) {
// Silently handle exceptions
}
return nullptr;
}
// Function to load generic noart logo directly as GDI+ bitmap (preserves alpha)
std::unique_ptr<Gdiplus::Bitmap> load_generic_noart_logo_gdiplus() {
// Check if custom station logos are enabled
if (!cfg_enable_custom_logos) {
return nullptr;
}
// Get the logos directory path (using same logic as other logo functions)
pfc::string8 logos_dir;
// Use custom logos folder if configured
if (!cfg_logos_folder.is_empty()) {
logos_dir = cfg_logos_folder.get_ptr();
if (!logos_dir.is_empty() && logos_dir[logos_dir.length() - 1] != '\\') {
logos_dir += "\\";
}
} else {
// Use default path
pfc::string8 profile_url = core_api::get_profile_path();
pfc::string8 profile_path;
if (strstr(profile_url.c_str(), "file://") == profile_url.c_str()) {
profile_path = profile_url.c_str() + 7;
for (size_t i = 0; i < profile_path.length(); i++) {
if (profile_path[i] == '/') {