summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/music-player.js
blob: 73cae27c5ad3ec00637c131c5c2b496f2a588beb (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
import {
  html, useState, useEffect, useRef, useCallback,
} from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import { CHUNK_SIZE, pipelinedDownload } from './file-utils.js';

/**
 * The Music app's persistent player bar (docs/musicbay.md §2.3, §7.2).
 *
 * Owned and rendered by group-page.js, *not* by music-app.js: it is the one
 * piece of this feature that lives outside the tab-switched area, so
 * playback survives navigating to Chat or Files, exactly the way the
 * video/preview modals are shell-owned rather than owned by whichever app
 * opened them. music-app.js never touches audio state directly — it only
 * calls `onPlayQueue(tracks, startIndex)`, threaded down from group-page.js,
 * to hand this component a new queue.
 *
 * 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 musicbay.md §2.2. 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.
 */

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',
};

// Kept in sync with the node's BROWSER_INCOMPATIBLE_AUDIO_EXTS
// (webrtc_server.py) — both name the same two formats no mainstream
// browser's <audio> element decodes natively.
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')}`;
}

function shuffledOrder(n, keepFirst) {
  const order = Array.from({ length: n }, (_, i) => i);
  // Fisher-Yates, then move keepFirst to the front so shuffling on doesn't
  // interrupt whatever is already playing.
  for (let i = order.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [order[i], order[j]] = [order[j], order[i]];
  }
  if (keepFirst != null) {
    const at = order.indexOf(keepFirst);
    if (at > 0) { order.splice(at, 1); order.unshift(keepFirst); }
  }
  return order;
}

// Bounded: only the currently playing track plus a one-track read-ahead 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.
const MAX_CACHED_BLOBS = 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 }) {
  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>
          <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({ transportRef, gekRef, queue, onClose }) {
  const audioRef = useRef(null);
  const blobCacheRef = useRef(new Map()); // file id -> { url, order: insertion index }
  const blobInsertRef = useRef(0);
  const loadTokenRef = useRef(0);

  const [tracks, setTracks] = useState([]);
  const [order, setOrder] = useState([]);
  const [pos, setPos] = useState(0); // index into `order`
  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 currentTrack = tracks[order[pos]] || null;

  const advancePastFailure = useCallback(() => {
    consecutiveFailuresRef.current += 1;
    if (consecutiveFailuresRef.current > MAX_CONSECUTIVE_FAILURES || order.length <= 1) return;
    if (pos + 1 < order.length) setPos(pos + 1);
    else if (repeat === 'all') setPos(0);
  }, [order.length, 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);
  }, []);

  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);
    }
  }, []);

  const fetchTrackBlob = useCallback(async (entry) => {
    const cached = blobCacheRef.current.get(entry.id);
    if (cached) return cached.url;
    const transport = transportRef.current;
    if (!transport) throw new Error(t('music.err_transport'));
    // A track ending (or "next") right after a screen-lock reconnect started
    // is exactly when this used to throw: `connected` was still false because
    // the reconnect it only had to wait a few seconds for hadn't landed yet.
    // waitForReconnect is a no-op when nothing is in flight, so this costs
    // nothing on the ordinary path.
    if (!transport.connected) await transport.waitForReconnect();
    if (!transport.connected) throw new Error(t('music.err_transport'));

    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, gekRef.current, downloadId, totalChunks);
    const blob = new Blob(chunks, { type: mime });
    const url = URL.createObjectURL(blob);
    // Keyed by the track's own id, not `downloadId` — the transcode cache
    // hash is an implementation detail of getting there, and a second play
    // of the same track must still hit this cache rather than re-requesting
    // a transcode the node already ran once.
    blobCacheRef.current.set(entry.id, { url, order: blobInsertRef.current++ });
    evictOldBlobs();
    return url;
  }, [transportRef, gekRef, evictOldBlobs]);

  // Silently warms the cache for the next track so pressing "next" doesn't
  // visibly wait (musicbay.md §2.2) — best-effort, never surfaces an error.
  const prefetchNext = useCallback((fromPos) => {
    const nextEntry = tracks[order[fromPos + 1]];
    if (!nextEntry || blobCacheRef.current.has(nextEntry.id)) return;
    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 n = queue.tracks.length;
    const initialOrder = shuffle ? shuffledOrder(n, queue.startIndex) : Array.from({ length: n }, (_, i) => i);
    const startPos = shuffle ? 0 : queue.startIndex;
    setTracks(queue.tracks);
    setOrder(initialOrder);
    setPos(startPos);
    setError('');
    consecutiveFailuresRef.current = 0;
    // Playback itself starts from the effect below, keyed on [tracks, order, pos].
  }, [queue]);

  // 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(() => {
    if (!currentTrack) return;
    const myToken = ++loadTokenRef.current;
    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;
        await audio.play();
        consecutiveFailuresRef.current = 0;
        setPlaying(true);
        prefetchNext(pos);
      } catch (err) {
        if (loadTokenRef.current !== myToken) return;
        setError(err.message || String(err));
        setPlaying(false);
        advancePastFailure();
      } finally {
        if (loadTokenRef.current === myToken) setLoading(false);
      }
    })();
    // eslint-disable-next-line
  }, [currentTrack && currentTrack.id]);

  // 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(() => {
    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) => setPos(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.
    const audio = audioRef.current;
    if (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') {
      const audio = audioRef.current;
      if (audio) { audio.currentTime = 0; audio.play().catch(() => {}); }
      return;
    }
    skipNext();
  }, [repeat, skipNext]);

  const togglePlaying = useCallback(() => {
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) { audio.pause(); setPlaying(false); }
    else { audio.play().then(() => setPlaying(true)).catch(() => {}); }
  }, [playing]);

  const toggleShuffle = useCallback(() => {
    setShuffle((prev) => {
      const next = !prev;
      saveShuffle(next);
      // Reshuffling keeps the currently playing track in place — turning
      // shuffle on mid-album must not interrupt what's already playing.
      const currentId = tracks[order[pos]] && tracks[order[pos]].id;
      const currentIdx = tracks.findIndex((tr) => tr.id === currentId);
      const newOrder = next
        ? shuffledOrder(tracks.length, currentIdx)
        : Array.from({ length: tracks.length }, (_, i) => i);
      setOrder(newOrder);
      setPos(next ? 0 : currentIdx);
      return next;
    });
  }, [tracks, order, pos]);

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

  const seek = useCallback((e) => {
    const audio = audioRef.current;
    if (audio && isFinite(audio.duration)) audio.currentTime = parseFloat(e.target.value);
  }, []);

  const handleClose = useCallback(() => {
    const audio = audioRef.current;
    if (audio) audio.pause();
    if (onClose) onClose();
  }, [onClose]);

  if (!currentTrack) return null;

  const title = currentTrack.display_title || currentTrack.name;
  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">
      <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=${duration || 0} step="1" value=${currentTime}
          disabled=${!duration} onInput=${seek} />
        <span class="music-player-time">${formatTime(duration)}</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')}
          onInput=${(e) => setVolume(parseFloat(e.target.value))} />
      </div>
      <div class="music-player-extra">
        <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)} />
    `}
  `;
}

export { MusicPlayerBar, formatTime };