Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
3504 lines (3321 loc) · 171 KB
/
Copy pathapp.js
File metadata and controls
3504 lines (3321 loc) · 171 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
import { kv } from './db.js';
/* ================= util ================= */
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
const enc = encodeURIComponent;
const fmt = (s) => {
if (!isFinite(s) || s < 0) s = 0;
s = Math.floor(s);
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), x = String(s % 60).padStart(2, '0');
return h ? `${h}:${String(m).padStart(2, '0')}:${x}` : `${m}:${x}`;
};
const fmtLong = (s) => {
const m = Math.max(1, Math.round(s / 60));
return m < 60 ? `${m} menit` : `${Math.floor(m / 60)} jam ${m % 60} menit`;
};
const shuffled = (a) => {
a = [...a];
for (let i = a.length - 1; i > 0; i--) {
const j = (Math.random() * (i + 1)) | 0;
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
const debounce = (fn, ms) => {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
};
const nf = new Intl.NumberFormat('id-ID');
const dateFmt = new Intl.DateTimeFormat('id-ID', { day: 'numeric', month: 'short', year: 'numeric' });
const ANDROID = /SvaraAndroid/.test(navigator.userAgent);
// Mode ringan: efek berat (blur, animasi, visualizer spektrum) dimatiin. Otomatis di app Android dan
// perangkat spek rendah; bisa dipaksa nyala/mati dari panel Suara (disimpan di localStorage 'svara-lite').
const litePref = () => { try { return localStorage.getItem('svara-lite') || 'auto'; } catch { return 'auto'; } };
const liteAuto = ANDROID || (navigator.deviceMemory || 8) <= 4 || (navigator.hardwareConcurrency || 8) <= 4;
let LITE = litePref() === 'auto' ? liteAuto : litePref() === 'on';
document.documentElement.classList.toggle('lite', LITE);
function setLite(on) {
try { on === liteAuto ? localStorage.removeItem('svara-lite') : localStorage.setItem('svara-lite', on ? 'on' : 'off'); } catch {}
LITE = on;
document.documentElement.classList.toggle('lite', LITE);
}
const motionMq = matchMedia('(prefers-reduced-motion: reduce)');
// Di mode ringan animasi hiasan ikut dimatiin, sama kayak "kurangi gerakan" di sistem
const reduceMotion = { get matches() { return LITE || motionMq.matches; } };
const isMobile = () => matchMedia('(max-width: 760px)').matches;
function hashStr(s) {
let h = 5381;
for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
return h.toString(36);
}
async function api(path, opts) {
const r = await fetch(path, opts);
const d = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(d.error || `Error ${r.status}`);
return d;
}
// Semua gambar lewat proxy lokal: di-cache dan warnanya bisa dibaca canvas
const img = (u) => (!u ? null : u.startsWith('/') ? u : /googleusercontent|ytimg|ggpht|mzstatic/.test(u) ? `/api/yt/img?u=${enc(u)}` : `/api/pod/img?u=${enc(u)}`);
/* ================= ikon ================= */
// Ikon vektor 24×24: garis membulat (o) atau isi penuh (f)
const o = (body) => `<svg viewBox="0 0 24 24" class="ic" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
const f = (body) => `<svg viewBox="0 0 24 24" class="ic" fill="currentColor" aria-hidden="true">${body}</svg>`;
const REPEAT = '<path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/>';
const HEART = '<path d="M19 14c1.5-1.5 3-3.2 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.8 0-3 .5-4.5 2-1.5-1.5-2.7-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4 3 5.5l7 7z"/>';
const BOOK = '<path d="M19 21l-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>';
const SPEAKER = '<path d="M11 5 6 9H3v6h3l5 4z"/>';
const I = {
play: f('<path d="M7 4.8v14.4a1.2 1.2 0 0 0 1.8 1l11.6-7.2a1.2 1.2 0 0 0 0-2L8.8 3.8A1.2 1.2 0 0 0 7 4.8z"/>'),
pause: f('<rect x="5.5" y="4" width="4.5" height="16" rx="1.4"/><rect x="14" y="4" width="4.5" height="16" rx="1.4"/>'),
next: f('<path d="M4.5 5.6v12.8a1.1 1.1 0 0 0 1.7.9l9.4-6.4a1.1 1.1 0 0 0 0-1.8L6.2 4.7a1.1 1.1 0 0 0-1.7.9z"/><rect x="17" y="4.5" width="2.6" height="15" rx="1.3"/>'),
prev: f('<path d="M19.5 5.6v12.8a1.1 1.1 0 0 1-1.7.9l-9.4-6.4a1.1 1.1 0 0 1 0-1.8l9.4-6.4a1.1 1.1 0 0 1 1.7.9z"/><rect x="4.4" y="4.5" width="2.6" height="15" rx="1.3"/>'),
shuffle: o('<path d="M2 18h1.4c1.3 0 2.5-.6 3.3-1.7l6.1-8.6c.7-1.1 2-1.7 3.3-1.7H22"/><path d="m18 2 4 4-4 4"/><path d="M2 6h1.9c1.5 0 2.9.9 3.6 2.2"/><path d="M22 18h-5.9c-1.3 0-2.6-.7-3.3-1.8l-.5-.8"/><path d="m18 14 4 4-4 4"/>'),
repeat: o(REPEAT),
repeat1: o(REPEAT + '<path d="M11 10h1v4"/>'),
vol: o(SPEAKER + '<path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M18.5 5.5a9.5 9.5 0 0 1 0 13"/>'),
mute: o(SPEAKER + '<path d="m22 9-6 6"/><path d="m16 9 6 6"/>'),
queue: o('<path d="M3 6h13"/><path d="M3 12h9"/><path d="M3 18h9"/><path d="M20 15V5l2 1"/><circle cx="17.5" cy="17.5" r="2.5"/>'),
lyrics: o('<path d="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M8 8h8"/><path d="M8 12h5"/>'),
heart: o(HEART),
heartF: f(HEART),
more: f('<circle cx="5" cy="12" r="1.9"/><circle cx="12" cy="12" r="1.9"/><circle cx="19" cy="12" r="1.9"/>'),
down: o('<path d="m6 9 6 6 6-6"/>'),
x: o('<path d="M18 6 6 18"/><path d="m6 6 12 12"/>'),
note: o('<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>'),
user: o('<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>'),
save: o('<path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/>'),
check: o('<path d="M20 6 9 17l-5-5"/>'),
search: o('<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>'),
plus: o('<path d="M12 5v14"/><path d="M5 12h14"/>'),
mic: o('<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><path d="M12 18v4"/>'),
book: o(BOOK),
bookF: f(BOOK),
arrow: o('<path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>'),
home: o('<path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z"/>'),
lib: o('<path d="M5 4v16"/><path d="M10 4v16"/><path d="m14.5 4.5 4.5 15"/>'),
side: o('<rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/>'),
full: o('<path d="M15 3h6v6"/><path d="M9 21H3v-6"/><path d="m21 3-7 7"/><path d="m3 21 7-7"/>'),
moon: o('<path d="M20.5 14.5A8.5 8.5 0 1 1 9.5 3.5a6.5 6.5 0 0 0 11 11z"/>'),
clock: o('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),
sun: o('<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.9 4.9 1.4 1.4"/><path d="m17.7 17.7 1.4 1.4"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.3 17.7-1.4 1.4"/><path d="m19.1 4.9-1.4 1.4"/>'),
contrast: o('<circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/>'),
trash: o('<path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v5"/><path d="M14 11v5"/>'),
edit: o('<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/>'),
disc: o('<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="2.5"/>'),
panel: o('<rect x="3" y="4" width="18" height="16" rx="3"/><path d="M9 4v16"/>'),
share: o('<path d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7"/><path d="m16 6-4-4-4 4"/><path d="M12 2v13"/>'),
pip: o('<rect x="2" y="4" width="20" height="16" rx="2.5"/><rect x="12" y="11" width="7" height="6" rx="1.2" fill="currentColor" stroke="none"/>'),
copy: o('<rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>'),
sliders: o('<path d="M4 21v-7"/><path d="M4 10V3"/><path d="M12 21v-9"/><path d="M12 8V3"/><path d="M20 21v-5"/><path d="M20 12V3"/><path d="M2 14h4"/><path d="M10 8h4"/><path d="M18 16h4"/>'),
stats: o('<path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M7 16V12"/><path d="M12 16V8"/><path d="M17 16v-5"/>'),
fire: o('<path d="M12 22c4 0 7-2.7 7-7 0-4-3-6-4-9-1 2-2 3-4 3 1-3 0-5-2-7 0 4-5 6-5 12 0 4.3 3 8 8 8z"/>'),
keys: o('<rect x="2" y="6" width="20" height="12" rx="2.5"/><path d="M6 10h.01"/><path d="M10 10h.01"/><path d="M14 10h.01"/><path d="M18 10h.01"/><path d="M7 14h10"/>'),
};
const EQ = '<span class="eq"><i></i><i></i><i></i></span>';
/* ================= state ================= */
const S = {
tr: new Map(), // id -> lagu/episode
coll: {}, // id -> metadata album/playlist/artis/podcast
browse: new Map(),
feed: null,
feedErr: null,
feedLoading: false,
search: {},
lists: {},
listSeq: 0,
playlists: [],
loved: new Set(),
plays: {},
savedColl: [],
subs: [],
podMeta: {},
podShows: new Map(),
podLoading: new Map(),
podLimit: {},
podTop: null,
podTopLoading: false,
podErr: null,
podpos: {},
podDone: new Set(),
rate: 1,
offline: null,
savedVids: new Set(),
saving: new Set(),
recentQ: [],
queue: [],
base: [],
idx: -1,
shuffle: false,
repeat: 'off',
volume: 80,
restorePos: 0,
panel: null,
lyr: null,
lyrCache: new Map(),
serverOk: null,
autoplay: true,
radio: true,
radioIds: new Set(),
sleep: null,
log: [], // riwayat dengerin: [waktu, id, detik]
smartIds: new Set(), // lagu sisipan smart shuffle
skips: {}, // id -> berapa kali di-skip cepat
};
/* ---------- mesin audio: dua elemen, biar bisa crossfade & gapless ---------- */
// Lagu berikutnya disiapin di elemen cadangan, terus tinggal "tukar" pas pindah lagu.
const AUD = [$('#audio'), $('#audio2')];
let audio = AUD[0];
const standby = () => (audio === AUD[0] ? AUD[1] : AUD[0]);
// Event cuma diurus buat elemen yang lagi jadi pemutar utama
const onAudio = (ev, fn) => AUD.forEach((el) => el.addEventListener(ev, (e) => { if (e.target === audio) fn(e); }));
// iOS nggak ngizinin volume elemen diatur (dan elemen kedua bisa diblok di latar), jadi di sana pakai satu elemen aja
const DUAL = (() => { const a = document.createElement('audio'); a.volume = 0.5; return a.volume === 0.5; })();
const FX = { xf: 0, eq: 'flat', bands: [0, 0, 0, 0, 0] };
let sleepMul = 1, fadeIn = 1, ghost = null, xfT = 0, xfNow = false;
const userVol = () => (S.volume / 100) ** 2 * sleepMul;
function setElVol(el, v) {
v = Math.max(0, Math.min(1, v));
if (el._g) { el.volume = 1; el._g.gain.value = v; } else el.volume = v;
}
const applyVol = () => setElVol(audio, userVol() * fadeIn);
function dropEl(el) {
el.pause();
el._id = null;
el.removeAttribute('src');
el.load();
}
// Lagu lama pelan-pelan turun, lagu baru pelan-pelan naik (kurva equal-power biar nggak ada "lubang" di tengah)
function crossfadeFrom(old, dur) {
endFade();
ghost = old;
const t0 = performance.now();
fadeIn = 0;
applyVol();
xfT = setInterval(() => {
const p = Math.min(1, (performance.now() - t0) / (dur * 1000));
if (ghost) setElVol(ghost, userVol() * Math.cos((p * Math.PI) / 2));
fadeIn = Math.sin((p * Math.PI) / 2);
applyVol();
if (p >= 1 || !ghost) endFade();
}, 40);
}
function endFade() {
clearInterval(xfT);
xfT = 0;
fadeIn = 1;
applyVol();
if (ghost) { const g = ghost; ghost = null; dropEl(g); }
}
function pauseAll() {
endFade();
audio.pause();
}
function upcoming() {
if (S.repeat === 'one' || S.sleep?.endOfTrack) return null;
const id = S.idx + 1 < S.queue.length ? S.queue[S.idx + 1] : S.repeat === 'all' ? S.queue[0] : null;
return T(id)?.kind === 'song' ? id : null;
}
// Dipanggil tiap timeupdate: siapin lagu berikutnya ~25 detik sebelum habis, lalu mulai crossfade
function xfTick(c, d) {
// audio._id beda = lagi di tengah pindah lagu; jangan ganggu elemen cadangan
if (!DUAL || audio.paused || ghost || !d || audio._id !== S.queue[S.idx] || cur()?.kind !== 'song') return;
const left = d - c;
const id = upcoming();
if (!id || left > FX.xf + 25) return;
const sb = standby();
if (sb._id !== id) { sb._id = id; sb.preload = 'auto'; sb.muted = audio.muted; sb.src = `/api/yt/stream/${T(id).vid}`; }
if (FX.xf > 0 && left <= FX.xf && left > 0.5 && d > FX.xf * 2 + 10 && sb.readyState >= 3 && !sb.error) { xfNow = true; next(true); }
}
/* ---------- equalizer (Web Audio, baru dinyalain kalau dipakai) ---------- */
const BANDS = [[60, 'lowshelf', '60'], [230, 'peaking', '230'], [910, 'peaking', '910'], [3600, 'peaking', '3.6k'], [14000, 'highshelf', '14k']];
const EQ_PRESETS = {
flat: ['Datar', [0, 0, 0, 0, 0]],
bass: ['Bass Boost', [7, 4, 0, 0, 1]],
vocal: ['Vokal', [-2, -1, 3, 4, 1]],
acoustic: ['Akustik', [3, 1, 1, 3, 3]],
electro: ['Elektronik', [5, 2, -2, 2, 5]],
rock: ['Rock', [4, 2, -1, 2, 4]],
night: ['Malam', [2, 1, 0, -2, -4]],
treble: ['Treble', [-1, 0, 0, 3, 6]],
};
let actx = null, eqF = [], preG = null, anl = null, anBuf = null;
for (const ev of ['pointerdown', 'keydown']) document.addEventListener(ev, () => { if (!actx && !audio.paused) wakeGraph(); }, { capture: true, passive: true });
/* ---------- visualizer: gelombang spektrum beneran, bagian yang udah lewat diwarnai ---------- */
const VIZ_N = 72;
let vizRaf = 0, vizV = null, vizCol = null, vizColAt = 0;
function vizStart() { if (!vizRaf) vizRaf = requestAnimationFrame(vizFrame); }
let vizLast = 0;
function vizFrame(now) {
vizRaf = 0;
if (LITE && now - vizLast < 40) { if (!audio.paused) vizRaf = requestAnimationFrame(vizFrame); return; }
vizLast = now;
const cvs = $$('canvas.spec').filter((c) => (c.closest('#np') ? npOpen() : c.offsetParent !== null));
if (pipWin) cvs.push(...pipWin.document.querySelectorAll('canvas.spec'));
if (!cvs.length && !npOpen()) return;
vizV ||= new Float32Array(VIZ_N);
if (!vizCol || now - vizColAt > 1000) {
const cs = getComputedStyle(document.documentElement);
vizCol = ['--viz-a', '--coral', '--viz-b', '--fg'].map((k) => cs.getPropertyValue(k).trim());
vizColAt = now;
}
const playing = !audio.paused;
const live = playing && anl && actx?.state === 'running';
if (live) anl.getByteFrequencyData(anBuf);
const binHz = (actx?.sampleRate || 48000) / 2048;
let energy = 0;
for (let i = 0; i < VIZ_N; i++) {
let t = 0;
if (live) {
// Frekuensi disebar logaritmik (40 Hz - 15 kHz), kayak telinga dengerin
const f0 = 40 * 375 ** (i / VIZ_N), f1 = 40 * 375 ** ((i + 1) / VIZ_N);
let m = 0;
for (let b = Math.floor(f0 / binHz); b <= Math.ceil(f1 / binHz); b++) m = Math.max(m, anBuf[b] || 0);
// Bass biasanya paling keras: diredam dikit, treble didongkrak biar seimbang
t = Math.min(0.95, (m / 255) ** 1.8 * (0.5 + (i / VIZ_N) * 1.1));
} else if (playing) {
t = 0.18 + 0.32 * Math.abs(Math.sin(i * 0.45 + now / 260) * Math.sin(i * 0.13 - now / 610));
}
vizV[i] += (t - vizV[i]) * (t > vizV[i] ? 0.55 : 0.14);
energy += vizV[i];
}
const d = durNow(), prog = d ? Math.min(1, posNow() / d) : 0;
for (const c of cvs) drawWave(c, prog);
beatTick(now, live);
if (npOpen() && !LITE) drawRing();
hhFrame(now, live);
if (playing || energy > 0.05) vizRaf = requestAnimationFrame(vizFrame);
}
// Bar spektrum yang tumbuh keluar dari keempat sisi cover di layar penuh, warnanya dari cover
let ringPal = null, ringPalU = '';
function drawRing() {
const c = $('.np-ring'), art = $('.np-art');
if (!c || !art) return;
const t = cur();
if (t?.art !== ringPalU) { ringPalU = t?.art || ''; ringPal = null; if (t?.art) palette(t.art).then((p) => { if (ringPalU === t.art) ringPal = p; }); }
const dpr = devicePixelRatio || 1, cr = c.getBoundingClientRect(), ar = art.getBoundingClientRect();
if (!cr.width || !ar.width) return;
if (c.width !== Math.round(cr.width * dpr)) { c.width = Math.round(cr.width * dpr); c.height = Math.round(cr.height * dpr); }
const x = c.getContext('2d');
x.setTransform(dpr, 0, 0, dpr, 0, 0);
x.clearRect(0, 0, cr.width, cr.height);
const S0 = ar.width, gap = 12, x0 = ar.left - cr.left - gap, y0 = ar.top - cr.top - gap, side = S0 + gap * 2;
const cx = x0 + side / 2, cy = y0 + side / 2, maxL = Math.min(70, S0 * 0.16);
const [c1, c2, c3] = ringPal || [vizCol[0], vizCol[1], vizCol[2]];
const g = x.createConicGradient(-Math.PI / 2, cx, cy);
g.addColorStop(0, c1); g.addColorStop(0.33, c2); g.addColorStop(0.66, c3); g.addColorStop(1, c1);
x.strokeStyle = g;
x.lineCap = 'round';
x.lineWidth = Math.max(2.5, side / 150);
const n = 112;
for (let k = 0; k < n; k++) {
const pos = k / n;
// spektrum dicerminkan biar simetris; bass di tengah sisi atas, sisi bawah dipendekin biar nggak nimpa judul
const m = 1 - Math.abs(((pos - 0.125 + 1) % 1) * 2 - 1);
const v = vizV[Math.floor(m * (VIZ_N - 1) * 0.75)];
const tt = pos * 4, sd = Math.floor(tt), u = tt - sd;
const L = 3 + v * maxL * (sd === 2 ? 0.35 : 1);
let px, py, nx, ny;
if (sd === 0) { px = x0 + u * side; py = y0; nx = 0; ny = -1; }
else if (sd === 1) { px = x0 + side; py = y0 + u * side; nx = 1; ny = 0; }
else if (sd === 2) { px = x0 + side - u * side; py = y0 + side; nx = 0; ny = 1; }
else { px = x0; py = y0 + side - u * side; nx = -1; ny = 0; }
x.globalAlpha = 0.35 + v * 0.65;
x.beginPath();
x.moveTo(px, py);
x.lineTo(px + nx * L, py + ny * L);
x.stroke();
}
x.globalAlpha = 1;
}
function drawWave(c, prog) {
const dpr = devicePixelRatio || 1, w = c.clientWidth, h = c.clientHeight;
if (!w || !h) return;
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); }
const x = c.getContext('2d');
x.setTransform(dpr, 0, 0, dpr, 0, 0);
x.clearRect(0, 0, w, h);
// Bar tipis membulat, simetris atas-bawah; yang udah lewat pakai gradasi, sisanya pudar
const n = Math.max(24, Math.min(VIZ_N, Math.floor(w / 6)));
const step = w / n, bw = Math.max(2, step * 0.5), mid = h / 2;
const g = x.createLinearGradient(0, 0, w, 0);
g.addColorStop(0, vizCol[0]);
g.addColorStop(0.5, vizCol[1]);
g.addColorStop(1, vizCol[2]);
const px = w * prog;
for (let k = 0; k < n; k++) {
const v = vizV[Math.floor((k / n) * VIZ_N)];
const bh = Math.max(bw, v * (h - 2));
const bx = k * step + (step - bw) / 2;
const on = bx + bw / 2 <= px;
x.globalAlpha = on ? 1 : 0.22;
x.fillStyle = on ? g : vizCol[3];
x.beginPath();
x.roundRect(bx, mid - bh / 2, bw, bh, bw / 2);
x.fill();
}
x.globalAlpha = 1;
}
const eqOn = () => FX.bands.some((x) => x);
function graph() {
if (actx) return actx;
const C = window.AudioContext || window.webkitAudioContext;
if (!C) return null;
try {
const ctx = new C();
const srcs = AUD.map((el) => ctx.createMediaElementSource(el));
preG = ctx.createGain();
eqF = BANDS.map(([f, type]) => { const b = ctx.createBiquadFilter(); b.type = type; b.frequency.value = f; b.Q.value = 1.1; return b; });
anl = ctx.createAnalyser();
anl.fftSize = 2048;
anl.smoothingTimeConstant = 0.72;
anBuf = new Uint8Array(anl.frequencyBinCount);
[preG, ...eqF, anl].reduce((a, b) => (a.connect(b), b)).connect(ctx.destination);
AUD.forEach((el, i) => { el._g = ctx.createGain(); srcs[i].connect(el._g); el._g.connect(preG); });
actx = ctx;
} catch { return null; }
applyEq();
applyVol();
return actx;
}
function applyEq() {
if (!actx) return;
const t = actx.currentTime;
eqF.forEach((b, i) => b.gain.setTargetAtTime(FX.bands[i], t, 0.04));
// Turunin sedikit gain depan biar band yang di-boost nggak bikin pecah
preG.gain.setTargetAtTime(10 ** ((-Math.max(0, ...FX.bands) * 0.6) / 20), t, 0.04);
}
// Graph Web Audio harus dibikin pas ada interaksi user, kalau nggak AudioContext-nya ketahan (suspended) dan jadi senyap
// Di desktop graph selalu dipakai (buat visualizer); di iOS cuma kalau EQ nyala
function wakeGraph() {
if (((DUAL && !LITE) || eqOn()) && !actx && (navigator.userActivation?.hasBeenActive ?? true)) graph();
if (actx?.state === 'suspended') actx.resume().catch(() => {});
}
const T = (id) => S.tr.get(id);
const cur = () => T(S.queue[S.idx]);
/* ================= data lagu ================= */
function song(x) {
const id = `yt:${x.vid}`;
const o = T(id) || {};
const t = {
id, kind: 'song', vid: x.vid, title: x.title || o.title || 'Tanpa judul',
artist: x.artist || o.artist || '', artistId: x.artistId || o.artistId || '',
album: x.album || o.album || '', albumId: x.albumId || o.albumId || '',
duration: x.duration || o.duration || 0, raw: x.art || o.raw || '', art: img(x.art) || o.art || null,
};
S.tr.set(id, t);
return t;
}
function ytEp(x, show = {}) {
const id = `yt:${x.vid}`;
const o = T(id) || {};
const t = {
id, kind: 'pod', vid: x.vid, src: `/api/yt/stream/${x.vid}`, title: x.title || o.title || 'Episode',
artist: x.artist || show.title || o.artist || 'Podcast', showHref: show.id ? `#/c/${enc(show.id)}` : x.showId ? `#/c/${enc(x.showId)}` : o.showHref || '', views: x.views || o.views || '',
dateText: x.date || o.dateText || '', desc: x.desc || o.desc || '', duration: x.duration || o.duration || 0, raw: x.art || o.raw || '', art: img(x.art) || o.art || null,
};
S.tr.set(id, t);
return t;
}
function itemId(x, show) {
if (x.type === 'song') return song(x).id;
if (x.type === 'episode') return ytEp(x, show).id;
return null;
}
function rememberColl(x) {
if (!x?.id) return;
const o = S.coll[x.id] || {};
S.coll[x.id] = { id: x.id, type: x.type || o.type, title: x.title || o.title, sub: x.sub ?? o.sub ?? '', art: x.art || o.art || '' };
}
const saveTracks = debounce(() => {
const used = new Set([...S.queue, ...S.base, ...S.loved, ...S.playlists.flatMap((p) => p.ids), ...Object.keys(S.plays), ...Object.keys(S.podpos), ...S.podDone]);
kv.set('tracks', [...S.tr.values()].filter((t) => used.has(t.id)));
}, 700);
/* ================= warna cover ================= */
const artColors = new Map();
const artLoads = new Map();
function avgColor(src) {
const c = new OffscreenCanvas(24, 24);
const x = c.getContext('2d', { willReadFrequently: true });
x.drawImage(src, 0, 0, 24, 24);
const px = x.getImageData(0, 0, 24, 24).data;
let r = 0, g = 0, b = 0, w = 0;
for (let i = 0; i < px.length; i += 4) {
const mx = Math.max(px[i], px[i + 1], px[i + 2]), mn = Math.min(px[i], px[i + 1], px[i + 2]);
const wt = ((mx - mn) / 255) * (mx / 255) + 0.04;
r += px[i] * wt; g += px[i + 1] * wt; b += px[i + 2] * wt; w += wt;
}
return [r / w, g / w, b / w].map(Math.round);
}
function artLoad(u) {
if (!u) return Promise.resolve(null);
if (artLoads.has(u)) return artLoads.get(u);
const p = new Promise((res) => {
const im = new Image();
im.onload = () => { try { artColors.set(u, avgColor(im)); } catch {} res(u); };
im.onerror = () => res(null);
im.src = u;
});
artLoads.set(u, p);
return p;
}
// Warna placeholder yang konsisten per lagu/gambar selagi cover belum kemuat
const hue = (x) => { let h = 2166136261; for (let i = 0; i < x.length; i++) h = Math.imul(h ^ x.charCodeAt(i), 16777619) >>> 0; return h % 360; };
const cover = (u, cls = '', seed = u) =>
`<div class="cover ${cls}"${seed ? ` style="--h:${hue(seed)}"` : ''}>${cls.includes('round') ? I.user : I.note}${u ? `<img src="${esc(u)}" alt="" loading="lazy" decoding="async" onload="this.classList.add('ok')">` : ''}</div>`;
/* ================= pemutar ================= */
let counted = false;
function load(i, play = true, at = 0) {
if (i < 0 || i >= S.queue.length) return;
S.idx = i;
const t = cur();
$('#lcd').classList.add('loading');
renderBar();
// Reset tampilan waktu ke lagu BARU, biar durasi lagu sebelumnya nggak nyangkut
// (dulu left/cur cuma diupdate pas timeupdate, jadi sempat nampilin waktu lagu lama)
const nd = t?.duration || 0;
setSeek(nd ? (at / nd) * 1000 : 0);
$$('[data-np=cur]').forEach((e) => (e.textContent = fmt(at)));
$$('[data-np=left]').forEach((e) => (e.textContent = nd ? fmt(nd) : '--:--'));
markPlaying();
renderQueue();
loadLyrics();
const sb = standby();
const fade = xfNow;
xfNow = false;
if (DUAL && t.kind === 'song' && !at && sb._id === t.id && sb.getAttribute('src') && !sb.error) {
// Udah kebuffer di elemen cadangan: tukar, langsung bunyi tanpa jeda
const old = audio;
endFade();
audio = sb;
audio.muted = old.muted;
if (audio.currentTime > 0.5) audio.currentTime = 0;
if (fade && !old.paused && FX.xf > 0) crossfadeFrom(old, FX.xf);
else { dropEl(old); applyVol(); }
metaFix();
} else {
endFade();
if (t.kind === 'pod') {
audio.src = t.src;
// Podcast lanjut dari menit terakhir
if (!at && !S.podDone.has(t.id)) at = S.podpos[t.id] || 0;
} else {
audio.src = `/api/yt/stream/${t.vid}`;
}
}
audio._id = t.id;
counted = false;
audio.defaultPlaybackRate = audio.playbackRate = t.kind === 'pod' ? S.rate : 1;
if (at) audio.currentTime = at;
S.restorePos = 0;
if (play) audio.play().catch(() => {});
setMediaSession(t);
saveState();
saveTracks();
flipArt();
loadChips();
updateHomeHero();
}
function playFrom(ids, i = 0, shuffle = false, srcName) {
ids = ids.filter((id) => T(id));
if (!ids.length) return;
S.src = { mix: false, name: srcName || pageSrcName(), chip: '' };
if (shuffle) S.shuffle = true;
S.base = [...ids];
if (shuffle) {
S.queue = shuffled(ids);
i = 0;
} else if (S.shuffle) {
const first = ids[i];
S.queue = [first, ...shuffled(ids.filter((_, k) => k !== i))];
i = 0;
} else S.queue = [...ids];
S.smartIds.clear();
load(i);
if (S.shuffle === 'smart') smartFill();
}
function togglePlay() {
if (S.idx < 0) return toast('Pilih lagu dulu ya');
if (!audio.src) return load(S.idx, true, S.restorePos);
audio.paused ? audio.play().catch(() => {}) : pauseAll();
}
/* ---------- up next: mix rekomendasi ala YouTube Music ---------- */
// S.src = sumber antrean: { mix, name, chip }. UPMETA = chip suasana buat lagu yang lagi diputar.
const UPN = new Map();
let UPMETA = { vid: '', chips: [] };
let mixLoading = false;
function upNext(vid, chip) {
const k = `${vid}|${chip?.pl || ''}|${chip?.params || ''}`;
if (!UPN.has(k)) {
const q = chip ? `&pl=${enc(chip.pl)}¶ms=${enc(chip.params)}` : '';
UPN.set(k, api(`/api/yt/upnext?vid=${vid}${q}`).catch((e) => { UPN.delete(k); throw e; }));
}
return UPN.get(k);
}
async function loadChips() {
const t = cur();
if (!t?.vid || t.kind !== 'song' || UPMETA.vid === t.vid) return;
UPMETA = { vid: t.vid, chips: [] };
try {
const d = await upNext(t.vid);
if (cur()?.vid !== t.vid) return;
UPMETA = { vid: t.vid, chips: d.chips || [], title: d.title };
renderQueue();
renderNowSide(true);
} catch {}
}
// Pilih lagu satuan (beranda, cari, chart) = mulai mix: lagunya diputar, "berikutnya" diisi rekomendasi
function playMix(id, list, i) {
const t = T(id);
if (!t?.vid || t.kind !== 'song') return playFrom(list || [id], i || 0);
S.queue = [id];
S.base = [id];
S.src = { mix: true, name: `Mix ${t.title}`, chip: '' };
load(0);
fillMix(t.vid);
}
async function fillMix(vid, chip) {
mixLoading = true;
renderQueue();
renderNowSide(true);
try {
const d = await upNext(vid, chip);
const t = cur();
if (t?.vid !== vid) return;
if (d.title && !chip) S.src.name = d.title;
S.src.chip = chip?.label || '';
const ids = d.items.map((x) => song(x).id).filter((id) => id !== t.id);
S.queue = [...S.queue.slice(0, S.idx + 1), ...ids];
S.base = [...S.queue];
ids.forEach((x) => S.radioIds.add(x));
if (ids[0]) prefetch(ids[0]);
saveTracks();
} catch {
toast('Rekomendasi gagal dimuat');
} finally {
mixLoading = false;
renderQueue();
renderNowSide(true);
saveState();
}
}
// Ganti suasana mix lewat chip (Semua, Temukan, Romansa, ...)
function pickChip(i) {
const t = cur();
const c = UPMETA.chips[i];
if (!t || !c || UPMETA.vid !== t.vid) return;
if (!S.src?.mix) S.src = { mix: true, name: UPMETA.title || `Mix ${t.title}`, chip: '' };
S.src.chip = c.label;
fillMix(t.vid, i === 0 ? null : c);
}
// Nama sumber buat daftar yang diputar dari halaman (album, playlist, favorit, dll)
const pageSrcName = () => $('.page .hero h1, .page .vh h1')?.textContent.trim() || 'Antrean';
let radioLoading = null;
// Kalau antrean mau habis, tambahin lagu mirip dari lagu yang lagi diputar
async function ensureRadio() {
const t = cur();
if (!S.radio || !t?.vid || t.kind !== 'song' || S.repeat === 'all' || S.queue.length - S.idx - 1 > 2) return;
if (radioLoading) return radioLoading;
radioLoading = (async () => {
try {
const items = await api(`/api/yt/radio?vid=${t.vid}`);
const have = new Set(S.queue);
const recent = new Set(Object.keys(S.plays).sort((a, b) => S.plays[b].last - S.plays[a].last).slice(0, 30));
const ids = items.map((x) => song(x).id).filter((id) => !have.has(id) && !recent.has(id)).slice(0, 15);
if (!ids.length) return;
ids.forEach((id) => S.radioIds.add(id));
S.queue.push(...ids);
S.base.push(...ids);
prefetch(ids[0]);
renderQueue();
renderNowSide(true);
saveState();
saveTracks();
} catch {}
})();
try { await radioLoading; } finally { radioLoading = null; }
}
async function next(auto = false) {
if (!S.queue.length) return;
if (!auto) noteSkip();
if (S.idx + 1 >= S.queue.length && S.radio && S.repeat !== 'all') await ensureRadio();
if (S.idx + 1 < S.queue.length) return load(S.idx + 1);
if (S.repeat === 'all' || !auto) return load(0, S.repeat === 'all' || !auto);
pauseAll();
}
function prev() {
if (audio.currentTime > 3 || S.idx <= 0) {
if (!audio.src) return load(Math.max(0, S.idx));
audio.currentTime = 0;
return;
}
load(S.idx - 1);
}
// Acak: mati -> acak -> smart shuffle (diselipin lagu mirip ✨, lagu yang sering di-skip ditaruh belakang)
function toggleShuffle() {
const id = S.queue[S.idx];
S.shuffle = !S.shuffle ? true : S.shuffle === true ? 'smart' : false;
if (S.shuffle === true) S.queue = [...S.queue.slice(0, S.idx + 1), ...shuffled(S.queue.slice(S.idx + 1))];
else if (S.shuffle === 'smart') smartFill();
else {
dropSmart();
if (S.base.length) { S.queue = [...S.base]; S.idx = Math.max(0, S.queue.indexOf(id)); }
}
renderBar();
renderQueue();
saveState();
toast({ true: 'Acak nyala', smart: '✨ Smart shuffle: diselipin lagu mirip', false: 'Acak mati' }[S.shuffle]);
}
function dropSmart() {
S.queue = S.queue.filter((x, i) => i <= S.idx || !S.smartIds.has(x));
S.smartIds.clear();
}
let smartBusy = false;
async function smartFill() {
const t = cur();
if (!t?.vid || smartBusy) return;
smartBusy = true;
try {
const rest = S.queue.slice(S.idx + 1).filter((x) => !S.smartIds.has(x));
const ok = shuffled(rest.filter((x) => (S.skips[x] || 0) < 2)), late = rest.filter((x) => (S.skips[x] || 0) >= 2);
const seeds = [t, ...ok.slice(0, 2).map(T)].filter((x) => x?.vid).slice(0, 2);
const ds = await Promise.all(seeds.map((x) => upNext(x.vid).catch(() => null)));
if (S.shuffle !== 'smart' || cur() !== t) return;
const have = new Set(S.queue);
const recs = shuffled([...new Set(ds.flatMap((d) => d?.items || []).map((x) => song(x).id))].filter((x) => !have.has(x) && (S.skips[x] || 0) < 2));
const out = [];
let r = 0;
const add = () => { if (recs[r]) { S.smartIds.add(recs[r]); out.push(recs[r++]); } };
ok.forEach((x, i) => { out.push(x); if (i % 3 === 2) add(); });
while (out.length < 15 && recs[r]) add();
S.queue = [...S.queue.slice(0, S.idx + 1), ...out, ...late];
saveTracks();
renderQueue();
renderNowSide(true);
saveState();
} finally { smartBusy = false; }
}
// Skip di 30 detik pertama = sinyal "kurang suka"
const saveSkips = debounce(() => kv.set('skips', S.skips), 1000);
function noteSkip() {
const t = cur();
if (!t || t.kind !== 'song' || !audio.src) return;
const c = audio.currentTime, d = durNow();
if (c < 30 && d > 60) { S.skips[t.id] = (S.skips[t.id] || 0) + 1; saveSkips(); }
else if (c > d * 0.6 && S.skips[t.id]) { S.skips[t.id]--; saveSkips(); }
}
function cycleRepeat() {
S.repeat = { off: 'all', all: 'one', one: 'off' }[S.repeat];
renderBar();
saveState();
toast({ off: 'Ulangi mati', all: 'Ulangi semua', one: 'Ulangi satu lagu' }[S.repeat]);
}
function playNext(ids) {
if (S.idx < 0) return playFrom(ids);
S.queue.splice(S.idx + 1, 0, ...ids);
S.base.splice(S.base.indexOf(S.queue[S.idx]) + 1, 0, ...ids);
renderQueue();
saveState();
saveTracks();
toast(ids.length > 1 ? `${ids.length} lagu diputar berikutnya` : 'Diputar berikutnya');
}
function addToQueue(ids) {
if (S.idx < 0) return playFrom(ids);
S.queue.push(...ids);
S.base.push(...ids);
renderQueue();
saveState();
saveTracks();
toast(ids.length > 1 ? `${ids.length} lagu masuk antrean` : 'Masuk antrean');
}
function removeAt(qi) {
if (qi === S.idx) return;
const [id] = S.queue.splice(qi, 1);
if (qi < S.idx) S.idx--;
const bi = S.base.indexOf(id);
if (bi >= 0) S.base.splice(bi, 1);
renderQueue();
saveState();
}
function seekTo(sec) {
if (!audio.src) { S.restorePos = Math.max(0, sec); return; }
audio.currentTime = Math.max(0, Math.min(sec, isFinite(audio.duration) ? audio.duration : sec));
}
function setVolume(v) {
S.volume = v;
audio.muted = false;
applyVol();
$$('input.vol').forEach((r) => { r.value = v; r.style.setProperty('--p', v + '%'); });
renderMute();
saveState();
}
function renderMute() {
const m = audio.muted || S.volume === 0;
$$('[data-act=mute]').forEach((b) => (b.innerHTML = m ? I.mute : I.vol));
}
const stopLoading = () => { $('#lcd').classList.remove('loading'); renderPlayBtn(); };
onAudio('playing', () => {
stopLoading();
// Siapin lagu berikutnya biar pindah lagu langsung bunyi
prefetch(S.queue[S.idx + 1]);
ensureRadio();
});
onAudio('canplay', stopLoading);
onAudio('play', () => {
document.body.classList.remove('paused');
renderPlayBtn(true);
const t = cur();
if (t && !counted) {
counted = true;
const p = (S.plays[t.id] ||= { n: 0, last: 0 });
p.n++;
p.last = Date.now();
savePlays();
logStart(t.id);
}
wakeGraph();
vizStart();
updateHomeHero();
lyrLoop();
if ('mediaSession' in navigator) navigator.mediaSession.playbackState = 'playing';
});
onAudio('pause', () => {
updateHomeHero();
document.body.classList.add('paused');
renderPlayBtn(true);
saveState();
if ('mediaSession' in navigator) navigator.mediaSession.playbackState = 'paused';
});
/* ---------- timer tidur ---------- */
function setSleep(v) {
S.sleep = v;
sleepMul = 1;
applyVol();
renderSleep();
if (!v) return toast('Timer tidur dimatiin');
toast(v.endOfTrack ? 'Musik berhenti habis lagu ini' : `Musik berhenti ${Math.round((v.until - Date.now()) / 60000)} menit lagi`);
}
function renderSleep() {
const left = S.sleep?.until ? Math.max(0, Math.ceil((S.sleep.until - Date.now()) / 60000)) : 0;
$$('[data-act=sleep]').forEach((b) => {
b.classList.toggle('on', !!S.sleep);
b.title = !S.sleep ? 'Timer tidur' : S.sleep.endOfTrack ? 'Berhenti habis lagu ini' : `Berhenti ${left} menit lagi`;
b.dataset.left = S.sleep?.until ? `${left}m` : S.sleep ? '1' : '';
});
}
function sleepMenu(el) {
const r = el.getBoundingClientRect();
const m = (min) => ({ label: `${min} menit`, act: () => setSleep({ until: Date.now() + min * 60000 }) });
showMenu(r.left - 140, r.top - 250, [
...(S.sleep ? [{ label: 'Matiin timer', danger: true, act: () => setSleep(null) }, '-'] : []),
m(15), m(30), m(45), m(60),
{ label: 'Habis lagu ini', act: () => setSleep({ endOfTrack: true }) },
]);
}
function sleepStop() {
pauseAll();
sleepMul = 1;
applyVol();
S.sleep = null;
renderSleep();
toast('Timer tidur: musik dijeda, selamat istirahat');
}
setInterval(() => {
if (!S.sleep?.until) return;
const left = S.sleep.until - Date.now();
// Volume turun pelan di 10 detik terakhir
if (left <= 10000 && left > 0 && !audio.paused) {
sleepMul = left / 10000;
applyVol();
}
if (left <= 0) sleepStop();
else renderSleep();
}, 1000);
// Ulangi satu lagu: muat ulang src-nya, jangan cuma currentTime = 0. Di app Mac (WKWebView)
// seek ke 0 habis 'ended' bisa bikin pemutar nyangkut di 0:00 / 0:00 padahal statusnya main.
function replay() {
counted = false;
audio.load();
audio.play().catch(() => {});
// Pengaman: kalau 5 detik kemudian masih belum jalan juga, muat ulang lagunya dari nol
const id = S.queue[S.idx];
setTimeout(() => {
if (S.queue[S.idx] === id && S.repeat === 'one' && !audio.paused && !(audio.currentTime > 0.3)) load(S.idx);
}, 5000);
}
onAudio('ended', () => {
if (S.sleep?.endOfTrack) { audio.currentTime = 0; return sleepStop(); }
if (cur()?.kind === 'pod') {
markDone(cur().id);
if (!S.autoplay && S.repeat !== 'one') return;
}
if (S.repeat === 'one') replay();
else next(true);
});
onAudio('error', () => {
stopLoading();
if (!audio.src) return;
const t = cur();
if (S.serverOk === false) return toast('Server Svara belum nyala, jalanin ./senandung dulu');
toast(t?.kind === 'pod' ? 'Episode ini gagal diputar' : `“${t?.title}” gagal diputar, lanjut ke berikutnya`);
if (S.idx + 1 < S.queue.length) setTimeout(() => cur() === t && next(true), 1400);
});
function metaFix() {
const t = cur();
if (t && isFinite(audio.duration) && Math.abs((t.duration || 0) - audio.duration) > 2) {
t.duration = audio.duration;
saveTracks();
}
tick();
}
onAudio('loadedmetadata', metaFix);
// WebKit kadang ngasih durasi Infinity/NaN (mis. pas muter ulang), jangan sampai tampilan jadi 0:00 / 0:00
const durNow = () => (isFinite(audio.duration) && audio.duration > 0 ? audio.duration : cur()?.duration || 0);
const posNow = () => (audio.src ? (isFinite(audio.currentTime) ? audio.currentTime : 0) : S.restorePos);
let seeking = false;
let lastSave = 0;
function setSeek(v) {
const p = v / 10 + '%';
for (const r of $$('input.seek')) {
r.value = v;
r.parentElement.style.setProperty('--p', p);
}
$('#lcd').style.setProperty('--p', p);
}
function tick() {
const d = durNow();
const c = posNow();
if (!seeking) {
setSeek(d ? Math.min(1, c / d) * 1000 : 0);
$$('[data-np=cur]').forEach((e) => (e.textContent = fmt(c)));
$$('[data-np=left]').forEach((e) => (e.textContent = fmt(d)));
}
if (audio.paused) syncLyrics(c);
updateSideLyr();
const t = cur();
if (t?.kind === 'pod' && audio.src && !audio.paused && c > 5) {
if (d && c > d - 25) {
if (!S.podDone.has(t.id)) markDone(t.id);
} else {
S.podpos[t.id] = c;
savePod();
}
}
if (Date.now() - lastSave > 5000) { lastSave = Date.now(); saveState(); }
xfTick(c, d);
logTick();
hhLyr();
vizStart();
if ('mediaSession' in navigator && d && isFinite(d) && audio.src) {
try { navigator.mediaSession.setPositionState({ duration: d, position: Math.min(c, d), playbackRate: audio.playbackRate }); } catch {}
}
}
onAudio('timeupdate', tick);
for (const r of $$('input.seek')) {
r.addEventListener('input', () => {
seeking = true;
const d = durNow();
const c = (r.value / 1000) * d;
setSeek(r.value);
$$('[data-np=cur]').forEach((e) => (e.textContent = fmt(c)));
$$('[data-np=left]').forEach((e) => (e.textContent = fmt(d)));
});
r.addEventListener('change', () => {
const d = durNow();
seekTo((r.value / 1000) * d);
seeking = false;
tick();
});
}
for (const r of $$('input.vol')) r.addEventListener('input', () => setVolume(+r.value));
function setMediaSession(t) {
document.title = `${t.title} · ${t.artist}`;
if (!('mediaSession' in navigator)) return;
const meta = { title: t.title, artist: t.artist, album: t.album || '' };
navigator.mediaSession.metadata = new MediaMetadata(t.art ? { ...meta, artwork: [{ src: t.art, sizes: '544x544', type: 'image/jpeg' }] } : meta);
}
if ('mediaSession' in navigator) {
const h = (a, f) => { try { navigator.mediaSession.setActionHandler(a, f); } catch {} };
h('play', () => togglePlay());
h('pause', () => pauseAll());
h('previoustrack', prev);
h('nexttrack', () => next());
h('seekto', (e) => seekTo(e.seekTime));
h('seekbackward', () => seekTo(audio.currentTime - 10));
h('seekforward', () => seekTo(audio.currentTime + 10));
}
// Siapin audio sebelum diklik, biar langsung bunyi.
// Lagu diunduh penuh (kecil); episode cukup diambil link-nya (file-nya gede)
const prepared = new Set();
function prefetch(id) {
const t = T(id);
if (!t?.vid || prepared.has(t.vid)) return;
prepared.add(t.vid);