-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIRPFFmpeg.cpp
More file actions
5143 lines (4425 loc) · 176 KB
/
Copy pathIRPFFmpeg.cpp
File metadata and controls
5143 lines (4425 loc) · 176 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
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0600
#include "framework.h"
#include "IRPFFmpeg.h"
#include "compact_mode.h"
#include "cover_art.h"
#include "eq_window.h"
#include "file_recording.h"
#include "language_manager.h"
#include "resource.h"
#include <windowsx.h>
#include <commctrl.h>
#include <shellapi.h>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <chrono>
#include <ctime>
#include <cstdarg>
#include <cctype>
#include <cwctype>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <wininet.h>
#include <uxtheme.h>
#include <dwmapi.h>
#include <shlwapi.h> // Для PathCombine
#include <gdiplus.h>
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "wininet.lib")
#pragma comment(lib, "UxTheme.lib")
#pragma comment(lib, "dwmapi.lib")
#pragma comment(lib, "msimg32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "gdiplus.lib")
const int MAX_RECONNECT_ATTEMPTS = 3;
const int RECONNECT_DELAY_MS = 2000;
const wchar_t MAIN_WINDOW_TITLE[] = L"IRPffmpeg v1.2.3";
#define ID_TIMER_IMAGE_URL 3
#define ID_TIMER_METADATA 4
#define IDT_COVER_RESTORE 5
#define IDT_TRACK_TOAST_HIDE 6
static constexpr UINT kTrayIconId = 1;
static constexpr int kTrackToastSize = 400;
static constexpr int kTrackToastMargin = 18;
static constexpr BYTE kTrackToastLayeredAlpha = 255;
static constexpr UINT kTrackToastHideDelayMs = 5000;
static const wchar_t TRACK_TOAST_CLASS[] = L"IRPFFmpegTrackToast";
static const wchar_t TRACK_TOAST_TEXT_CLASS[] = L"IRPFFmpegTrackToastText";
// -------------------------------
// Global UI Handles
// -------------------------------
HWND g_hMainWnd = NULL;
HWND g_hCoverArt = NULL;
HWND g_hPlaylist = NULL;
HWND g_hHistory = NULL;
HWND g_hStatic = NULL;
HBRUSH g_hbrBlack = nullptr;
HWND g_hBtnPlayPause, g_hBtnStop, g_hBtnOpen, g_hBtnPrev, g_hBtnNext;
HWND g_hVolumeButton;
HWND g_hLabelVolume, g_hLabelTreble, g_hLabelBass;
HWND g_hNowPlayingBar = NULL;
static ULONG_PTR g_volumeGdiplusToken = 0;
static const std::wstring kPlayIcon = L"▶ ";
static const std::wstring kPlaylistPlayingIcon = L"\u29BF ";
// -------------------------------
// Global variables for Audio Logic
// -------------------------------
std::atomic<bool> running(false);
std::atomic_bool g_suppressFfmpegDecoderLog(false);
std::atomic_bool g_audioStreamInfoAllowed(false);
std::atomic_bool g_enableDebugLogFile(false);// true - включить логирование в файл debug_log.txt, false - отключить
std::string current_track;
std::string current_metadata;
std::mutex metadata_mutex;
std::mutex g_coverFileMutex;
std::vector<std::string> track_history;
std::atomic<bool> g_stopImageThread(false);
std::thread g_playbackControlThread;
int reconnect_attempts = 0;
AVFormatContext* formatCtx = nullptr;
AVCodecContext* codecCtx = nullptr;
AVFilterGraph* filterGraph = nullptr;
AVFilterContext* filter_abuf = nullptr;
AVFilterContext* filter_aeq = nullptr;
AVFilterContext* filter_avol = nullptr;
AVFilterContext* filter_asink = nullptr;
std::atomic<float> current_volume(0.5f);
std::atomic<float> current_eq_gain(10.0f);
std::atomic<float> current_eq_gain_bass(2.0f);
std::atomic<unsigned long> g_playbackGeneration(0);
bool g_enableStereoWidth = true;
bool g_enableSpeechIntelligibilityCompressor = false;
bool g_enableLufsGainNormalizer = false;
bool g_enableExciter = false;
bool g_enableDeepBass = false;
bool g_enableLimiterGainRider = true;
bool g_enableIcyStationNameUpdates = true;
bool g_minimizeToTray = true;
bool g_showTrackToast = true;
bool g_compactModeAlwaysOnTop = true;
bool g_compactModeWithoutSpectrum = false;
bool g_compactModePositionSaved = false;
int g_compactModeX = 0;
int g_compactModeY = 0;
bool g_trackToastPositionSaved = false;
int g_trackToastX = 0;
int g_trackToastY = 0;
int g_stereoWidthPercent = 30;
std::thread g_playbackThread;
std::string g_currentUrl;
std::atomic_bool g_quit_flag(false);
std::thread g_imageUrlThread;
std::atomic<bool> g_bIsImageUrlThreadRunning(false);
std::atomic<bool> g_playbackThreadRunning(false);
CRITICAL_SECTION g_url_vec_cs;
int g_currentlyPlayingIndex = -1;
static int g_previousStationIndex = -1;
// очередь запросов для единственного control-потока
static std::vector<std::string> g_controlVector;
static std::mutex ControlVectorMutex;
static std::atomic<bool> g_controlThreadRunning(false);
static std::mutex g_stopPlaybackMutex;
// -------------------------------
static HFONT hButtonFont = NULL; // Font for button icons
static HFONT hListboxFont = NULL; // Font for listbox items
static HFONT hNowPlayingTitleFont = NULL;
const int TITLE_HEIGHT = 0;
extern const int alwaysVisibleExtent = 1024; // pixels
extern const int maxVisibleExtent = 2048; // pixels
bool rec_is_flac = false;
// Глобальный вектор для хранения плейлиста
static std::vector<PlaylistItem> playlist;
struct PlaylistNameResolvedPayload {
unsigned long generation = 0;
int index = -1;
std::wstring url;
std::wstring name;
};
static std::thread g_playlistNameResolveThread;
static std::atomic<bool> g_stopPlaylistNameResolveThread(false);
static std::atomic<unsigned long> g_playlistNameResolveGeneration(0);
static std::mutex g_ffmpegStatusMutex;
static std::string g_lastFfmpegStatusRaw;
static std::string g_lastFfmpegLogRaw;
static std::wstring g_nowPlayingTitle;
static std::wstring g_nowPlayingStatus = L"Остановлено";
static std::wstring g_nowPlayingStreamInfo;
static std::wstring g_nowPlayingElapsed;
static std::wstring g_limiterRiderStatus;
static std::wstring g_lufsNormalizerStatus;
static bool g_isReallyExiting = false;
static bool g_trayIconAdded = false;
static bool g_isInTray = false;
static bool g_trayHideBalloonShown = false;
static bool g_restoringFromTray = false;
static bool g_minimizeToTrayFromCaptionButton = false;
static HWND g_hTrackToast = nullptr;
static HWND g_hTrackToastText = nullptr;
static std::wstring g_trackToastTitle;
static SDL_Window* g_trackToastSdlWindow = nullptr;
static SDL_Renderer* g_trackToastRenderer = nullptr;
static bool g_trackToastDragging = false;
static POINT g_trackToastDragOffset = {};
static UINT g_wmTaskbarCreated = 0;
static void SetupMainDialogTooltips(HWND hDlg);
#define WM_RENDER_COVER (WM_USER + 100)
// формат: "Global\\{GUID}")
#define SINGLE_INSTANCE_MUTEX_NAME L"Global\\IRPffmpegInstanceMutex_1"
static void SanitizeM3ULine(std::string& text)
{
for (char& ch : text) {
if (ch == '\r' || ch == '\n') {
ch = ' ';
}
}
}
static bool SavePlaylistToM3U(const std::wstring& filename, const std::vector<PlaylistItem>& items)
{
std::ofstream file(filename, std::ios::binary | std::ios::trunc);
if (!file.is_open()) {
std::wstring msg = L"Could not write playlist file: " + filename;
MessageBoxW(g_hMainWnd, msg.c_str(), L"File Error", MB_OK | MB_ICONERROR);
return false;
}
file << "#EXTM3U\n";
for (const PlaylistItem& item : items) {
std::string name = wstring_to_utf8(item.name);
std::string url = wstring_to_utf8(item.url);
SanitizeM3ULine(name);
SanitizeM3ULine(url);
file << "#EXTINF:-1," << name << "\n";
file << url << "\n";
}
file.flush();
if (!file.good()) {
std::wstring msg = L"Failed to save playlist file: " + filename;
MessageBoxW(g_hMainWnd, msg.c_str(), L"File Error", MB_OK | MB_ICONERROR);
return false;
}
return true;
}
// -------------------------------
// Callbacks and Helpers
// -------------------------------
// FFmpeg interrupt callback
static int interrupt_callback(void* ctx) {
std::atomic_bool* q = static_cast<std::atomic_bool*>(ctx);
return q->load();
}
// Logging function
std::mutex log_mutex;
void LogToUI(const std::string& message) {
// Log to debug log file if enabled
if (!g_enableDebugLogFile.load()) {
return;
}
std::lock_guard<std::mutex> lock(log_mutex);
std::ofstream log_file("debug_log.txt", std::ios_base::app);
if (log_file.is_open()) {
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::time_t t = std::chrono::system_clock::to_time_t(now);
std::tm tm;
localtime_s(&tm, &t);
std::stringstream ss;
ss << "[" << std::this_thread::get_id() << "] "
<< std::put_time(&tm, "%H:%M:%S") << '.' << std::setfill('0') << std::setw(3) << ms.count()
<< ": " << message << std::endl;
log_file << ss.str();
// Also write to debug output, as it's still useful if not deadlocking
//OutputDebugStringA(ss.str().c_str());
}
}
void PostFfmpegStatus(const std::wstring& status)
{
if (!g_hMainWnd) return;
auto* text = new std::wstring(status);
if (!PostMessageW(g_hMainWnd, WM_APP_FFMPEG_STATUS, 0, (LPARAM)text)) {
delete text;
}
}
static void InvalidateNowPlayingBar(HWND hDlg)
{
HWND hBar = GetDlgItem(hDlg, IDC_STATIC_NOW_PLAYING_BAR);
if (hBar) {
InvalidateRect(hBar, NULL, FALSE);
}
CompactModeInvalidateTitle();
}
static void UpdatePlayPauseButtonIcon(HWND hDlg)
{
HWND hButton = GetDlgItem(hDlg, IDC_BUTTON_PP);
if (hButton) {
InvalidateRect(hButton, NULL, TRUE);
UpdateWindow(hButton);
}
}
static void ForceForegroundWindow(HWND hWnd)
{
if (!hWnd || !IsWindow(hWnd)) {
return;
}
if (IsIconic(hWnd)) {
ShowWindow(hWnd, SW_RESTORE);
}
else {
ShowWindow(hWnd, SW_SHOWNORMAL);
}
HWND hForeground = GetForegroundWindow();
DWORD foregroundThreadId = GetWindowThreadProcessId(hForeground, nullptr);
DWORD currentThreadId = GetCurrentThreadId();
bool attached = false;
if (foregroundThreadId != 0 && foregroundThreadId != currentThreadId) {
attached = AttachThreadInput(foregroundThreadId, currentThreadId, TRUE) != FALSE;
}
BringWindowToTop(hWnd);
SetActiveWindow(hWnd);
SetForegroundWindow(hWnd);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
if (attached) {
AttachThreadInput(foregroundThreadId, currentThreadId, FALSE);
}
}
static bool ShouldEnsureForeground(HWND hWnd)
{
return hWnd &&
IsWindow(hWnd) &&
!g_isInTray &&
!g_isReallyExiting &&
!g_restoringFromTray &&
!g_minimizeToTrayFromCaptionButton &&
!IsIconic(hWnd) &&
IsWindowVisible(hWnd);
}
static std::wstring GetPlaylistDisplayName(int index)
{
if (index < 0 || index >= static_cast<int>(playlist.size())) {
return std::wstring();
}
if (g_enableIcyStationNameUpdates &&
!playlist[index].disable_name_icy &&
!playlist[index].name_icy.empty()) {
return playlist[index].name_icy;
}
return playlist[index].name;
}
static std::wstring GetNowPlayingTitleText()
{
if (!g_nowPlayingTitle.empty()) {
return g_nowPlayingTitle;
}
if (g_currentlyPlayingIndex >= 0 &&
g_currentlyPlayingIndex < static_cast<int>(playlist.size())) {
return GetPlaylistDisplayName(g_currentlyPlayingIndex);
}
return Tr("nowplaying.no_data", L"Нет данных о треке");
}
static void CleanupTrackToastSdl()
{
if (g_trackToastRenderer) {
SDL_DestroyRenderer(g_trackToastRenderer);
g_trackToastRenderer = nullptr;
}
if (g_trackToastSdlWindow) {
SDL_DestroyWindow(g_trackToastSdlWindow);
g_trackToastSdlWindow = nullptr;
}
}
static void ConfigureTrackToastLayeredWindow(HWND hWnd)
{
if (!hWnd) {
return;
}
LONG_PTR exStyle = GetWindowLongPtrW(hWnd, GWL_EXSTYLE);
if ((exStyle & WS_EX_LAYERED) == 0) {
SetWindowLongPtrW(hWnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
}
SetLayeredWindowAttributes(hWnd, 0, kTrackToastLayeredAlpha, LWA_ALPHA);
}
static void RestartTrackToastHideTimer(HWND hWnd)
{
if (!hWnd || !IsWindow(hWnd)) {
return;
}
KillTimer(hWnd, IDT_TRACK_TOAST_HIDE);
SetTimer(hWnd, IDT_TRACK_TOAST_HIDE, kTrackToastHideDelayMs, nullptr);
}
static void SaveTrackToastPosition(HWND hWnd)
{
if (!hWnd || !IsWindow(hWnd)) {
return;
}
RECT toastRc = {};
if (GetWindowRect(hWnd, &toastRc)) {
g_trackToastPositionSaved = true;
g_trackToastX = toastRc.left;
g_trackToastY = toastRc.top;
}
}
static void FinishTrackToastDrag(HWND hWnd, bool releaseCapture)
{
if (!g_trackToastDragging) {
return;
}
g_trackToastDragging = false;
if (releaseCapture && GetCapture() == hWnd) {
ReleaseCapture();
}
SaveTrackToastPosition(hWnd);
RestartTrackToastHideTimer(hWnd);
}
static bool EnsureTrackToastSdl(HWND hWnd)
{
if (g_trackToastRenderer) {
return true;
}
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2");
g_trackToastSdlWindow = SDL_CreateWindowFrom(hWnd);
if (!g_trackToastSdlWindow) {
return false;
}
g_trackToastRenderer = SDL_CreateRenderer(g_trackToastSdlWindow, -1, SDL_RENDERER_SOFTWARE);
if (!g_trackToastRenderer) {
g_trackToastRenderer = SDL_CreateRenderer(g_trackToastSdlWindow, -1, SDL_RENDERER_ACCELERATED);
}
if (!g_trackToastRenderer) {
CleanupTrackToastSdl();
return false;
}
SDL_SetRenderDrawBlendMode(g_trackToastRenderer, SDL_BLENDMODE_BLEND);
return true;
}
static constexpr int kTrackToastTextPaddingX = 12;
static constexpr int kTrackToastTextPaddingY = 4;
static constexpr int kTrackToastMaxTextLines = 3;
static std::wstring NormalizeTrackToastTitleText(const std::wstring& text)
{
std::wstring normalized;
normalized.reserve(text.size());
bool previousWasSpace = false;
for (wchar_t ch : text) {
if (std::iswspace(ch)) {
if (!previousWasSpace) {
normalized.push_back(L' ');
previousWasSpace = true;
}
}
else {
normalized.push_back(ch);
previousWasSpace = false;
}
}
while (!normalized.empty() && normalized.front() == L' ') {
normalized.erase(normalized.begin());
}
while (!normalized.empty() && normalized.back() == L' ') {
normalized.pop_back();
}
return normalized;
}
static int MeasureTrackToastTextWidth(HDC hdc, const std::wstring& text)
{
SIZE size = {};
if (text.empty()) {
return 0;
}
GetTextExtentPoint32W(hdc, text.c_str(), static_cast<int>(text.size()), &size);
return size.cx;
}
static std::wstring EllipsizeTrackToastLine(HDC hdc, const std::wstring& text, int maxWidth)
{
static const std::wstring ellipsis = L"...";
if (MeasureTrackToastTextWidth(hdc, text) <= maxWidth) {
return text;
}
if (MeasureTrackToastTextWidth(hdc, ellipsis) > maxWidth) {
return std::wstring();
}
std::wstring result = text;
while (!result.empty()) {
result.pop_back();
while (!result.empty() && result.back() == L' ') {
result.pop_back();
}
std::wstring candidate = result + ellipsis;
if (MeasureTrackToastTextWidth(hdc, candidate) <= maxWidth) {
return candidate;
}
}
return ellipsis;
}
static std::vector<std::wstring> BuildTrackToastTextLines(HDC hdc, int width)
{
const int maxTextWidth = (std::max)(1, width - kTrackToastTextPaddingX * 2);
const std::wstring text = NormalizeTrackToastTitleText(g_trackToastTitle);
std::vector<std::wstring> words;
size_t pos = 0;
while (pos < text.size()) {
size_t next = text.find(L' ', pos);
if (next == std::wstring::npos) {
words.push_back(text.substr(pos));
break;
}
if (next > pos) {
words.push_back(text.substr(pos, next - pos));
}
pos = next + 1;
}
std::vector<std::wstring> lines;
std::wstring current;
size_t wordIndex = 0;
while (wordIndex < words.size() && lines.size() < kTrackToastMaxTextLines) {
const std::wstring& word = words[wordIndex];
std::wstring candidate = current.empty() ? word : current + L" " + word;
if (MeasureTrackToastTextWidth(hdc, candidate) <= maxTextWidth) {
current = std::move(candidate);
++wordIndex;
continue;
}
if (current.empty()) {
lines.push_back(EllipsizeTrackToastLine(hdc, word, maxTextWidth));
++wordIndex;
}
else {
lines.push_back(current);
current.clear();
}
}
if (!current.empty() && lines.size() < kTrackToastMaxTextLines) {
lines.push_back(current);
}
if (wordIndex < words.size() && !lines.empty()) {
std::wstring tail = lines.back();
for (size_t i = wordIndex; i < words.size(); ++i) {
if (!tail.empty()) {
tail += L" ";
}
tail += words[i];
}
lines.back() = EllipsizeTrackToastLine(hdc, tail, maxTextWidth);
}
if (lines.empty()) {
lines.push_back(L"");
}
return lines;
}
static int GetTrackToastLineHeight(HDC hdc)
{
TEXTMETRICW tm = {};
if (GetTextMetricsW(hdc, &tm)) {
return tm.tmHeight + tm.tmExternalLeading;
}
return 18;
}
static int CalculateTrackToastOverlayHeight(HDC hdc, int width, HFONT hFont)
{
HFONT hOldFont = hFont ? (HFONT)SelectObject(hdc, hFont) : nullptr;
const int lineHeight = GetTrackToastLineHeight(hdc);
const auto lines = BuildTrackToastTextLines(hdc, width);
const int textHeight = lineHeight * static_cast<int>(lines.size());
if (hOldFont) {
SelectObject(hdc, hOldFont);
}
return (std::max)(lineHeight + kTrackToastTextPaddingY * 2, textHeight + kTrackToastTextPaddingY * 2);
}
static HFONT CreateTrackToastTitleFont()
{
LOGFONTW lf = {};
lf.lfHeight = -15;
lf.lfWeight = FW_NORMAL;
lf.lfCharSet = DEFAULT_CHARSET;
wcscpy_s(lf.lfFaceName, L"Segoe UI");
return CreateFontIndirectW(&lf);
}
static void LayoutTrackToastText(HWND hWnd)
{
if (!g_hTrackToastText) {
return;
}
RECT rc = {};
GetClientRect(hWnd, &rc);
int overlayHeight = 22;
HDC overlayDc = GetDC(hWnd);
if (overlayDc) {
HFONT hTitleFont = CreateTrackToastTitleFont();
overlayHeight = CalculateTrackToastOverlayHeight(overlayDc, rc.right - rc.left, hTitleFont);
if (hTitleFont) {
DeleteObject(hTitleFont);
}
ReleaseDC(hWnd, overlayDc);
}
SetWindowPos(g_hTrackToastText, HWND_TOP, 0, 0, rc.right - rc.left, overlayHeight,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
InvalidateRect(g_hTrackToastText, nullptr, TRUE);
}
static void DrawTrackToastText(HWND hWnd, HDC hdc)
{
RECT rc = {};
GetClientRect(hWnd, &rc);
HFONT hTitleFont = CreateTrackToastTitleFont();
HFONT hOldFont = hTitleFont ? (HFONT)SelectObject(hdc, hTitleFont) : nullptr;
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, RGB(245, 245, 245));
const auto lines = BuildTrackToastTextLines(hdc, rc.right - rc.left);
const int lineHeight = GetTrackToastLineHeight(hdc);
int y = kTrackToastTextPaddingY;
for (const std::wstring& line : lines) {
RECT textRect = {
kTrackToastTextPaddingX,
y,
rc.right - kTrackToastTextPaddingX,
y + lineHeight
};
DrawTextW(hdc, line.c_str(), -1, &textRect,
DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX);
y += lineHeight;
}
if (hOldFont) {
SelectObject(hdc, hOldFont);
}
if (hTitleFont) {
DeleteObject(hTitleFont);
}
}
static void DrawTrackToast(HWND hWnd, HDC hdc)
{
RECT rc = {};
GetClientRect(hWnd, &rc);
const int width = rc.right - rc.left;
const int height = rc.bottom - rc.top;
int overlayHeight = 22;
HDC overlayDc = GetDC(hWnd);
if (overlayDc) {
HFONT hTitleFont = CreateTrackToastTitleFont();
overlayHeight = CalculateTrackToastOverlayHeight(overlayDc, width, hTitleFont);
if (hTitleFont) {
DeleteObject(hTitleFont);
}
ReleaseDC(hWnd, overlayDc);
}
if (EnsureTrackToastSdl(hWnd)) {
SDL_SetRenderDrawColor(g_trackToastRenderer, 35, 38, 44, 255);
SDL_RenderClear(g_trackToastRenderer);
SDL_Surface* loadedSurface = nullptr;
{
std::lock_guard<std::mutex> lock(g_coverFileMutex);
loadedSurface = IMG_Load("cover_cache\\cover.jpg");
}
if (loadedSurface) {
SDL_Texture* coverTexture = SDL_CreateTextureFromSurface(g_trackToastRenderer, loadedSurface);
SDL_FreeSurface(loadedSurface);
if (coverTexture) {
SDL_Rect dst = { 0, 0, width, height };
SDL_RenderCopy(g_trackToastRenderer, coverTexture, nullptr, &dst);
SDL_DestroyTexture(coverTexture);
}
}
SDL_SetRenderDrawBlendMode(g_trackToastRenderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(g_trackToastRenderer, 0, 0, 0, 190);
SDL_Rect overlayRect = { 0, 0, width, overlayHeight };
SDL_RenderFillRect(g_trackToastRenderer, &overlayRect);
SDL_SetRenderDrawBlendMode(g_trackToastRenderer, SDL_BLENDMODE_NONE);
SDL_SetRenderDrawColor(g_trackToastRenderer, 190, 190, 190, 255);
SDL_Rect borderRect = { 0, 0, width - 1, height - 1 };
SDL_RenderDrawRect(g_trackToastRenderer, &borderRect);
SDL_RenderPresent(g_trackToastRenderer);
}
else {
HBRUSH fallbackBrush = CreateSolidBrush(RGB(35, 38, 44));
FillRect(hdc, &rc, fallbackBrush);
DeleteObject(fallbackBrush);
RECT overlayRect = { 0, 0, width, overlayHeight };
HBRUSH overlayBrush = CreateSolidBrush(RGB(0, 0, 0));
FillRect(hdc, &overlayRect, overlayBrush);
DeleteObject(overlayBrush);
HBRUSH borderBrush = CreateSolidBrush(RGB(190, 190, 190));
FrameRect(hdc, &rc, borderBrush);
DeleteObject(borderBrush);
}
LayoutTrackToastText(hWnd);
}
static LRESULT CALLBACK TrackToastTextProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
DrawTrackToastText(hWnd, hdc);
EndPaint(hWnd, &ps);
return 0;
}
case WM_LBUTTONDOWN:
case WM_MOUSEMOVE:
case WM_LBUTTONUP:
{
HWND hParent = GetParent(hWnd);
if (hParent) {
POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
MapWindowPoints(hWnd, hParent, &pt, 1);
SendMessageW(hParent, msg, wParam, MAKELPARAM(pt.x, pt.y));
return 0;
}
break;
}
case WM_NCDESTROY:
if (g_hTrackToastText == hWnd) {
g_hTrackToastText = nullptr;
}
break;
}
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
static LRESULT CALLBACK TrackToastProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
DrawTrackToast(hWnd, hdc);
EndPaint(hWnd, &ps);
return 0;
}
case WM_TIMER:
if (wParam == IDT_TRACK_TOAST_HIDE) {
KillTimer(hWnd, IDT_TRACK_TOAST_HIDE);
ShowWindow(hWnd, SW_HIDE);
return 0;
}
break;
case WM_LBUTTONDOWN:
KillTimer(hWnd, IDT_TRACK_TOAST_HIDE);
g_trackToastDragging = true;
g_trackToastDragOffset.x = GET_X_LPARAM(lParam);
g_trackToastDragOffset.y = GET_Y_LPARAM(lParam);
SetCapture(hWnd);
return 0;
case WM_MOUSEMOVE:
if (g_trackToastDragging) {
POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
ClientToScreen(hWnd, &pt);
int x = pt.x - g_trackToastDragOffset.x;
int y = pt.y - g_trackToastDragOffset.y;
SetWindowPos(hWnd, HWND_TOPMOST, x, y, 0, 0,
SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
return 0;
}
break;
case WM_LBUTTONUP:
if (g_trackToastDragging) {
FinishTrackToastDrag(hWnd, true);
return 0;
}
break;
case WM_CAPTURECHANGED:
FinishTrackToastDrag(hWnd, false);
break;
case WM_NCDESTROY:
CleanupTrackToastSdl();
if (g_hTrackToastText && GetParent(g_hTrackToastText) == hWnd) {
g_hTrackToastText = nullptr;
}
if (g_hTrackToast == hWnd) {
g_hTrackToast = nullptr;
}
break;
}
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
static void RegisterTrackToastClass()
{
static bool registered = false;
static bool textRegistered = false;
if (registered && textRegistered) {
return;
}
HINSTANCE hInstance = GetModuleHandleW(nullptr);
HCURSOR hCursor = LoadCursor(nullptr, IDC_ARROW);
if (!registered) {
WNDCLASSW wc = {};
wc.lpfnWndProc = TrackToastProc;
wc.hInstance = hInstance;
wc.hCursor = hCursor;
wc.hbrBackground = nullptr;
wc.lpszClassName = TRACK_TOAST_CLASS;
if (RegisterClassW(&wc) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) {
registered = true;
}
}
if (!textRegistered) {
WNDCLASSW wc = {};
wc.lpfnWndProc = TrackToastTextProc;
wc.hInstance = hInstance;
wc.hCursor = hCursor;
wc.hbrBackground = nullptr;
wc.lpszClassName = TRACK_TOAST_TEXT_CLASS;
if (RegisterClassW(&wc) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) {
textRegistered = true;
}
}
}
static void ShowTrackToastIfNeeded(HWND hOwner)
{
const bool showInCurrentMode = g_isInTray || (CompactModeIsActive() && !g_isInTray);
if (!g_showTrackToast || !showInCurrentMode) {
return;
}
g_trackToastTitle = GetNowPlayingTitleText();
if (g_trackToastTitle.empty() || g_trackToastTitle == Tr("nowplaying.no_data", L"Нет данных о треке")) {
return;
}
RegisterTrackToastClass();
if (!g_hTrackToast) {
g_hTrackToast = CreateWindowExW(
WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_LAYERED,
TRACK_TOAST_CLASS,
L"",
WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT,
kTrackToastSize, kTrackToastSize,
hOwner,
nullptr,
GetModuleHandleW(nullptr),
nullptr);
}
if (!g_hTrackToast) {
return;
}
ConfigureTrackToastLayeredWindow(g_hTrackToast);
if (!g_hTrackToastText) {
g_hTrackToastText = CreateWindowExW(
WS_EX_TRANSPARENT,
TRACK_TOAST_TEXT_CLASS,
L"",
WS_CHILD | WS_VISIBLE,
0, 0,
kTrackToastSize, 24,
g_hTrackToast,
nullptr,
GetModuleHandleW(nullptr),
nullptr);
}
CleanupTrackToastSdl();
MONITORINFO mi = {};
mi.cbSize = sizeof(mi);
HMONITOR hMon = MonitorFromWindow(hOwner, MONITOR_DEFAULTTONEAREST);
if (!GetMonitorInfoW(hMon, &mi)) {
SystemParametersInfoW(SPI_GETWORKAREA, 0, &mi.rcWork, 0);
}
int x = mi.rcWork.right - kTrackToastSize - kTrackToastMargin;
int y = mi.rcWork.bottom - kTrackToastSize - kTrackToastMargin;
if (g_trackToastPositionSaved) {
x = g_trackToastX;
y = g_trackToastY;
}
if (x < mi.rcWork.left) x = mi.rcWork.left;
if (y < mi.rcWork.top) y = mi.rcWork.top;
if (x + kTrackToastSize > mi.rcWork.right) x = mi.rcWork.right - kTrackToastSize;
if (y + kTrackToastSize > mi.rcWork.bottom) y = mi.rcWork.bottom - kTrackToastSize;
SetWindowPos(g_hTrackToast, HWND_TOPMOST, x, y, kTrackToastSize, kTrackToastSize,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
LayoutTrackToastText(g_hTrackToast);
InvalidateRect(g_hTrackToast, nullptr, TRUE);
UpdateWindow(g_hTrackToast);
if (g_hTrackToastText) {
InvalidateRect(g_hTrackToastText, nullptr, TRUE);
UpdateWindow(g_hTrackToastText);
}
RestartTrackToastHideTimer(g_hTrackToast);
}
static bool IsTransientPlaybackStatus(const std::wstring& status)
{
if (status.empty() || status == TrString("status.stopped", L"Остановлено")) {
return false;
}
if (status.rfind(L"\u25B7", 0) == 0) {
return false;
}
static const wchar_t* tokens[] = {
L"FFmpeg",
L"Подключение",
L"Чтение",
L"Анализ",
L"Используемый",
L"Ошибка",
L"Поток",
L"таймаут",
L"Переподключение",
L"Попытка",
L"Аудиоустройство",
L"Пропускаем",
L"Connecting",
L"Reading",
L"Analyzing",
L"Active",
L"Error",