Repository Public
1"use client";2import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";3import { api } from "@/lib/client-api";4import type { Track } from "@/lib/types";56/**7 * The player: one <audio> element that lives in the app layout (so it survives navigation), a queue, and the8 * account's playback state saved to the server. Playback always starts from a user gesture (iOS requirement):9 * a restored session shows the track paused at its saved position and waits for a tap.10 */1112export type Repeat = "off" | "all" | "one";13export type PlayerError = null | "network" | "decode" | "unsupported" | "unavailable" | "preparing_failed";14type Variant = "original" | "compat";1516interface State {17 queue: Track[]; index: number; playing: boolean; loading: boolean; preparing: boolean;18 shuffle: boolean; repeat: Repeat; volume: number; canSetVolume: boolean; error: PlayerError; variant: Variant;19}20interface Actions {21 playTracks(tracks: Track[], startIndex?: number, opts?: { shuffle?: boolean }): void;22 toggle(): void; next(): void; prev(): void; seek(ms: number): void; jumpTo(index: number): void;23 playNext(tracks: Track[]): void; addToQueue(tracks: Track[]): void; removeAt(index: number): void; move(from: number, to: number): void; clearUpcoming(): void;24 setShuffle(on: boolean): void; cycleRepeat(): void; setVolume(v: number): void; retry(): void;25 patchTrack(id: string, patch: Partial<Track>): void;26 /** Current position read from the audio clock (for frame-accurate displays such as lyrics). */27 positionMs(): number;28}29export interface Progress { positionMs: number; durationMs: number; bufferedMs: number }3031const StateCtx = createContext<State | null>(null);32const ActionsCtx = createContext<Actions | null>(null);33const ProgressCtx = createContext<Progress>({ positionMs: 0, durationMs: 0, bufferedMs: 0 });34export const usePlayer = () => useContext(StateCtx)!;35export const usePlayerActions = () => useContext(ActionsCtx)!;36export const useProgress = () => useContext(ProgressCtx);37export function useCurrentTrack(): Track | null { const s = usePlayer(); return s.queue[s.index] ?? null; }3839const streamUrl = (t: Track, v: Variant) => `/api/v1/stream/${t.id}${v === "compat" ? "?v=compat" : ""}`;40const MIME: Record<string, string> = { flac: "audio/flac", mp3: "audio/mpeg", aac: "audio/mp4", alac: 'audio/mp4; codecs="alac"', vorbis: 'audio/ogg; codecs="vorbis"', opus: 'audio/ogg; codecs="opus"' };4142/** Which file this browser should be given for a track: the original when it can decode it, the AAC rendition otherwise. */43function pickVariant(t: Track, audio: HTMLAudioElement): Variant | "none" {44 if (t.webPlayable === "yes") return "original";45 if (t.webPlayable === "some") {46 const mime = t.container === "aiff" ? "audio/aiff" : MIME[t.codec];47 if (mime && audio.canPlayType(mime) !== "") return "original";48 }49 return "compat";50}5152function shuffled<T>(a: T[]): T[] { const r = a.slice(); for (let i = r.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [r[i], r[j]] = [r[j], r[i]]; } return r; }5354export function PlayerProvider({ children }: { children: ReactNode }) {55 const audioRef = useRef<HTMLAudioElement | null>(null);56 const [state, setState] = useState<State>({ queue: [], index: 0, playing: false, loading: false, preparing: false, shuffle: false, repeat: "off", volume: 1, canSetVolume: true, error: null, variant: "original" });57 const [progress, setProgress] = useState<Progress>({ positionMs: 0, durationMs: 0, bufferedMs: 0 });58 const ref = useRef(state); ref.current = state;59 const unshuffled = useRef<Track[] | null>(null); // queue order before shuffle was switched on60 const pendingSeek = useRef<number | null>(null); // position to restore once metadata is known61 const loadedKey = useRef<string>(""); // `${trackId}:${variant}` currently in the <audio>62 const wantPlay = useRef(false);63 const consecutiveErrors = useRef(0);64 const restored = useRef(false);65 const pollTimer = useRef<ReturnType<typeof setTimeout> | null>(null);6667 const set = useCallback((p: Partial<State> | ((s: State) => Partial<State>)) => setState((s) => ({ ...s, ...(typeof p === "function" ? p(s) : p) })), []);6869 // ── Loading a track into the element ──────────────────────────────────────────────────────────────70 const load = useCallback((t: Track | undefined, opts: { play: boolean; atMs?: number; variant?: Variant }) => {71 const a = audioRef.current;72 if (pollTimer.current) { clearTimeout(pollTimer.current); pollTimer.current = null; }73 if (!a) return;74 if (!t) { a.removeAttribute("src"); a.load(); loadedKey.current = ""; set({ playing: false, loading: false, preparing: false, error: null }); setProgress({ positionMs: 0, durationMs: 0, bufferedMs: 0 }); return; }75 wantPlay.current = opts.play;76 let variant: Variant | "none" = opts.variant ?? pickVariant(t, a);77 if (variant === "compat" && t.compatState !== "ready") {78 // No rendition yet: ask the server for one and wait for it (bounded), unless it is switched off.79 if (t.compatState === "disabled" && t.webPlayable === "no") variant = "none";80 else return void prepareCompat(t, opts);81 }82 if (variant === "none") { a.removeAttribute("src"); a.load(); loadedKey.current = ""; set({ playing: false, loading: false, preparing: false, error: "unsupported" }); setProgress({ positionMs: 0, durationMs: t.durationMs, bufferedMs: 0 }); return; }83 pendingSeek.current = opts.atMs && opts.atMs > 0 ? opts.atMs : null;84 loadedKey.current = `${t.id}:${variant}`;85 a.src = streamUrl(t, variant);86 a.load();87 set({ error: null, loading: opts.play, preparing: false, variant });88 setProgress({ positionMs: opts.atMs ?? 0, durationMs: t.durationMs, bufferedMs: 0 });89 if (opts.play) a.play().catch(() => { /* surfaced by the error / pause events */ });90 // eslint-disable-next-line react-hooks/exhaustive-deps91 }, [set]);9293 const prepareCompat = useCallback((t: Track, opts: { play: boolean; atMs?: number }) => {94 const a = audioRef.current;95 if (a) { a.removeAttribute("src"); a.load(); }96 loadedKey.current = "";97 set({ preparing: true, loading: false, playing: false, error: null });98 setProgress({ positionMs: opts.atMs ?? 0, durationMs: t.durationMs, bufferedMs: 0 });99 const started = Date.now();100 const tick = async () => {101 if (ref.current.queue[ref.current.index]?.id !== t.id) return; // the listener moved on102 try {103 const cur = await api<Track>(`/api/v1/library/tracks/${t.id}`);104 if (cur.compatState === "ready") {105 set((s) => ({ queue: s.queue.map((q) => (q.id === t.id ? { ...q, compatState: "ready" } : q)) }));106 return load({ ...t, compatState: "ready" }, { ...opts, variant: "compat" });107 }108 if (cur.compatState === "error" || Date.now() - started > 4 * 60_000) return set({ preparing: false, error: "preparing_failed" });109 } catch { /* transient: keep polling */ }110 pollTimer.current = setTimeout(tick, 2000);111 };112 api(`/api/v1/library/tracks/${t.id}/compat`, { method: "POST" }).then(tick).catch(() => set({ preparing: false, error: t.webPlayable === "no" ? "unsupported" : "preparing_failed" }));113 }, [load, set]);114115 // ── Queue navigation ──────────────────────────────────────────────────────────────────────────────116 const goTo = useCallback((index: number, play: boolean) => {117 const s = ref.current;118 if (index < 0 || index >= s.queue.length) return;119 set({ index });120 load(s.queue[index], { play });121 }, [load, set]);122123 const advance = useCallback((auto: boolean) => {124 const s = ref.current;125 if (s.queue.length === 0) return;126 if (auto && s.repeat === "one") { const a = audioRef.current; if (a) { a.currentTime = 0; a.play().catch(() => {}); } return; }127 if (s.index + 1 < s.queue.length) return goTo(s.index + 1, true);128 if (s.repeat === "all") return goTo(0, true);129 if (auto) { set({ playing: false }); wantPlay.current = false; } // end of the queue130 }, [goTo, set]);131132 const actions = useMemo<Actions>(() => ({133 playTracks(tracks, startIndex = 0, opts) {134 if (tracks.length === 0) return;135 consecutiveErrors.current = 0;136 let queue = tracks, index = Math.min(Math.max(0, startIndex), tracks.length - 1);137 const shuffle = opts?.shuffle ?? ref.current.shuffle;138 if (shuffle) {139 unshuffled.current = tracks;140 const first = opts?.shuffle ? tracks[Math.floor(Math.random() * tracks.length)] : tracks[index];141 queue = [first, ...shuffled(tracks.filter((t) => t !== first))]; index = 0;142 } else unshuffled.current = null;143 set({ queue, index, shuffle });144 load(queue[index], { play: true });145 },146 toggle() {147 const a = audioRef.current, s = ref.current, t = s.queue[s.index];148 if (!a || !t) return;149 if (!loadedKey.current.startsWith(t.id)) return load(t, { play: true, atMs: pendingSeek.current ?? progressRef.current.positionMs });150 if (a.paused) { wantPlay.current = true; a.play().catch(() => {}); } else { wantPlay.current = false; a.pause(); }151 },152 next() { consecutiveErrors.current = 0; advance(false); },153 prev() {154 const a = audioRef.current, s = ref.current;155 if (a && a.currentTime > 3) { a.currentTime = 0; return; }156 if (s.index > 0) goTo(s.index - 1, true); else if (s.repeat === "all" && s.queue.length) goTo(s.queue.length - 1, true); else if (a) a.currentTime = 0;157 },158 seek(ms) {159 const a = audioRef.current;160 if (!a) return;161 if (loadedKey.current && a.readyState >= 1) a.currentTime = ms / 1000; else pendingSeek.current = ms;162 setProgress((p) => ({ ...p, positionMs: ms }));163 },164 jumpTo(index) { consecutiveErrors.current = 0; goTo(index, true); },165 playNext(tracks) {166 const s = ref.current;167 if (s.queue.length === 0) return actions.playTracks(tracks, 0, { shuffle: false });168 const queue = [...s.queue.slice(0, s.index + 1), ...tracks, ...s.queue.slice(s.index + 1)];169 set({ queue });170 },171 addToQueue(tracks) {172 const s = ref.current;173 if (s.queue.length === 0) { set({ queue: tracks, index: 0 }); load(tracks[0], { play: false }); return; }174 set({ queue: [...s.queue, ...tracks] });175 },176 removeAt(i) {177 const s = ref.current;178 if (i < 0 || i >= s.queue.length) return;179 const queue = s.queue.filter((_, k) => k !== i);180 if (i === s.index) { const index = Math.min(i, queue.length - 1); set({ queue, index: Math.max(0, index) }); load(queue[index], { play: s.playing }); }181 else set({ queue, index: i < s.index ? s.index - 1 : s.index });182 },183 move(from, to) {184 const s = ref.current;185 if (from === to || from < 0 || to < 0 || from >= s.queue.length || to >= s.queue.length) return;186 const queue = s.queue.slice(); const [x] = queue.splice(from, 1); queue.splice(to, 0, x);187 const cur = s.queue[s.index];188 set({ queue, index: queue.indexOf(cur) });189 },190 clearUpcoming() { const s = ref.current; set({ queue: s.queue.slice(0, s.index + 1) }); },191 setShuffle(on) {192 const s = ref.current, cur = s.queue[s.index];193 if (on) { unshuffled.current = s.queue; set({ shuffle: true, queue: cur ? [...s.queue.slice(0, s.index + 1), ...shuffled(s.queue.slice(s.index + 1))] : s.queue }); }194 else {195 const byId = new Map(s.queue.map((t) => [t.id, t]));196 const orig = unshuffled.current?.map((t) => byId.get(t.id)).filter((t): t is Track => !!t); unshuffled.current = null;197 if (orig && cur && orig.length === s.queue.length) set({ shuffle: false, queue: orig, index: Math.max(0, orig.findIndex((t) => t.id === cur.id)) }); else set({ shuffle: false });198 }199 },200 cycleRepeat() { set((s) => ({ repeat: s.repeat === "off" ? "all" : s.repeat === "all" ? "one" : "off" })); },201 setVolume(v) { const a = audioRef.current; const vol = Math.min(1, Math.max(0, v)); if (a) a.volume = vol; set({ volume: vol }); },202 retry() { const s = ref.current, t = s.queue[s.index]; if (t) { consecutiveErrors.current = 0; load(t, { play: true, atMs: progressRef.current.positionMs }); } },203 patchTrack(id, patch) { set((s) => ({ queue: s.queue.map((q) => (q.id === id ? { ...q, ...patch } : q)) })); },204 positionMs() { const a = audioRef.current; return a && loadedKey.current ? a.currentTime * 1000 : progressRef.current.positionMs; },205 }), [advance, goTo, load, set]);206207 const progressRef = useRef(progress); progressRef.current = progress;208209 // ── <audio> events ────────────────────────────────────────────────────────────────────────────────210 useEffect(() => {211 const a = audioRef.current;212 if (!a) return;213 // iOS ignores script volume (hardware buttons only): detect it and hide the slider there.214 const before = a.volume; a.volume = 0.5; const canSetVolume = a.volume === 0.5; a.volume = before;215 set({ canSetVolume });216217 const onTime = () => setProgress((p) => ({ ...p, positionMs: a.currentTime * 1000 }));218 const onMeta = () => {219 if (pendingSeek.current != null) { try { a.currentTime = pendingSeek.current / 1000; } catch { /* not seekable yet */ } pendingSeek.current = null; }220 const d = Number.isFinite(a.duration) ? a.duration * 1000 : ref.current.queue[ref.current.index]?.durationMs ?? 0;221 setProgress((p) => ({ ...p, durationMs: d }));222 };223 const onProgress = () => { try { const b = a.buffered; if (b.length) setProgress((p) => ({ ...p, bufferedMs: b.end(b.length - 1) * 1000 })); } catch { /* ignore */ } };224 const onPlaying = () => { consecutiveErrors.current = 0; set({ playing: true, loading: false, error: null }); };225 const onPause = () => set({ playing: false });226 const onWaiting = () => set({ loading: true });227 const onCanPlay = () => set({ loading: false });228 const onEnded = () => advance(true);229 const onError = () => {230 const s = ref.current, t = s.queue[s.index];231 if (!t || !a.error || !loadedKey.current) return;232 const code = a.error.code;233 const at = a.currentTime * 1000 || progressRef.current.positionMs;234 set({ playing: false, loading: false });235 if (code === MediaError.MEDIA_ERR_NETWORK || !navigator.onLine) return set({ error: "network" });236 // The original could not be decoded by this browser → fall back to the AAC rendition once.237 if (s.variant === "original" && (code === MediaError.MEDIA_ERR_DECODE || code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED)) {238 fetch(streamUrl(t, "original"), { method: "HEAD", credentials: "same-origin" }).then((r) => {239 if (r.status === 401) { window.location.assign("/login"); return; }240 if (!r.ok) return set({ error: "unavailable" });241 if (t.compatState === "ready") load(t, { play: wantPlay.current, atMs: at, variant: "compat" }); else prepareCompat(t, { play: wantPlay.current, atMs: at });242 }).catch(() => set({ error: "network" }));243 return;244 }245 set({ error: code === MediaError.MEDIA_ERR_DECODE ? "decode" : "unavailable" });246 // Unattended playback moves on past a broken track, but never loops through a broken queue.247 if (wantPlay.current && ++consecutiveErrors.current <= 2 && s.index + 1 < s.queue.length) setTimeout(() => { if (ref.current.queue[ref.current.index]?.id === t.id) goTo(ref.current.index + 1, true); }, 1500);248 };249 const onOnline = () => { if (ref.current.error === "network") actions.retry(); };250 const ev: [string, () => void][] = [["timeupdate", onTime], ["loadedmetadata", onMeta], ["durationchange", onMeta], ["progress", onProgress], ["playing", onPlaying], ["pause", onPause], ["waiting", onWaiting], ["canplay", onCanPlay], ["ended", onEnded], ["error", onError]];251 for (const [n, f] of ev) a.addEventListener(n, f);252 window.addEventListener("online", onOnline);253 return () => { for (const [n, f] of ev) a.removeEventListener(n, f); window.removeEventListener("online", onOnline); };254 }, [actions, advance, goTo, load, prepareCompat, set]);255256 // ── Restore the account's last session (paused) ──────────────────────────────────────────────────257 useEffect(() => {258 let alive = true;259 api<{ queue: Track[]; index: number; positionMs: number; shuffle: boolean; repeat: Repeat; volume: number }>("/api/v1/library/playback").then((p) => {260 if (!alive) return;261 restored.current = true;262 if (ref.current.queue.length > 0) return; // the listener already started something263 const a = audioRef.current; if (a) a.volume = p.volume;264 set({ queue: p.queue, index: p.index, shuffle: false, repeat: p.repeat, volume: p.volume });265 const t = p.queue[p.index];266 if (t) { pendingSeek.current = p.positionMs; setProgress({ positionMs: p.positionMs, durationMs: t.durationMs, bufferedMs: 0 }); }267 }).catch(() => { restored.current = true; });268 return () => { alive = false; };269 }, [set]);270271 // ── Save the playback state (debounced; flushed when the page is hidden) ─────────────────────────272 const lastSaved = useRef("");273 const save = useCallback((keepalive = false) => {274 if (!restored.current) return;275 const s = ref.current;276 const bodyObj = { queue: s.queue.slice(0, 2000).map((t) => t.id), index: Math.min(s.index, 1999), positionMs: Math.max(0, Math.round(progressRef.current.positionMs)), shuffle: s.shuffle, repeat: s.repeat, volume: s.volume };277 const key = JSON.stringify({ ...bodyObj, positionMs: Math.round(bodyObj.positionMs / 5000) });278 if (key === lastSaved.current) return;279 lastSaved.current = key;280 api("/api/v1/library/playback", { method: "PUT", body: bodyObj, keepalive }).catch(() => { lastSaved.current = ""; });281 }, []);282 useEffect(() => { const t = setTimeout(() => save(), 800); return () => clearTimeout(t); }, [state.queue, state.index, state.shuffle, state.repeat, state.volume, state.playing, save]);283 useEffect(() => {284 const iv = setInterval(() => { if (ref.current.playing) save(); }, 10_000);285 const flush = () => { if (document.visibilityState === "hidden") save(true); };286 document.addEventListener("visibilitychange", flush); window.addEventListener("pagehide", flush);287 return () => { clearInterval(iv); document.removeEventListener("visibilitychange", flush); window.removeEventListener("pagehide", flush); };288 }, [save]);289290 // ── System media controls (lock screen, headphones, keyboard media keys) ─────────────────────────291 const current = state.queue[state.index];292 useEffect(() => {293 if (!("mediaSession" in navigator)) return;294 if (!current) { navigator.mediaSession.metadata = null; return; }295 const art = current.album.artworkId;296 navigator.mediaSession.metadata = new MediaMetadata({297 title: current.title, artist: current.artist.name, album: current.album.title,298 artwork: art ? [96, 320, 640].map((s) => ({ src: `/api/v1/art/${art}?s=${s}`, sizes: `${s}x${s}`, type: "image/jpeg" })) : [{ src: "/icons/icon-512.png", sizes: "512x512", type: "image/png" }],299 });300 }, [current]);301 useEffect(() => {302 if (!("mediaSession" in navigator)) return;303 const ms = navigator.mediaSession;304 const h: [MediaSessionAction, MediaSessionActionHandler][] = [305 ["play", () => actions.toggle()], ["pause", () => actions.toggle()], ["previoustrack", () => actions.prev()], ["nexttrack", () => actions.next()],306 ["seekto", (d) => { if (d.seekTime != null) actions.seek(d.seekTime * 1000); }],307 ["seekbackward", (d) => actions.seek(Math.max(0, progressRef.current.positionMs - (d.seekOffset ?? 10) * 1000))],308 ["seekforward", (d) => actions.seek(progressRef.current.positionMs + (d.seekOffset ?? 10) * 1000)],309 ];310 for (const [n, f] of h) { try { ms.setActionHandler(n, f); } catch { /* action not supported here */ } }311 return () => { for (const [n] of h) { try { ms.setActionHandler(n, null); } catch { /* ignore */ } } };312 }, [actions]);313 useEffect(() => { if ("mediaSession" in navigator) navigator.mediaSession.playbackState = state.playing ? "playing" : current ? "paused" : "none"; }, [state.playing, current]);314 const posBucket = Math.floor(progress.positionMs / 5000);315 useEffect(() => {316 if (!("mediaSession" in navigator) || !navigator.mediaSession.setPositionState) return;317 const d = progress.durationMs / 1000, p = progressRef.current.positionMs / 1000;318 if (d > 0 && p <= d) { try { navigator.mediaSession.setPositionState({ duration: d, position: p, playbackRate: 1 }); } catch { /* ignore */ } }319 }, [posBucket, progress.durationMs, state.playing]);320321 return (322 <StateCtx.Provider value={state}>323 <ActionsCtx.Provider value={actions}>324 <ProgressCtx.Provider value={progress}>325 {children}326 {/* No src until the listener presses play: a restored, paused session downloads nothing. */}327 <audio ref={audioRef} preload="auto" playsInline />328 </ProgressCtx.Provider>329 </ActionsCtx.Provider>330 </StateCtx.Provider>331 );332}333