-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.cpp
More file actions
1145 lines (1036 loc) · 41.4 KB
/
Copy pathplayer.cpp
File metadata and controls
1145 lines (1036 loc) · 41.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
/*
* C++ + GTK3 音乐/视频播放器 (GNOME 风格, mpv 引擎)
* 支持 mp3/wav/flac/ogg/m4a 等音频 + mp4/mkv/avi/webm 等视频 (通过 mpv)
* 元数据/封面来自 taglib;midi 走系统 MCI
*/
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <gtk/gtk.h>
#include <gdk/gdkwin32.h>
#include <windows.h>
#include <mmsystem.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <taglib/fileref.h>
#include <taglib/tag.h>
#include <taglib/mpegfile.h>
#include <taglib/id3v2tag.h>
#include <taglib/attachedpictureframe.h>
#include "json.hpp"
using json = nlohmann::json;
#define APP_ID "com.example.cmusicplayer"
/* ---------------- 曲目信息 ---------------- */
typedef struct TrackInfo {
gchar *path;
gchar *title;
gchar *artist;
gchar *album;
long duration_ms;
int is_video;
int is_midi;
GdkPixbuf *cover; /* 480x480 方形或 NULL */
GdkPixbuf *thumb; /* 44x44 方形或 NULL */
} TrackInfo;
static GtkWidget *window = NULL;
static GtkWidget *headerbar = NULL;
static GtkWidget *media_stack = NULL;
static GtkWidget *cover_widget = NULL;
static GtkWidget *video_area = NULL;
static GtkWidget *playlist_box = NULL;
static GtkWidget *btn_play = NULL;
static GtkWidget *play_icon = NULL;
static GtkWidget *btn_loop = NULL;
static GtkWidget *loop_icon = NULL;
static GtkWidget *title_label = NULL;
static GtkWidget *sub_label = NULL;
static GtkWidget *time_cur = NULL;
static GtkWidget *time_total = NULL;
static GtkWidget *pos_scale = NULL;
static GtkWidget *vol_scale = NULL;
static GtkWidget *status_label = NULL;
static GtkListBoxRow *current_row = NULL;
static GList *playlist = NULL;
static TrackInfo *current_track = NULL;
static GdkPixbuf *cover_pixbuf = NULL;
static GdkPixbuf *placeholder_thumb = NULL;
static guint pos_timer = 0;
static int is_playing = 0;
static int is_paused = 0;
static int seeking = 0;
static int loop_mode = 1; /* 0=顺序 1=列表循环 2=单曲循环 */
static long media_length = 0;
static char current_file[2048] = "";
static int vol_value = 80;
/* ---------------- mpv 引擎 (Windows 命名管道 IPC) ---------------- */
static HANDLE g_mpv_pipe = INVALID_HANDLE_VALUE;
static PROCESS_INFORMATION g_mpv_proc;
static int g_mpv_ok = 0;
static int sound_mode = 0; /* 0=无 1=mpv 2=MCI(midi) */
static int g_media_loaded = 0;
static double g_mpv_pos = 0;
static int g_mpv_eof = 0;
static int g_req_id = 0;
static std::string g_pipe_buf;
static HWND g_video_hwnd = 0;
static void format_time(long ms, char *buf, size_t len);
static void stop_song(void);
static void mpv_send(const json &j)
{
if (g_mpv_pipe == INVALID_HANDLE_VALUE) return;
std::string s = j.dump() + "\n";
DWORD wrote = 0;
WriteFile(g_mpv_pipe, s.data(), (DWORD)s.size(), &wrote, NULL);
}
static void mpv_command(json args)
{
json j;
j["command"] = args;
j["request_id"] = ++g_req_id;
mpv_send(j);
}
static void mpv_set_prop(const char *name, json value)
{
mpv_command(json::array({"set_property", name, value}));
}
static void mpv_observe(int id, const char *name)
{
mpv_command(json::array({"observe_property", id, name}));
}
static void handle_mpv_msg(const std::string &msg)
{
json j;
try {
j = json::parse(msg);
} catch (...) {
return;
}
if (!j.contains("event")) return;
std::string ev = j["event"].get<std::string>();
if (ev == "property-change") {
std::string name = j.value("name", "");
if (name == "time-pos" && j.contains("data") && !j["data"].is_null())
g_mpv_pos = j["data"].get<double>();
else if (name == "duration" && j.contains("data") && !j["data"].is_null()) {
double dur = j["data"].get<double>();
if (media_length == 0 && dur > 0) {
media_length = (long)(dur * 1000);
gtk_range_set_range(GTK_RANGE(pos_scale), 0, media_length > 0 ? media_length : 1);
char b2[16];
format_time(media_length, b2, sizeof b2);
gtk_label_set_text(GTK_LABEL(time_total), b2);
}
} else if (name == "eof-reached" && j.contains("data") && j["data"].is_boolean()) {
g_mpv_eof = j["data"].get<bool>() ? 1 : 0;
}
} else if (ev == "end-file") {
std::string reason = j.value("reason", "");
if (reason == "eof")
g_mpv_eof = 1;
else if (reason == "error") {
char msg2[2400];
snprintf(msg2, sizeof msg2, "无法播放文件:\n%s", current_file[0] ? current_file : "未知");
GtkWidget *d = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", msg2);
gtk_dialog_run(GTK_DIALOG(d));
gtk_widget_destroy(d);
stop_song();
}
} else if (ev == "start-file") {
g_media_loaded = 1;
g_mpv_eof = 0;
}
}
static void mpv_drain(void)
{
if (g_mpv_pipe == INVALID_HANDLE_VALUE) return;
DWORD avail = 0;
if (!PeekNamedPipe(g_mpv_pipe, NULL, 0, NULL, &avail, NULL)) {
CloseHandle(g_mpv_pipe);
g_mpv_pipe = INVALID_HANDLE_VALUE;
return;
}
if (avail > 0) {
char tmp[65536];
DWORD rd = 0;
if (ReadFile(g_mpv_pipe, tmp, sizeof tmp, &rd, NULL) && rd > 0)
g_pipe_buf.append(tmp, rd);
}
int depth = 0, start = -1;
for (size_t i = 0; i < g_pipe_buf.size(); i++) {
char c = g_pipe_buf[i];
if (c == '{') {
if (depth == 0) start = (int)i;
depth++;
} else if (c == '}') {
depth--;
if (depth == 0 && start >= 0) {
std::string msg = g_pipe_buf.substr(start, i - start + 1);
g_pipe_buf.erase(0, i + 1);
handle_mpv_msg(msg);
return mpv_drain();
}
}
}
if (g_pipe_buf.size() > 1 << 20) g_pipe_buf.clear();
}
static void mpv_start(void)
{
wchar_t exe[MAX_PATH];
GetModuleFileNameW(NULL, exe, MAX_PATH);
wchar_t *slash = wcsrchr(exe, L'\\');
if (!slash) return;
*slash = L'\0';
wchar_t mpv_path[MAX_PATH], mpv_dir[MAX_PATH], cmd[4096];
swprintf(mpv_dir, sizeof mpv_dir / 2, L"%ls\\mpv", exe);
swprintf(mpv_path, sizeof mpv_path / 2, L"%ls\\mpv.exe", mpv_dir);
if (GetFileAttributesW(mpv_path) == INVALID_FILE_ATTRIBUTES) {
g_mpv_ok = 0;
return;
}
if (g_video_hwnd)
swprintf(cmd, sizeof cmd / 2,
L"\"%ls\" --no-terminal --idle=yes --input-ipc-server=\\\\.\\pipe\\musicplayer_ipc --wid=%llu",
mpv_path, (unsigned long long)g_video_hwnd);
else
swprintf(cmd, sizeof cmd / 2,
L"\"%ls\" --no-terminal --idle=yes --input-ipc-server=\\\\.\\pipe\\musicplayer_ipc",
mpv_path);
STARTUPINFOW si;
ZeroMemory(&si, sizeof si);
si.cb = sizeof si;
if (!CreateProcessW(NULL, cmd, NULL, NULL, FALSE, CREATE_NO_WINDOW,
NULL, mpv_dir, &si, &g_mpv_proc)) {
g_mpv_ok = 0;
return;
}
for (int i = 0; i < 60; i++) {
g_mpv_pipe = CreateFileW(L"\\\\.\\pipe\\musicplayer_ipc",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (g_mpv_pipe != INVALID_HANDLE_VALUE) break;
Sleep(100);
}
if (g_mpv_pipe == INVALID_HANDLE_VALUE) {
TerminateProcess(g_mpv_proc.hProcess, 0);
g_mpv_ok = 0;
return;
}
g_mpv_ok = 1;
Sleep(200);
mpv_observe(1, "time-pos");
mpv_observe(2, "duration");
mpv_observe(3, "eof-reached");
}
static void mpv_cleanup(void)
{
if (g_mpv_pipe != INVALID_HANDLE_VALUE) {
json q;
q["command"] = json::array({"quit"});
mpv_send(q);
Sleep(300);
CloseHandle(g_mpv_pipe);
}
if (g_mpv_proc.hProcess) {
if (WaitForSingleObject(g_mpv_proc.hProcess, 100) == WAIT_TIMEOUT)
TerminateProcess(g_mpv_proc.hProcess, 0);
CloseHandle(g_mpv_proc.hProcess);
CloseHandle(g_mpv_proc.hThread);
}
}
/* ---------------- MCI 封装 (midi 后备) ---------------- */
static int mci(const char *cmd)
{
return mciSendStringA(cmd, NULL, 0, NULL) == MMSYSERR_NOERROR;
}
static long mci_status(const char *cmd)
{
char buf[64] = "0";
mciSendStringA(cmd, buf, sizeof buf, NULL);
return strtol(buf, NULL, 10);
}
/* ---------------- 工具函数 ---------------- */
static void format_time(long ms, char *buf, size_t len)
{
long t = ms / 1000;
snprintf(buf, len, "%02ld:%02ld", t / 60, t % 60);
}
static GdkPixbuf *cover_square(GdkPixbuf *src, int size)
{
int w = gdk_pixbuf_get_width(src), h = gdk_pixbuf_get_height(src);
int s = MIN(w, h), x = (w - s) / 2, y = (h - s) / 2;
GdkPixbuf *sub = gdk_pixbuf_new_subpixbuf(src, x, y, s, s);
GdkPixbuf *scaled = gdk_pixbuf_scale_simple(sub, size, size, GDK_INTERP_BILINEAR);
g_object_unref(sub);
return scaled;
}
static GdkPixbuf *make_placeholder_thumb(void)
{
cairo_surface_t *sf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 44, 44);
cairo_t *cr = cairo_create(sf);
cairo_set_source_rgb(cr, 0.18, 0.18, 0.21);
cairo_paint(cr);
cairo_set_source_rgba(cr, 1, 1, 1, 0.25);
cairo_select_font_face(cr, "Segoe UI Symbol", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, 22);
cairo_text_extents_t te;
cairo_text_extents(cr, "\xe2\x99\xaa", &te);
cairo_move_to(cr, (44 - te.width) / 2 - te.x_bearing, (44 - te.height) / 2 - te.y_bearing);
cairo_show_text(cr, "\xe2\x99\xaa");
cairo_destroy(cr);
GdkPixbuf *pb = gdk_pixbuf_get_from_surface(sf, 0, 0, 44, 44);
cairo_surface_destroy(sf);
return pb;
}
/* ---------------- 元数据解析 (taglib) ---------------- */
static int ext_is_video(const char *ext)
{
static const char *v[] = { "mp4", "mkv", "avi", "mov", "webm", "flv", "m4v",
"ts", "m2ts", "wmv", "mpg", "mpeg", "3gp", "ogv", "rmvb", "vob",
"mts", "m2v", "divx", "asf", "f4v" };
for (size_t i = 0; i < sizeof v / sizeof v[0]; i++)
if (!g_ascii_strcasecmp(ext, v[i])) return 1;
return 0;
}
static TrackInfo *track_parse(const char *path)
{
TrackInfo *t = g_new0(TrackInfo, 1);
t->path = g_strdup(path);
const char *ext = strrchr(path, '.');
if (ext) {
if (!g_ascii_strcasecmp(ext, ".mid") || !g_ascii_strcasecmp(ext, ".midi"))
t->is_midi = 1;
else if (ext_is_video(ext))
t->is_video = 1;
}
gchar *base = g_path_get_basename(path);
gchar *dot = strrchr(base, '.');
if (dot) *dot = 0;
t->title = base;
t->artist = g_strdup("未知艺术家");
t->album = g_strdup("");
gunichar2 *wpath = g_utf8_to_utf16(path, -1, NULL, NULL, NULL);
if (wpath) {
TagLib::FileName fn((const wchar_t *)wpath);
TagLib::FileRef f(fn);
if (!f.isNull()) {
if (f.tag()) {
TagLib::Tag *tag = f.tag();
if (!tag->title().isEmpty())
{ g_free(t->title); t->title = g_strdup(tag->title().to8Bit(true).c_str()); }
if (!tag->artist().isEmpty())
{ g_free(t->artist); t->artist = g_strdup(tag->artist().to8Bit(true).c_str()); }
if (!tag->album().isEmpty())
{ g_free(t->album); t->album = g_strdup(tag->album().to8Bit(true).c_str()); }
}
if (f.audioProperties())
t->duration_ms = (long)f.audioProperties()->lengthInMilliseconds();
if (!t->is_video) {
TagLib::MPEG::File *mp3 = dynamic_cast<TagLib::MPEG::File *>(f.file());
if (mp3) {
TagLib::ID3v2::Tag *id3 = mp3->ID3v2Tag();
if (id3) {
TagLib::ID3v2::FrameList fl = id3->frameList("APIC");
for (TagLib::ID3v2::FrameList::ConstIterator it = fl.begin(); it != fl.end(); ++it) {
TagLib::ID3v2::AttachedPictureFrame *ap =
dynamic_cast<TagLib::ID3v2::AttachedPictureFrame *>(*it);
if (ap && ap->picture().size() > 0) {
GInputStream *in = g_memory_input_stream_new_from_data(
ap->picture().data(), (gssize)ap->picture().size(), NULL);
GdkPixbuf *pb = gdk_pixbuf_new_from_stream(in, NULL, NULL);
g_object_unref(in);
if (pb) {
t->cover = cover_square(pb, 480);
t->thumb = cover_square(pb, 44);
g_object_unref(pb);
}
if (t->cover) break;
}
}
}
}
}
}
g_free(wpath);
}
return t;
}
static void track_free(TrackInfo *t)
{
if (!t) return;
g_free(t->path);
g_free(t->title);
g_free(t->artist);
g_free(t->album);
if (t->cover) g_object_unref(t->cover);
if (t->thumb) g_object_unref(t->thumb);
g_free(t);
}
/* ---------------- UI 更新 ---------------- */
static void set_play_icon(const char *name)
{
gtk_image_set_from_icon_name(GTK_IMAGE(play_icon), name, GTK_ICON_SIZE_BUTTON);
}
static void update_loop_button(void)
{
const char *icon = loop_mode == 2 ? "repeat-single-symbolic" : "repeat-symbolic";
gtk_image_set_from_icon_name(GTK_IMAGE(loop_icon), icon, GTK_ICON_SIZE_BUTTON);
GtkStyleContext *ctx = gtk_widget_get_style_context(btn_loop);
if (loop_mode == 0)
gtk_style_context_remove_class(ctx, "suggested-action");
else
gtk_style_context_add_class(ctx, "suggested-action");
gtk_widget_set_tooltip_text(btn_loop,
loop_mode == 0 ? "顺序播放(点击切换)" :
loop_mode == 1 ? "列表循环(点击切换)" : "单曲循环(点击切换)");
}
static void update_status(void)
{
char buf[2200];
const char *base = current_file[0] ? strrchr(current_file, '\\') : NULL;
const char *name = base ? base + 1 : current_file;
if (current_file[0] == 0)
snprintf(buf, sizeof buf, "就绪 - 点击\"打开\"选择音乐或视频文件");
else if (is_playing)
snprintf(buf, sizeof buf, "正在播放: %s", name);
else if (is_paused)
snprintf(buf, sizeof buf, "已暂停: %s", name);
else
snprintf(buf, sizeof buf, "已停止: %s", name);
gtk_label_set_text(GTK_LABEL(status_label), buf);
}
static void apply_track_meta(void)
{
TrackInfo *t = current_track;
if (!t) {
gtk_label_set_text(GTK_LABEL(title_label), "未播放");
gtk_label_set_text(GTK_LABEL(sub_label), "从播放列表选择一首歌或视频");
if (cover_pixbuf) { g_object_unref(cover_pixbuf); cover_pixbuf = NULL; }
gtk_widget_queue_draw(cover_widget);
gtk_stack_set_visible_child(GTK_STACK(media_stack), cover_widget);
gtk_header_bar_set_subtitle(GTK_HEADER_BAR(headerbar), "");
gtk_label_set_text(GTK_LABEL(time_total), "00:00");
return;
}
gtk_label_set_text(GTK_LABEL(title_label), t->title);
if (t->album && t->album[0]) {
gchar *sub = g_strdup_printf("%s · %s", t->artist, t->album);
gtk_label_set_text(GTK_LABEL(sub_label), sub);
g_free(sub);
} else {
gtk_label_set_text(GTK_LABEL(sub_label), t->artist);
}
if (t->is_video) {
gtk_stack_set_visible_child(GTK_STACK(media_stack), video_area);
if (cover_pixbuf) { g_object_unref(cover_pixbuf); cover_pixbuf = NULL; }
gtk_header_bar_set_subtitle(GTK_HEADER_BAR(headerbar), "视频");
} else {
gtk_stack_set_visible_child(GTK_STACK(media_stack), cover_widget);
if (t->cover) {
if (cover_pixbuf) g_object_unref(cover_pixbuf);
cover_pixbuf = (GdkPixbuf *)g_object_ref(t->cover);
} else if (cover_pixbuf) {
g_object_unref(cover_pixbuf);
cover_pixbuf = NULL;
}
gtk_widget_queue_draw(cover_widget);
gtk_header_bar_set_subtitle(GTK_HEADER_BAR(headerbar),
t->album && t->album[0] ? t->album : t->artist);
}
{
char buf[16];
format_time(t->duration_ms, buf, sizeof buf);
gtk_label_set_text(GTK_LABEL(time_total), buf);
}
gtk_window_set_title(GTK_WINDOW(window), t->title);
}
/* ---------------- 播放控制 ---------------- */
static void apply_volume(void)
{
if (sound_mode == 1 && g_mpv_ok)
mpv_set_prop("volume", vol_value);
else if (sound_mode == 2) {
char cmd[64];
snprintf(cmd, sizeof cmd, "setaudio song volume to %d", vol_value * 10);
mci(cmd);
}
}
static int open_song(TrackInfo *t)
{
const char *path = t->path;
if (sound_mode == 2) mci("close song");
sound_mode = 0;
if (t->is_midi) {
char cmd[2600];
snprintf(cmd, sizeof cmd, "open \"%s\" type sequencer alias song", path);
if (!mci(cmd)) {
char msg[2400];
snprintf(msg, sizeof msg, "无法打开文件:\n%s\n\n该格式不受支持", path);
GtkWidget *d = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", msg);
gtk_dialog_run(GTK_DIALOG(d));
gtk_widget_destroy(d);
return 0;
}
mci("set song time format milliseconds");
sound_mode = 2;
media_length = mci_status("status song length");
if (media_length <= 0 && t->duration_ms > 0)
media_length = t->duration_ms;
} else {
if (!g_mpv_ok) {
char msg[2400];
snprintf(msg, sizeof msg, "mpv 引擎未就绪,无法播放:\n%s", path);
GtkWidget *d = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", msg);
gtk_dialog_run(GTK_DIALOG(d));
gtk_widget_destroy(d);
return 0;
}
std::string p(path);
for (size_t i = 0; i < p.size(); i++)
if (p[i] == '\\') p[i] = '/';
mpv_command(json::array({"loadfile", p, "replace"}));
sound_mode = 1;
g_media_loaded = 1;
g_mpv_eof = 0;
apply_volume();
media_length = t->duration_ms > 0 ? t->duration_ms : 0;
}
current_track = t;
strncpy(current_file, path, sizeof current_file - 1);
current_file[sizeof current_file - 1] = 0;
gtk_range_set_range(GTK_RANGE(pos_scale), 0, media_length > 0 ? media_length : 1);
gtk_range_set_value(GTK_RANGE(pos_scale), 0);
{
char b1[16], b2[16];
format_time(0, b1, sizeof b1);
format_time(media_length, b2, sizeof b2);
gtk_label_set_text(GTK_LABEL(time_cur), b1);
gtk_label_set_text(GTK_LABEL(time_total), b2);
}
apply_track_meta();
return 1;
}
static void play_song(int from_begin)
{
if (sound_mode == 1 && g_mpv_ok) {
if (!g_media_loaded && current_track) {
std::string p(current_track->path);
for (size_t i = 0; i < p.size(); i++)
if (p[i] == '\\') p[i] = '/';
mpv_command(json::array({"loadfile", p, "replace"}));
g_media_loaded = 1;
}
if (from_begin)
mpv_command(json::array({"seek", 0, "absolute"}));
mpv_set_prop("pause", false);
g_mpv_eof = 0;
} else if (sound_mode == 2) {
mci(from_begin ? "play song from 0" : "play song");
}
is_playing = 1;
is_paused = 0;
set_play_icon("media-playback-pause-symbolic");
update_status();
}
static void pause_song(void)
{
if (sound_mode == 1 && g_mpv_ok)
mpv_set_prop("pause", true);
else if (sound_mode == 2)
mci("pause song");
is_paused = 1;
set_play_icon("media-playback-start-symbolic");
update_status();
}
static void stop_song(void)
{
if (sound_mode == 1 && g_mpv_ok) {
mpv_command(json::array({"stop"}));
g_media_loaded = 0;
g_mpv_eof = 0;
} else if (sound_mode == 2) {
mci("stop song");
mci("seek song to 0");
}
is_playing = 0;
is_paused = 0;
set_play_icon("media-playback-start-symbolic");
gtk_range_set_value(GTK_RANGE(pos_scale), 0);
gtk_label_set_text(GTK_LABEL(time_cur), "00:00");
update_status();
}
/* ---------------- 播放列表 ---------------- */
static int row_index(GtkListBoxRow *row)
{
if (!row) return -1;
GList *children = gtk_container_get_children(GTK_CONTAINER(playlist_box));
int i = 0;
for (GList *l = children; l; l = l->next) {
if (l->data == (gpointer)row) {
g_list_free(children);
return i;
}
i++;
}
g_list_free(children);
return -1;
}
static void playlist_append(TrackInfo *t)
{
GtkWidget *row = gtk_list_box_row_new();
GtkWidget *h = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
gtk_widget_set_margin_start(h, 6);
gtk_widget_set_margin_end(h, 10);
gtk_widget_set_margin_top(h, 5);
gtk_widget_set_margin_bottom(h, 5);
GtkWidget *img = gtk_image_new_from_pixbuf(t->thumb ? t->thumb : placeholder_thumb);
GtkWidget *vb = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
GtkWidget *l1 = gtk_label_new(t->title);
gtk_label_set_xalign(GTK_LABEL(l1), 0.0);
gtk_label_set_ellipsize(GTK_LABEL(l1), PANGO_ELLIPSIZE_END);
gtk_widget_set_halign(l1, GTK_ALIGN_START);
gtk_style_context_add_class(gtk_widget_get_style_context(l1), "track-title");
GtkWidget *l2 = gtk_label_new(t->is_video ? "视频" : t->artist);
gtk_label_set_xalign(GTK_LABEL(l2), 0.0);
gtk_label_set_ellipsize(GTK_LABEL(l2), PANGO_ELLIPSIZE_END);
gtk_widget_set_halign(l2, GTK_ALIGN_START);
gtk_style_context_add_class(gtk_widget_get_style_context(l2), "track-artist");
gtk_box_pack_start(GTK_BOX(vb), l1, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vb), l2, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(h), img, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(h), vb, TRUE, TRUE, 0);
gtk_container_add(GTK_CONTAINER(row), h);
gtk_widget_show_all(row);
gtk_list_box_insert(GTK_LIST_BOX(playlist_box), row, -1);
playlist = g_list_append(playlist, t);
}
static void go_to_index(int idx, int autoplay)
{
GtkWidget *row = GTK_WIDGET(gtk_list_box_get_row_at_index(GTK_LIST_BOX(playlist_box), idx));
if (!row) return;
TrackInfo *t = (TrackInfo *)g_list_nth_data(playlist, idx);
if (!t) return;
current_row = GTK_LIST_BOX_ROW(row);
gtk_list_box_select_row(GTK_LIST_BOX(playlist_box), current_row);
if (open_song(t)) {
if (autoplay)
play_song(0);
else
stop_song();
}
}
/* ---------------- 信号回调 ---------------- */
static void on_open_clicked(GtkWidget *w, gpointer data)
{
GtkWidget *dlg = gtk_file_chooser_dialog_new("选择媒体文件", GTK_WINDOW(window),
GTK_FILE_CHOOSER_ACTION_OPEN,
"取消", GTK_RESPONSE_CANCEL,
"打开", GTK_RESPONSE_ACCEPT, NULL);
gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dlg), TRUE);
GtkFileFilter *f = gtk_file_filter_new();
gtk_file_filter_set_name(f, "媒体文件 (*.mp3 *.wav *.flac *.ogg *.m4a *.mp4 *.mkv *.avi ...)");
gtk_file_filter_add_pattern(f, "*.mp3");
gtk_file_filter_add_pattern(f, "*.wav");
gtk_file_filter_add_pattern(f, "*.flac");
gtk_file_filter_add_pattern(f, "*.ogg");
gtk_file_filter_add_pattern(f, "*.opus");
gtk_file_filter_add_pattern(f, "*.m4a");
gtk_file_filter_add_pattern(f, "*.aac");
gtk_file_filter_add_pattern(f, "*.wma");
gtk_file_filter_add_pattern(f, "*.mid");
gtk_file_filter_add_pattern(f, "*.midi");
gtk_file_filter_add_pattern(f, "*.mp4");
gtk_file_filter_add_pattern(f, "*.mkv");
gtk_file_filter_add_pattern(f, "*.avi");
gtk_file_filter_add_pattern(f, "*.mov");
gtk_file_filter_add_pattern(f, "*.webm");
gtk_file_filter_add_pattern(f, "*.flv");
gtk_file_filter_add_pattern(f, "*.wmv");
gtk_file_filter_add_pattern(f, "*.mpg");
gtk_file_filter_add_pattern(f, "*.mpeg");
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dlg), f);
GtkFileFilter *fall = gtk_file_filter_new();
gtk_file_filter_set_name(fall, "所有文件");
gtk_file_filter_add_pattern(fall, "*");
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dlg), fall);
if (gtk_dialog_run(GTK_DIALOG(dlg)) == GTK_RESPONSE_ACCEPT) {
GSList *files = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dlg));
for (GSList *l = files; l; l = l->next)
playlist_append(track_parse((const char *)l->data));
g_slist_free_full(files, g_free);
}
gtk_widget_destroy(dlg);
}
static void on_play_clicked(GtkWidget *w, gpointer data)
{
if (current_file[0] == 0) {
if (playlist == NULL) return;
go_to_index(0, 1);
} else if (is_playing) {
pause_song();
} else {
play_song(0);
}
}
static void on_stop_clicked(GtkWidget *w, gpointer data)
{
if (current_file[0]) stop_song();
}
static void on_loop_clicked(GtkWidget *w, gpointer data)
{
loop_mode = (loop_mode + 1) % 3;
update_loop_button();
}
static void on_prev_clicked(GtkWidget *w, gpointer data)
{
int count = g_list_length(playlist);
if (count == 0) return;
int idx = current_row ? row_index(current_row) : 0;
if (idx < 0) idx = 0;
go_to_index((idx - 1 + count) % count, 1);
}
static void on_next_clicked(GtkWidget *w, gpointer data)
{
int count = g_list_length(playlist);
if (count == 0) return;
int idx = current_row ? row_index(current_row) : -1;
go_to_index((idx + 1) % count, 1);
}
static void on_row_activated(GtkListBox *box, GtkListBoxRow *row, gpointer data)
{
current_row = row;
int idx = row_index(row);
if (idx >= 0 && open_song((TrackInfo *)g_list_nth_data(playlist, idx)))
play_song(0);
}
static void on_vol_changed(GtkRange *range, gpointer data)
{
vol_value = (int)gtk_range_get_value(range);
apply_volume();
}
static gboolean on_pos_press(GtkWidget *w, GdkEventButton *ev, gpointer data)
{
seeking = 1;
return FALSE;
}
static gboolean on_pos_release(GtkWidget *w, GdkEventButton *ev, gpointer data)
{
seeking = 0;
if (current_file[0] == 0) return FALSE;
long ms = (long)gtk_range_get_value(GTK_RANGE(pos_scale));
if (sound_mode == 1 && g_mpv_ok && g_media_loaded) {
mpv_command(json::array({"seek", ms / 1000.0, "absolute"}));
} else if (sound_mode == 2) {
char cmd[64];
snprintf(cmd, sizeof cmd, "seek song to %ld", ms);
mci(cmd);
if (is_playing)
mci("play song");
else if (is_paused) {
mci("play song");
mci("pause song");
}
}
return FALSE;
}
static gboolean on_tick(gpointer data)
{
mpv_drain();
if (sound_mode == 1 && g_mpv_ok) {
long pos_ms = (long)(g_mpv_pos * 1000.0);
if (!seeking && media_length > 0)
gtk_range_set_value(GTK_RANGE(pos_scale), pos_ms < media_length ? pos_ms : media_length);
{
char b1[16], b2[16];
format_time(pos_ms, b1, sizeof b1);
format_time(media_length, b2, sizeof b2);
gtk_label_set_text(GTK_LABEL(time_cur), b1);
gtk_label_set_text(GTK_LABEL(time_total), b2);
}
if (is_playing && g_mpv_eof) {
int count = g_list_length(playlist);
if (loop_mode == 2) {
g_mpv_eof = 0;
play_song(1);
} else {
int idx = current_row ? row_index(current_row) : -1;
int next = idx + 1;
if (next < count)
go_to_index(next, 1);
else if (loop_mode == 1)
go_to_index(0, 1);
else
stop_song();
}
}
} else if (sound_mode == 2) {
long pos = mci_status("status song position");
if (!seeking && media_length > 0)
gtk_range_set_value(GTK_RANGE(pos_scale), pos < media_length ? pos : media_length);
{
char b1[16], b2[16];
format_time(pos, b1, sizeof b1);
format_time(media_length, b2, sizeof b2);
gtk_label_set_text(GTK_LABEL(time_cur), b1);
gtk_label_set_text(GTK_LABEL(time_total), b2);
}
if (is_playing && media_length > 0 && pos >= media_length - 250) {
int count = g_list_length(playlist);
if (loop_mode == 2) {
play_song(1);
} else {
int idx = current_row ? row_index(current_row) : -1;
int next = idx + 1;
if (next < count)
go_to_index(next, 1);
else if (loop_mode == 1)
go_to_index(0, 1);
else
stop_song();
}
}
}
return G_SOURCE_CONTINUE;
}
/* ---------------- 封面绘制 ---------------- */
static void rounded_rect(cairo_t *cr, double x, double y, double w, double h, double r)
{
cairo_new_path(cr);
cairo_arc(cr, x + r, y + r, r, G_PI, 3 * G_PI / 2);
cairo_arc(cr, x + w - r, y + r, r, 3 * G_PI / 2, 2 * G_PI);
cairo_arc(cr, x + w - r, y + h - r, r, 0, G_PI / 2);
cairo_arc(cr, x + r, y + h - r, r, G_PI / 2, G_PI);
cairo_close_path(cr);
}
static gboolean on_cover_draw(GtkWidget *w, cairo_t *cr, gpointer data)
{
GtkAllocation a;
gtk_widget_get_allocation(w, &a);
double W = a.width, H = a.height, r = 16.0;
rounded_rect(cr, 0.5, 0.5, W - 1, H - 1, r);
cairo_clip(cr);
if (cover_pixbuf) {
int iw = gdk_pixbuf_get_width(cover_pixbuf);
int ih = gdk_pixbuf_get_height(cover_pixbuf);
double s = MAX(W / iw, H / ih);
cairo_save(cr);
cairo_translate(cr, W / 2, H / 2);
cairo_scale(cr, s, s);
cairo_translate(cr, -iw / 2.0, -ih / 2.0);
gdk_cairo_set_source_pixbuf(cr, cover_pixbuf, 0, 0);
cairo_paint(cr);
cairo_restore(cr);
} else {
cairo_pattern_t *grad = cairo_pattern_create_linear(0, 0, 0, H);
cairo_pattern_add_color_stop_rgb(grad, 0, 0.24, 0.24, 0.28);
cairo_pattern_add_color_stop_rgb(grad, 1, 0.13, 0.13, 0.16);
cairo_set_source(cr, grad);
cairo_paint(cr);
cairo_pattern_destroy(grad);
cairo_set_source_rgba(cr, 1, 1, 1, 0.20);
cairo_select_font_face(cr, "Segoe UI Symbol", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, W * 0.5);
cairo_text_extents_t te;
cairo_text_extents(cr, "\xe2\x99\xab", &te);
cairo_move_to(cr, (W - te.width) / 2 - te.x_bearing, (H - te.height) / 2 - te.y_bearing);
cairo_show_text(cr, "\xe2\x99\xab");
}
rounded_rect(cr, 0.5, 0.5, W - 1, H - 1, r);
cairo_set_source_rgba(cr, 1, 1, 1, 0.10);
cairo_set_line_width(cr, 1.0);
cairo_stroke(cr);
return FALSE;
}
/* ---------------- 打包运行环境 ---------------- */
static void setup_bundle_env(void)
{
wchar_t buf[MAX_PATH];
GetModuleFileNameW(NULL, buf, MAX_PATH);
wchar_t *slash = wcsrchr(buf, L'\\');
if (!slash) return;
*slash = L'\0';
gchar *dir = g_utf16_to_utf8((const gunichar2 *)buf, -1, NULL, NULL, NULL);
if (!dir) return;
gchar *p = g_build_filename(dir, "lib", "gdk-pixbuf-2.0", "2.10.0", "loaders.cache", NULL);
if (g_file_test(p, G_FILE_TEST_EXISTS))
g_setenv("GDK_PIXBUF_MODULE_FILE", p, TRUE);
g_free(p);
p = g_build_filename(dir, "share", "glib-2.0", "schemas", NULL);
if (g_file_test(p, G_FILE_TEST_IS_DIR))
g_setenv("GSETTINGS_SCHEMA_DIR", p, TRUE);
g_free(p);
p = g_build_filename(dir, "etc", "fonts", NULL);
if (g_file_test(p, G_FILE_TEST_IS_DIR))
g_setenv("FONTCONFIG_PATH", p, TRUE);
g_free(p);
g_free(dir);
}
/* ---------------- 主程序 ---------------- */
static void activate(GtkApplication *app, gpointer data)
{
g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", TRUE, NULL);
GtkCssProvider *css = gtk_css_provider_new();
const gchar *css_data =
"window.player-window { background-color: #1d1d21; }\n"
"headerbar { background-color: #232327; border-bottom: 1px solid #2f2f35; box-shadow: none; }\n"
"headerbar .title { color: #f6f6f8; }\n"
"headerbar .subtitle { color: #9a9aa2; }\n"
"list { background-color: transparent; }\n"
"list row { border-radius: 10px; margin: 1px 2px; }\n"
"list row:hover { background-color: rgba(255,255,255,0.06); }\n"
"scrolledwindow { background-color: transparent; }\n"
".song-title { font-size: 19px; font-weight: 700; color: #f6f6f8; }\n"
".song-sub { font-size: 13px; color: #9a9aa2; }\n"
".track-title { font-size: 13px; font-weight: 600; color: #e8e8ec; }\n"
".track-artist { font-size: 11px; color: #9a9aa2; }\n"
".time-label { font-size: 11px; color: #9a9aa2; }\n"
".status-label { font-size: 11px; color: #7a7a82; }\n"
"scale trough { min-height: 4px; border-radius: 2px; background-color: #3a3a42; }\n"
"scale highlight { border-radius: 2px; background-color: #3584e4; }\n"
"scale slider { background-color: #3584e4; }\n"
"button.suggested-action { background-color: #3584e4; }\n"
"button.suggested-action:hover { background-color: #4d94e8; }\n";
gtk_css_provider_load_from_data(css, css_data, -1, NULL);
gtk_style_context_add_provider_for_screen(gdk_screen_get_default(),
GTK_STYLE_PROVIDER(css), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
g_object_unref(css);
window = gtk_application_window_new(app);
gtk_window_set_default_size(GTK_WINDOW(window), 480, 760);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_style_context_add_class(gtk_widget_get_style_context(window), "player-window");
gtk_window_set_icon_name(GTK_WINDOW(window), "multimedia-player");
/* HeaderBar */
headerbar = gtk_header_bar_new();
gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(headerbar), TRUE);
gtk_header_bar_set_title(GTK_HEADER_BAR(headerbar), "音乐播放器");