summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
blob: 4587990815403573eb0b998953a9e17d59e20ef8 (plain) (blame)
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
import {
  html, useState, useEffect, useReducer, useRef, useCallback,
} from './vendor/htm-preact.js';
import { queueReducer, emptyQueue } from './queue-ops.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import { useStickyBand } from './sticky.js';
import { CHUNK_SIZE, pipelinedDownload } from './file-utils.js';
import { playback, cast as castBridge } from './platform.js';
import { castSession, useCastDevice, loadFile, CastButton } from './cast-session.js';

/**
 * The Music app's persistent player bar (docs/MESHBAY_DESIGN.md §9.8).
 *
 * Owned and rendered by app.js — the router's parent — so playback survives
 * navigating between groups, search, and other pages. Both group-page.js
 * and search-page.js trigger playback by calling `onPlayQueue(tracks,
 * startIndex)`, which flows up to app.js.
 *
 * Each track carries a `groupId`; the player calls `getConnection(groupId)`
 * per track to obtain the right transport — a pool-based lazy connection
 * that transparently handles single-group and cross-group queues.
 *
 * No streaming, no MSE, no node-side transcode pool for the common case: a
 * track is a few megabytes, so it is downloaded and decrypted once through
 * the same chunk pipeline Files already uses (file-utils.js's
 * pipelinedDownload), then played from a blob URL — the deliberate
 * simplification recorded in docs/MESHBAY_DESIGN.md §9.8. WMA and Musepack are
 * the one exception (`NEEDS_TRANSCODE_RE` below): neither decodes in a
 * browser's <audio> element at all, tagged correctly or not, so those two go
 * through `transport.requestAudioTranscode` first — a node-side,
 * cached-after-once AAC/M4A conversion — before the same download/blob path
 * runs.
 *
 * With a television chosen (cast-session.js), the same decrypted track is
 * handed to the cast relay instead of the <audio> element, with its cover,
 * and the bar becomes the receiver's remote: its play, pause, seek, previous
 * and next drive the television, its clock is the television's, and the end
 * of a track there moves the queue on as `ended` does here (docs/MESHBAY_DESIGN.md
 * §11.4). The element keeps the track's source for its duration, and never
 * plays while casting.
 */

const MIME_BY_EXT = {
  mp3: 'audio/mpeg', flac: 'audio/flac', ogg: 'audio/ogg', opus: 'audio/opus',
  wav: 'audio/wav', aac: 'audio/aac', m4a: 'audio/mp4',
};

// The same two formats as the node's BROWSER_INCOMPATIBLE_AUDIO_EXTS
// (transport/webrtc/apps/music.py), which is the one that decides: the node refuses a
// transcode request for anything else. This is here so the player does not
// ask for one it knows will be refused — not because it enforces the rule.
// It used to be the only thing that did, and a member's own message never
// passed through it.
const NEEDS_TRANSCODE_RE = /\.(wma|mpc)$/i;

function guessMime(name) {
  const ext = (name || '').split('.').pop().toLowerCase();
  return MIME_BY_EXT[ext] || 'audio/mpeg';
}

function formatTime(seconds) {
  if (!isFinite(seconds) || seconds < 0) return '0:00';
  const total = Math.floor(seconds);
  const m = Math.floor(total / 60);
  const s = total % 60;
  return `${m}:${String(s).padStart(2, '0')}`;
}

// Bounded: only the currently playing track plus the read-ahead window are
// ever worth holding in memory. Older blob URLs are revoked, not merely
// dropped — otherwise every track played in a session leaks its object URL.
// Sized for the largest read-ahead prefetchDepth() can return (currently
// playing + 5 on Wi-Fi) — a smaller run on cellular just evicts sooner.
const MAX_CACHED_BLOBS = 6;

/**
 * How many tracks to warm the cache for, ahead of the one playing.
 *
 * A prefetched track needs no live connection to play — it is exactly what
 * buys time through a screen-lock network gap (see transport.js's
 * auto-reconnect) — so the more of a mobile-data budget it is safe to spend
 * on tracks that might not even get listened to, the better the odds a lock
 * of ordinary length is fully covered by tracks already sitting in
 * blobCacheRef. Wi-Fi is effectively free and usually fast, so 5; a metered
 * connection (or one this API cannot see at all) gets 3 — enough to matter,
 * not so much it burns a noticeable chunk of a data plan on an album that
 * might get abandoned after track one.
 *
 * `navigator.connection` is Chromium-only (Chrome, Edge, Electron) — plain
 * `undefined` on Firefox and Safari, where this must fall through to the
 * conservative tier exactly as it would for a cellular connection it could
 * name. Never assume "fast" from the absence of a signal that says so.
 */
function prefetchDepth() {
  const conn = navigator.connection;
  if (conn && conn.type === 'wifi') return 5;
  return 3;
}

function loadVolume() {
  try {
    const v = parseFloat(localStorage.getItem('meshbay_music_volume'));
    return isFinite(v) && v >= 0 && v <= 1 ? v : 1;
  } catch { return 1; }
}
function saveVolume(v) {
  try { localStorage.setItem('meshbay_music_volume', String(v)); } catch { /* per-device only */ }
}
function loadShuffle() {
  try { return localStorage.getItem('meshbay_music_shuffle') === '1'; } catch { return false; }
}
function saveShuffle(v) {
  try { localStorage.setItem('meshbay_music_shuffle', v ? '1' : '0'); } catch { /* per-device only */ }
}
function loadRepeat() {
  try {
    const v = localStorage.getItem('meshbay_music_repeat');
    return v === 'all' || v === 'one' ? v : 'off';
  } catch { return 'off'; }
}
function saveRepeat(v) {
  try { localStorage.setItem('meshbay_music_repeat', v); } catch { /* per-device only */ }
}

// The current queue, tracklist form -- "go back to what's playing" without
// switching tabs or hunting for the album/folder it came from. Works the
// same regardless of how the queue was built (an album, a consolidated
// misc/loose bucket, a single standalone track).
//
// The header alone ("Playing now") named the *panel*, not the track — on a
// long queue the highlighted row can be scrolled out of view entirely, so
// opening this told you nothing you didn't already know. It now shows the
// current track's own title/artist right under the header, and scrolls the
// highlighted row into view on open rather than leaving it to be found.
function QueuePanel({ tracks, order, pos, onSelect, onClose, onSaveAsPlaylist }) {
  const activeRowRef = useRef(null);
  useEffect(() => {
    if (activeRowRef.current) {
      activeRowRef.current.scrollIntoView({ block: 'center' });
    }
  }, []);

  const current = tracks[order[pos]];

  return html`
    <div class="video-overlay" onClick=${(e) => {
      if (e.target.classList.contains('video-overlay')) onClose();
    }}>
      <div class="music-detail">
        <div class="video-top-bar">
          <span class="video-title">${t('music.queue_title')}</span>
          ${/* "Save the current queue as a playlist" lives here rather than in
                Music's toolbar menu, because this panel is where the current
                queue is a thing the reader can actually see — and because the
                queue is the player's own state, which a menu in a different
                component would have to have lifted out of it. */''}
          ${onSaveAsPlaylist && html`
            <button class="video-close" title=${t('playlists.save_queue')}
              onClick=${() => onSaveAsPlaylist(order.map((i) => tracks[i]))}>
              <${Icon} name="playlist" /></button>
          `}
          <button class="video-close" onClick=${onClose} title=${t('video.close')}>
            <${Icon} name="close" /></button>
        </div>
        ${current && html`
          <div class="music-queue-now-playing">
            <span class="music-queue-now-playing-title">
              ${current.display_title || current.name}</span>
            ${current.artist && html`
              <span class="music-queue-now-playing-artist"> — ${current.artist}</span>`}
          </div>
        `}
        <div class="music-detail-body">
          <div class="music-tracklist">
            ${order.map((idx, i) => html`
              <button class="music-track-row ${i === pos ? 'active' : ''}" key=${tracks[idx].id}
                ref=${i === pos ? activeRowRef : null}
                onClick=${() => { onSelect(i); onClose(); }}>
                <span class="music-track-no">${i + 1}</span>
                <span class="music-track-title">${tracks[idx].display_title || tracks[idx].name}</span>
                <span class="music-track-duration">${formatTime(tracks[idx].duration || 0)}</span>
              </button>
            `)}
          </div>
        </div>
      </div>
    </div>
  `;
}

function MusicPlayerBar({ getConnection, queue, onClose, userPrefs, onSaveQueue }) {
  // Pinned to the bottom of the window, over the bottom of the sidebar; the
  // sidebar subtracts this so its last entry is not underneath.
  const barBand = useStickyBand('--music-bar-h');
  const audioRef = useRef(null);
  const blobCacheRef = useRef(new Map()); // file id -> { url, order: insertion index }
  const blobInsertRef = useRef(0);
  const loadTokenRef = useRef(0);

  // The queue: every entry, the play order over it, and where in that order
  // we are (docs/playlists.md §9.3). One reducer rather than three useStates
  // because "add to queue" derives its new indices from the current track
  // count, and two appends batched into one tick cannot both see it.
  const [queueState, dispatch] = useReducer(queueReducer, null, emptyQueue);
  const { tracks, order, pos } = queueState;
  const [playing, setPlaying] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [shuffle, setShuffle] = useState(loadShuffle);
  const [repeat, setRepeat] = useState(loadRepeat); // 'off' | 'all' | 'one'
  const [volume, setVolume] = useState(loadVolume);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [showQueue, setShowQueue] = useState(false);
  // A broken source file (truncated download, a format the browser has no
  // decoder for) must not stall a "play all" queue on the one track that
  // failed — found live against a real library: a corrupt few-hundred-byte
  // file with no audio stream at all, sitting between two good tracks.
  // Bounded so a queue that turns out to be *entirely* bad (every file the
  // same unsupported format) fails once, visibly, rather than burning
  // through the whole list in an instant.
  const consecutiveFailuresRef = useRef(0);
  const MAX_CONSECUTIVE_FAILURES = 5;
  const prefetchAfterInsertRef = useRef(false);
  // Groups that did not answer this session. A playlist crosses groups, and
  // one of them being off is a property of that group rather than of each of
  // its tracks in turn — see advancePastFailure below (docs/playlists.md §11.3).
  const downGroupsRef = useRef(new Set());
  // When the page last came back from hidden. A phone with its screen off
  // drops every connection at once, so a track that fails for lack of one
  // while the page sleeps, or just after it wakes, says nothing about its
  // group: it is retried rather than skipped (see the load effect below).
  const wokeAtRef = useRef(0);
  const [retryNonce, setRetryNonce] = useState(0);
  const WAKE_GRACE_MS = 30000;

  const currentTrack = tracks[order[pos]] || null;

  /**
   * Move past a track that will not play.
   *
   * Two failures, and they are properties of different things:
   *
   * A **decode** failure belongs to that file — a truncated download, a format
   * with no decoder. The bounded counter is right for it: a queue that turns
   * out to be entirely bad fails once, visibly, rather than burning through
   * the whole list in an instant.
   *
   * A **connection** failure belongs to that *group*. The same bound applied
   * to it is a regression playlists introduce into code that is correct today:
   * a playlist whose next six tracks all come from one node that is off stops
   * at the sixth, with an error, and the reader sees "the playlist is broken".
   * So the group is marked down and every one of its queued tracks is skipped
   * in one step, with the counter reset — which is what the bound was
   * protecting in the first place.
   */
  const advancePastFailure = useCallback((groupDown) => {
    if (order.length <= 1) return;
    let next = pos + 1;
    if (groupDown) {
      downGroupsRef.current.add(groupDown);
      consecutiveFailuresRef.current = 0;
      while (next < order.length
             && downGroupsRef.current.has(tracks[order[next]]
                                          && tracks[order[next]].groupId)) {
        next += 1;
      }
    } else {
      consecutiveFailuresRef.current += 1;
      if (consecutiveFailuresRef.current > MAX_CONSECUTIVE_FAILURES) return;
    }
    if (next < order.length) { dispatch({ type: 'skipTo', pos: next }); return; }
    if (repeat === 'all') dispatch({ type: 'skipTo', pos: 0 });
    // Nothing left that can play. Stopping once, with the error already on
    // screen, is the honest end — and is what the bound above exists to reach.
  }, [tracks, order, pos, repeat]);

  // Stops playback the moment this bar goes away for any reason -- the
  // close button below, or the shell tearing it down on its own (leaving
  // the group, switching to a different one). A component removed from the
  // DOM should already stop an <audio> element, but that's the browser's
  // behaviour to rely on, not this app's to assert; pausing explicitly, and
  // releasing every cached blob URL rather than leaving them for the tab's
  // lifetime, costs nothing and isn't optional either way.
  useEffect(() => () => {
    const audio = audioRef.current;
    if (audio) { audio.pause(); audio.src = ''; }
    for (const { url } of blobCacheRef.current.values()) URL.revokeObjectURL(url);
  }, []);

  // Held for as long as a track plays or loads: without it a phone freezes the
  // page a minute after the screen goes off, and the next track never loads.
  // Let go a few seconds late, because skipping a track that failed passes
  // through "not playing", and Android refuses to take the hold back from the
  // background: a playlist would stop at its first bad file.
  const keepAliveRef = useRef({ held: false, timer: null });
  const active = playing || loading;
  useEffect(() => {
    const k = keepAliveRef.current;
    if (!active) return;
    clearTimeout(k.timer);
    if (!k.held) { k.held = true; playback.keepAlive(true); }
    return () => {
      k.timer = setTimeout(() => { k.held = false; playback.keepAlive(false); }, 5000);
    };
  }, [active]);

  // Screen Wake Lock, opt-in only (Settings → music_keep_screen_on) and only
  // while a track is actually playing — off by default because the ordinary
  // expectation, matching Spotify/Deezer, is that the phone locks on its own
  // idle timer while listening (docs/MESHBAY_DESIGN.md §9.8). Unlike the video
  // player's unconditional lock, this must not fight that default for
  // everyone who never asked for it; it exists for whoever explicitly wants
  // to trade battery for riding out the WebRTC screen-lock reconnect gap
  // without waiting on it at all.
  useEffect(() => {
    if (!playing) return;
    if (!(userPrefs && userPrefs.music_keep_screen_on === 'true')) return;
    if (!('wakeLock' in navigator)) return;
    let sentinel = null;
    let cancelled = false;
    const acquire = async () => {
      try {
        const wl = await navigator.wakeLock.request('screen');
        if (cancelled) { try { wl.release(); } catch { /* ignore */ } return; }
        sentinel = wl;
        wl.addEventListener('release', () => { sentinel = null; });
      } catch (e) {
        // Battery saver, no permission, an insecure context — playback has
        // never depended on this, so there is nothing to fall back to.
        console.warn('[MeshBay] Wake lock request failed:', e.message);
      }
    };
    acquire();
    // Released automatically the moment the page goes hidden (spec
    // behaviour) — re-requested here so it holds again once foregrounded,
    // same as the video player's handling of the same event.
    const onVisibility = () => {
      if (document.visibilityState === 'visible' && !sentinel) acquire();
    };
    document.addEventListener('visibilitychange', onVisibility);
    return () => {
      cancelled = true;
      document.removeEventListener('visibilitychange', onVisibility);
      if (sentinel) { try { sentinel.release(); } catch { /* already released */ } }
    };
  }, [playing, userPrefs && userPrefs.music_keep_screen_on]);

  const evictOldBlobs = useCallback(() => {
    const cache = blobCacheRef.current;
    while (cache.size > MAX_CACHED_BLOBS) {
      let oldestId = null, oldestOrder = Infinity;
      for (const [id, v] of cache) {
        if (v.order < oldestOrder) { oldestOrder = v.order; oldestId = id; }
      }
      if (oldestId == null) break;
      URL.revokeObjectURL(cache.get(oldestId).url);
      cache.delete(oldestId);
    }
  }, []);

  // ── Casting ──────────────────────────────────────────────────────────────
  const castDevice = useCastDevice();
  const remote = Boolean(castDevice) && castSession.canSendFiles;
  const remoteRef = useRef(remote);
  // Which track the television was last given, where it was when last
  // polled, and which track's end has already moved the queue on: the
  // receiver keeps reporting FINISHED until it is given something else.
  const remoteTrackRef = useRef(null);
  const remotePosRef = useRef(null);
  const finishedRef = useRef(null);
  // True while a track is on its way to the television: the receiver's
  // status still describes the previous one until it lands.
  const sendingRef = useRef(false);

  // The track's cover, for the television to show beside it — found as the
  // album card finds it (music-app.js): this track's own, else another queued
  // track of the same album that carries one, else the cover the node found
  // for the album. The node answers that last question from its cache, and
  // asks MusicBrainz only where the group has it on and the track is tagged.
  // A cover that cannot be had is no reason not to play the track.
  const fetchCover = useCallback(async (entry) => {
    try {
      const { transport, gek } = await getConnection(entry.groupId);
      if (!transport || !transport.connected) return null;
      const sibling = entry.album && tracks.find((tr) => tr.thumb_hash
        && tr.groupId === entry.groupId && tr.album === entry.album && tr.artist === entry.artist);
      let hash = entry.thumb_hash || (sibling && sibling.thumb_hash) || null;
      if (!hash && transport.fetchMusicMeta) {
        const meta = await transport.fetchMusicMeta(entry.id).catch(() => null);
        hash = (meta && meta.cover_thumb_hash) || null;
      }
      if (!hash) return null;
      const chunks = await pipelinedDownload(transport, gek, hash, 1);
      return { bytes: new Uint8Array(await new Blob(chunks).arrayBuffer()), type: 'image/jpeg' };
    } catch {
      return null;
    }
  }, [getConnection, tracks]);

  const sendToTv = useCallback(async (entry, startAt = 0) => {
    const cached = blobCacheRef.current.get(entry.id);
    if (!cached) throw new Error(t('music.err_playback'));
    sendingRef.current = true;
    try {
      const cover = await fetchCover(entry);
      remoteTrackRef.current = entry.id;
      remotePosRef.current = startAt;
      finishedRef.current = null;
      await loadFile({
        owner: 'music', startAt,
        bytes: new Uint8Array(await cached.blob.arrayBuffer()), type: cached.mime, cover,
        title: entry.display_title || entry.name, artist: entry.artist || '', album: entry.album || '',
      });
    } finally {
      sendingRef.current = false;
    }
  }, [fetchCover]);

  const fetchTrackBlob = useCallback(async (entry) => {
    const cached = blobCacheRef.current.get(entry.id);
    if (cached) return cached.url;
    // A group that does not answer is marked as such, so the queue can skip
    // all of its tracks at once rather than one failure at a time.
    const groupDown = () => {
      const e = new Error(t('music.err_transport'));
      e.isGroupDown = true;
      return e;
    };
    let transport;
    let gek;
    try {
      ({ transport, gek } = await getConnection(entry.groupId));
    } catch {
      throw groupDown();
    }
    if (!transport) throw groupDown();
    if (!transport.connected) await transport.waitForReconnect();
    if (!transport.connected) {
      const e = groupDown();
      e.transport = transport;
      throw e;
    }

    let downloadId = entry.id;
    let downloadSize = entry.size;
    let mime = guessMime(entry.name);
    if (NEEDS_TRANSCODE_RE.test(entry.name)) {
      let info;
      try {
        info = await transport.requestAudioTranscode(entry.id);
      } catch (err) {
        throw new Error(t('music.err_transcode'));
      }
      downloadId = info.hash;
      downloadSize = info.size;
      mime = info.mime || 'audio/mp4';
    }

    const totalChunks = Math.ceil(downloadSize / CHUNK_SIZE);
    const chunks = await pipelinedDownload(transport, gek, downloadId, totalChunks);
    const blob = new Blob(chunks, { type: mime });
    const url = URL.createObjectURL(blob);
    // The blob itself too: a cast hands its bytes to the relay.
    blobCacheRef.current.set(entry.id, { url, blob, mime, order: blobInsertRef.current++ });
    evictOldBlobs();
    return url;
  }, [getConnection, evictOldBlobs]);

  // Silently warms the cache for the next tracks so pressing "next" doesn't
  // visibly wait (docs/MESHBAY_DESIGN.md §9.8) — best-effort, never surfaces
  // an error.
  //
  // More than one: a screen lock can cost the transport several minutes (see
  // the WebRTC auto-reconnect in transport.js — this is the other half of
  // the same fix). A track already sitting in blobCacheRef needs no
  // connection at all to play, so whatever got fetched *before* the lock
  // started plays through it regardless of what the connection is doing
  // afterward — see prefetchDepth() for how far ahead that runway goes.
  const prefetchNext = useCallback((fromPos) => {
    const ahead = prefetchDepth();
    const playingGroup = tracks[order[fromPos]] && tracks[order[fromPos]].groupId;
    for (let i = 1; i <= ahead; i++) {
      const nextEntry = tracks[order[fromPos + i]];
      if (!nextEntry || blobCacheRef.current.has(nextEntry.id)) continue;
      // Only what this queue is already connected to. For an album these five
      // share one connection and nothing changes; for a shuffled cross-group
      // playlist they may want five *different* node dials of up to ten
      // seconds each, against a pool of twelve — to warm tracks the reader may
      // never reach (docs/playlists.md §9.5). The rest warm when the queue
      // gets to them and the dial has to happen anyway.
      if (nextEntry.groupId !== playingGroup) continue;
      if (downGroupsRef.current.has(nextEntry.groupId)) continue;
      fetchTrackBlob(nextEntry).catch(() => {});
    }
  }, [tracks, order, fetchTrackBlob]);

  // (Re)initialize the queue whenever the shell hands over a new one.
  // `queue.nonce` changes on every call to onPlayQueue, including "play the
  // same album again from track 0" — a fresh Date.now() each time, so this
  // effect always re-runs rather than bailing out on reference equality.
  useEffect(() => {
    if (!queue) return;
    const op = queue.op || 'replace';
    dispatch({
      type: op === 'next' ? 'insertNext' : op === 'append' ? 'append' : 'replace',
      tracks: queue.tracks,
      startIndex: queue.startIndex,
      shuffle,
    });
    // A deliberate queue change is new material to try, so the runaway bound
    // starts over; the bound exists to stop an automatic advance burning
    // through a bad queue, not to hold a user's own action against them.
    consecutiveFailuresRef.current = 0;
    if (op === 'replace') {
      setError('');
    } else {
      // Nothing that is playing changed, so the play effect below will not
      // run and will not warm anything — but "play next" just put a track at
      // pos + 1 that nobody has fetched. Flagged here, acted on once `order`
      // has actually been rebuilt.
      prefetchAfterInsertRef.current = true;
    }
    // Playback itself starts from the effect below, keyed on [tracks, order, pos].
  }, [queue]);

  useEffect(() => {
    if (!prefetchAfterInsertRef.current) return;
    prefetchAfterInsertRef.current = false;
    if (order.length) prefetchNext(pos);
    // Deliberately not keyed on `pos`: this runs for a queue edit, and the
    // ordinary advance is already covered where the current track loads.
    // eslint-disable-next-line
  }, [order]);

  // Loads and plays whatever `pos` now points to. Runs after the queue
  // effect above (pos/order/tracks all just changed together) and also
  // after skipNext/skipPrev/onEnded update `pos` alone.
  useEffect(() => {
    const onVisibility = () => {
      if (document.visibilityState === 'visible') wokeAtRef.current = Date.now();
    };
    document.addEventListener('visibilitychange', onVisibility);
    return () => document.removeEventListener('visibilitychange', onVisibility);
  }, []);

  const asleepOrJustWoke = () => document.visibilityState === 'hidden'
    || Date.now() - wokeAtRef.current < WAKE_GRACE_MS;

  // Retries the current track once the page is back and a connection may be:
  // the screen coming on, the network coming back, or the track's own
  // transport finishing its reconnect, whichever comes first. A visible page
  // also retries on a timer, so a failure that outlives the grace window
  // ends on the ordinary error path instead of a spinner nobody can clear.
  const retryWhenAwake = (myToken, transport) => {
    let stop = () => {};
    let timer = null;
    const fire = () => {
      stop();
      if (loadTokenRef.current === myToken) setRetryNonce((n) => n + 1);
    };
    const onVisibility = () => { if (document.visibilityState === 'visible') fire(); };
    document.addEventListener('visibilitychange', onVisibility);
    window.addEventListener('online', fire);
    const unsubscribe = transport ? transport.addReconnectListener(fire) : () => {};
    if (document.visibilityState === 'visible') timer = setTimeout(fire, 10000);
    stop = () => {
      clearTimeout(timer);
      document.removeEventListener('visibilitychange', onVisibility);
      window.removeEventListener('online', fire);
      unsubscribe();
    };
    if (transport && transport.connected) fire();
  };

  useEffect(() => {
    if (!currentTrack) return;
    const myToken = ++loadTokenRef.current;
    let waiting = false;
    setLoading(true);
    setError('');
    (async () => {
      try {
        const url = await fetchTrackBlob(currentTrack);
        if (loadTokenRef.current !== myToken) return; // superseded by a newer skip
        const audio = audioRef.current;
        if (!audio) return;
        audio.src = url;
        audio.currentTime = 0;
        if (remoteRef.current) {
          // To the television; the element keeps the source for its duration.
          audio.pause();
          setCurrentTime(0);
          try {
            await sendToTv(currentTrack, 0);
          } catch (castErr) {
            castErr.isCast = true;
            throw castErr;
          }
          if (loadTokenRef.current !== myToken) return;
          consecutiveFailuresRef.current = 0;
          setPlaying(true);
          prefetchNext(pos);
          return;
        }
        await audio.play();
        consecutiveFailuresRef.current = 0;
        setPlaying(true);
        prefetchNext(pos);
      } catch (err) {
        if (loadTokenRef.current !== myToken) return;
        // Autoplay refused (no recent tap): the track is loaded and fine, it
        // waits for the play button. Not an error, and no reason to skip it.
        if (err && err.name === 'NotAllowedError') { setPlaying(false); prefetchNext(pos); return; }
        // The television did not take it: that says nothing about the track,
        // so the queue stays where it is, with the reason on screen.
        if (err && err.isCast) { setError(err.message || String(err)); setPlaying(false); return; }
        if (err && err.isGroupDown && asleepOrJustWoke()) {
          // Our own connection is what went, not the group: keep the spinner
          // and this track, and try it again once we are back.
          waiting = true;
          setPlaying(false);
          retryWhenAwake(myToken, err.transport);
          return;
        }
        setError(err.message || String(err));
        setPlaying(false);
        // `fetchTrackBlob` throws `err_transport` when no node answered for
        // this track's group; anything else is about the file itself.
        advancePastFailure(err.isGroupDown ? currentTrack.groupId : null);
      } finally {
        if (loadTokenRef.current === myToken && !waiting) setLoading(false);
      }
    })();
    // eslint-disable-next-line
  }, [currentTrack && currentTrack.id, retryNonce]);

  // Belt and suspenders alongside the catch block above: `.play()` rejecting
  // is the common path for a source the browser can't decode at all, but a
  // decode failure can also surface later, asynchronously, as an `error`
  // event on the element itself rather than a rejected promise — found live
  // to matter (a truncated file with a valid-looking header but no audio
  // stream). Both paths converge on the same bounded advance, so whichever
  // fires first, the queue moves on exactly once.
  const handleMediaError = useCallback(() => {
    // Casting, the element only holds the source for its duration: whether it
    // could decode it says nothing about what the television is playing.
    if (remoteRef.current) return;
    const audio = audioRef.current;
    const mediaError = audio && audio.error;
    setError((mediaError && mediaError.message) || t('music.err_playback'));
    setPlaying(false);
    advancePastFailure();
  }, [advancePastFailure]);

  useEffect(() => {
    const audio = audioRef.current;
    if (audio) audio.volume = volume;
    saveVolume(volume);
  }, [volume]);

  const skipTo = useCallback((newPos) => dispatch({ type: 'skipTo', pos: newPos }), []);

  const skipNext = useCallback(() => {
    if (order.length === 0) return;
    if (pos + 1 < order.length) { skipTo(pos + 1); return; }
    if (repeat === 'all') { skipTo(0); return; }
    setPlaying(false); // end of queue, nothing to repeat
  }, [pos, order.length, repeat, skipTo]);

  const skipPrev = useCallback(() => {
    if (order.length === 0) return;
    // A few seconds in: restart the current track, the way most players do,
    // rather than always jumping to the previous one.
    if (remoteRef.current && castSession.owner === 'music' && (remotePosRef.current || 0) > 3) {
      castBridge.chromecastSeek(0).catch(() => {});
      remotePosRef.current = 0;
      setCurrentTime(0);
      return;
    }
    const audio = audioRef.current;
    if (!remoteRef.current && audio && audio.currentTime > 3) { audio.currentTime = 0; return; }
    if (pos > 0) { skipTo(pos - 1); return; }
    if (repeat === 'all') { skipTo(order.length - 1); }
  }, [pos, order.length, repeat, skipTo]);

  const onEnded = useCallback(() => {
    if (repeat === 'one') {
      if (remoteRef.current && currentTrack) {
        sendToTv(currentTrack, 0).catch((e) => { setError(e.message || String(e)); setPlaying(false); });
        return;
      }
      const audio = audioRef.current;
      if (audio) { audio.currentTime = 0; audio.play().catch(() => {}); }
      return;
    }
    skipNext();
  }, [repeat, skipNext, currentTrack, sendToTv]);
  const onEndedRef = useRef(onEnded);
  onEndedRef.current = onEnded;

  const togglePlaying = useCallback(() => {
    if (remoteRef.current && currentTrack) {
      // A film or a photo has the television: playing again gives it back
      // the track, from where it was.
      if (castSession.owner !== 'music') {
        sendToTv(currentTrack, remotePosRef.current || 0)
          .then(() => { setError(''); setPlaying(true); })
          .catch((e) => { setError(e.message || String(e)); setPlaying(false); });
        return;
      }
      (playing ? castBridge.chromecastPause() : castBridge.chromecastPlay())
        .then(() => setPlaying(!playing)).catch(() => {});
      return;
    }
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) { audio.pause(); setPlaying(false); }
    else { audio.play().then(() => { setError(''); setPlaying(true); }).catch(() => {}); }
  }, [playing, currentTrack, sendToTv]);

  // A television chosen, or let go, in the middle of a track: the track goes
  // on from where it was, on the other side.
  useEffect(() => {
    const was = remoteRef.current;
    remoteRef.current = remote;
    if (was === remote || !currentTrack) return;
    const audio = audioRef.current;
    if (remote) {
      const at = audio ? audio.currentTime : 0;
      const wasPlaying = playing;
      if (audio) audio.pause();
      // Still loading: the load effect sends it once it has it.
      if (!blobCacheRef.current.has(currentTrack.id)) return;
      sendToTv(currentTrack, at)
        .then(async () => {
          if (!wasPlaying) await castBridge.chromecastPause().catch(() => {});
          setPlaying(wasPlaying);
        })
        .catch((e) => { setError(e.message || String(e)); setPlaying(false); });
    } else {
      const at = remotePosRef.current;
      remoteTrackRef.current = null;
      if (audio && at != null && isFinite(at)) audio.currentTime = at;
      if (playing && audio) audio.play().catch(() => setPlaying(false));
    }
    // eslint-disable-next-line
  }, [remote]);

  // The television's clock and state, once a second, for as long as the
  // track there is ours.
  useEffect(() => {
    if (!remote) return undefined;
    let stopped = false;
    const tick = async () => {
      if (sendingRef.current || castSession.owner !== 'music' || !remoteTrackRef.current) return;
      const s = await castBridge.status().catch(() => null);
      const c = s && s.chromecast;
      if (stopped || sendingRef.current || castSession.owner !== 'music' || !c) return;
      if (!c.connected) { setPlaying(false); return; }
      if (c.position != null) { remotePosRef.current = c.position; setCurrentTime(c.position); }
      const state = c.playerState;
      if (state === 'PLAYING' || state === 'BUFFERING') setPlaying(true);
      else if (state === 'PAUSED') setPlaying(false);
      else if (state === 'IDLE' && String(c.idleReason || '').toLowerCase() === 'finished'
               && finishedRef.current !== remoteTrackRef.current) {
        finishedRef.current = remoteTrackRef.current;
        onEndedRef.current();
      }
    };
    const id = setInterval(tick, 1000);
    tick();
    // A film or a photo took the television: the track there has stopped.
    // Not when casting stops altogether — the track then carries on here.
    const unsubscribe = castSession.subscribe(() => {
      if (castSession.device && castSession.owner !== 'music') setPlaying(false);
    });
    return () => { stopped = true; clearInterval(id); unsubscribe(); };
  }, [remote]);

  // Reshuffling keeps the currently playing track in place — turning shuffle
  // on mid-album must not interrupt what's already playing. Which track that
  // is, is `order[pos]`; see queue-ops.js on why it is not looked up by id.
  const toggleShuffle = useCallback(() => {
    const next = !shuffle;
    setShuffle(next);
    saveShuffle(next);
    dispatch({ type: 'reshuffle', shuffle: next });
  }, [shuffle]);

  const cycleRepeat = useCallback(() => {
    setRepeat((prev) => {
      const next = prev === 'off' ? 'all' : prev === 'all' ? 'one' : 'off';
      saveRepeat(next);
      return next;
    });
  }, []);

  const seek = useCallback((e) => {
    const to = parseFloat(e.target.value);
    if (remoteRef.current) {
      if (castSession.owner !== 'music') return;
      castBridge.chromecastSeek(to).catch(() => {});
      remotePosRef.current = to;
      setCurrentTime(to);
      return;
    }
    const audio = audioRef.current;
    if (audio && isFinite(audio.duration)) audio.currentTime = to;
  }, []);

  const handleClose = useCallback(() => {
    const audio = audioRef.current;
    if (audio) audio.pause();
    // The television stops with the bar; it stays chosen for what comes next.
    if (remoteRef.current && castSession.owner === 'music') {
      castSession.claim(null);
      castBridge.chromecastDisconnect().catch(() => {});
      castBridge.stop().catch(() => {});
    }
    if (onClose) onClose();
  }, [onClose]);

  if (!currentTrack) return null;

  const title = currentTrack.display_title || currentTrack.name;
  // The element's, once it has read the file; the index's until then — and
  // while casting, a file this device cannot decode still has a length.
  const shownDuration = (isFinite(duration) && duration > 0) ? duration : (currentTrack.duration || 0);
  const repeatLabel = repeat === 'off' ? t('music.player_repeat_off')
    : repeat === 'all' ? t('music.player_repeat_all') : t('music.player_repeat_one');

  return html`
    <div class="music-player-bar" ref=${barBand}>
      <audio ref=${audioRef}
        onTimeUpdate=${(e) => setCurrentTime(e.target.currentTime)}
        onDurationChange=${(e) => setDuration(e.target.duration)}
        onEnded=${onEnded} onError=${handleMediaError} />
      <div class="music-player-info">
        <${Icon} name="music" cls="music-player-icon" />
        <div class="music-player-text">
          <div class="music-player-title">${title}</div>
          <div class="music-player-sub">
            ${[currentTrack.artist, currentTrack.album].filter(Boolean).join(' · ')}
          </div>
        </div>
      </div>
      <div class="music-player-transport">
        <button class="music-player-btn ${shuffle ? 'active' : ''}"
          title=${t('music.player_shuffle')} onClick=${toggleShuffle}>
          <${Icon} name="shuffle" />
        </button>
        <button class="music-player-btn" title=${t('music.player_prev')} onClick=${skipPrev}>
          <${Icon} name="skip-prev" />
        </button>
        <button class="music-player-btn music-player-play" title=${playing ? t('music.player_pause') : t('music.player_play')}
          onClick=${togglePlaying} disabled=${loading}>
          ${loading ? html`<span class="spinner"></span>` : html`<${Icon} name=${playing ? 'pause' : 'play'} />`}
        </button>
        <button class="music-player-btn" title=${t('music.player_next')} onClick=${skipNext}>
          <${Icon} name="skip-next" />
        </button>
        <button class="music-player-btn ${repeat !== 'off' ? 'active' : ''} music-player-repeat-${repeat}"
          title=${repeatLabel} onClick=${cycleRepeat}>
          <${Icon} name="repeat" />
          ${repeat === 'one' && html`<span class="music-repeat-badge">1</span>`}
        </button>
      </div>
      <div class="music-player-seek">
        <span class="music-player-time">${formatTime(currentTime)}</span>
        <input type="range" min="0" max=${shownDuration} step="1" value=${currentTime}
          disabled=${!shownDuration} onInput=${seek} />
        <span class="music-player-time">${formatTime(shownDuration)}</span>
      </div>
      <div class="music-player-volume">
        <${Icon} name="volume" />
        <input type="range" min="0" max="1" step="0.05" value=${volume}
          title=${t('music.player_volume')} disabled=${remote}
          onInput=${(e) => setVolume(parseFloat(e.target.value))} />
      </div>
      <div class="music-player-extra">
        <${CastButton} cls="music-player-btn" up />
        <button class="music-player-btn" title=${t('music.player_queue')} onClick=${() => setShowQueue(true)}>
          <${Icon} name="menu" />
        </button>
        <button class="music-player-btn" title=${t('music.player_close')} onClick=${handleClose}>
          <${Icon} name="close" />
        </button>
      </div>
      ${error && html`<div class="music-player-error">${error}</div>`}
    </div>
    ${showQueue && html`
      <${QueuePanel} tracks=${tracks} order=${order} pos=${pos}
        onSelect=${skipTo} onClose=${() => setShowQueue(false)}
        ${/* Saved in **play order**, which is what this panel is showing: if
              shuffle is on, that freezes the shuffle, and that is what "save
              what I am listening to" means. */''}
        onSaveAsPlaylist=${onSaveQueue && ((rows) => {
          setShowQueue(false);
          onSaveQueue(rows);
        })} />
    `}
  `;
}

export { MusicPlayerBar, formatTime };