Play new songs from YouTube in the browser

YouTube's bot checks block yt-dlp from fetching audio on the server, so
suggested songs now play in YouTube's embedded player, kept out of sight,
in the browser. yt-dlp is only used to search.

- GET /api/discover/youtube/<id> returns candidate video IDs, best first,
  or the one that played before (?refresh=true searches again).
- PUT /api/discover/youtube/<id> remembers the video that played.
- The UI tries the next candidate when a video can't be embedded, searches
  again when a remembered video is gone, and skips the song otherwise.
- Drop the YouTube audio proxy, and Deno from the image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
judeandClaude Opus 5.5 committed 2026-11-23 10:59:40 +00:00
1 parent 93e12cfc72
commit c84e7e715d
11 files changed
+495 -181

No files matched your search

+6 -1
View File
@@ -96,12 +96,17 @@ export const api = {
body: JSON.stringify({ status }),
}),
rebuild: (ruleId: string) => request<void>(`/rules/${ruleId}/rebuild`, { method: "POST" }),
/** Videos to play a suggestion with, best first. `refresh` searches again. */
youtubeVideos: (suggestionId: string, refresh = false) =>
request<{ video_ids: string[]; cached: boolean }>(`/youtube/${suggestionId}?refresh=${refresh}`),
/** The video that played, when it wasn't the first one */
setYoutubeVideo: (suggestionId: string, videoId: string) =>
request<void>(`/youtube/${suggestionId}`, json("PUT", { video_id: videoId })),
};
export const coverUrl = (coverArt: string, size = 120) =>
`/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`;
export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`;
export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${suggestionId}`;
/** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */
export const mixTitle = (mix: MixSummary) =>
+3 -2
View File
@@ -1,8 +1,9 @@
import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api";
import { coverUrl, Song, streamUrl, Suggestion } from "./api";
export type QueueItem = {
key: string;
source: "library" | "youtube";
/** Audio to stream, for library songs. YouTube ones play from `suggestionId`. */
src: string;
title: string;
artist: string;
@@ -24,7 +25,7 @@ export const fromSong = (song: Song): QueueItem => ({
export const fromSuggestion = (s: Suggestion): QueueItem => ({
key: `suggestion:${s.id}`,
source: "youtube",
src: youtubeUrl(s.id),
src: "",
title: s.title,
artist: s.artist,
album: s.release,
+14
View File
@@ -1125,6 +1125,20 @@ h2 {
color: var(--accent);
}
/* YouTube's player, for new songs: only the sound is wanted. Not display: none, as browsers
may not start or may throttle players that aren't rendered. */
.youtube-host {
position: fixed;
left: 0;
bottom: 0;
z-index: -1;
width: 1px;
height: 1px;
overflow: hidden;
opacity: 0;
pointer-events: none;
}
/* ---------- small screens ---------- */
@media (max-width: 800px) {
+155 -30
View File
@@ -1,16 +1,32 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { api } from "./api";
import { QueueItem } from "./queue";
import { HiddenYouTubePlayer, State, YouTubeEvents } from "./youtubePlayer";
export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error";
export type Player = ReturnType<typeof usePlayer>;
/** The video being tried for the current YouTube item */
type YouTubeAttempt = {
suggestionId: string;
videoIds: string[];
at: number;
/** `videoIds` is the one video that played before, so a fresh search might find another */
cached: boolean;
};
/**
* Library songs play in an <audio> element, streamed from Subsonic through playlistd. New songs
* play from YouTube in a hidden embedded player, in the browser.
*/
export function usePlayer(onError: (item: QueueItem) => void) {
const audio = useRef<HTMLAudioElement | null>(null);
if (audio.current === null && typeof Audio !== "undefined") {
audio.current = new Audio();
audio.current.preload = "auto";
}
const youtube = useRef<HiddenYouTubePlayer | null>(null);
const [queue, setQueue] = useState<QueueItem[]>([]);
const [index, setIndex] = useState(-1);
@@ -18,10 +34,16 @@ export function usePlayer(onError: (item: QueueItem) => void) {
const [time, setTime] = useState(0);
const [duration, setDuration] = useState(0);
const current = index >= 0 ? queue[index] : undefined;
const onYouTube = current?.source === "youtube";
// keep the latest values for the audio element's event handlers
const state = useRef({ queue, index, onError });
state.current = { queue, index, onError };
// counts loads, so a slow YouTube lookup for a song that's been skipped is ignored
const loads = useRef(0);
const attempt = useRef<YouTubeAttempt | null>(null);
const errorTimer = useRef<number | undefined>();
// keep the latest values for event handlers
const state = useRef({ queue, index, onError, onYouTube });
state.current = { queue, index, onError, onYouTube };
const playAt = useCallback((items: QueueItem[], at: number) => {
setQueue(items);
@@ -33,45 +55,149 @@ export function usePlayer(onError: (item: QueueItem) => void) {
if (index + 1 < queue.length) setIndex(index + 1);
else {
audio.current?.pause();
youtube.current?.pause();
setStatus("paused");
}
}, []);
const previous = useCallback(() => {
const el = audio.current;
if (el && el.currentTime > 3) el.currentTime = 0;
else setIndex((i) => Math.max(0, i - 1));
}, []);
const toggle = useCallback(() => {
const el = audio.current;
if (!el || !state.current.queue.length) return;
if (el.paused) void el.play().catch(() => undefined);
else el.pause();
}, []);
/** Give up on the current item and move on */
const failed = useCallback(() => {
setStatus("error");
const { queue, index, onError } = state.current;
if (queue[index]) onError(queue[index]);
window.clearTimeout(errorTimer.current);
errorTimer.current = window.setTimeout(next, 1500);
}, [next]);
const seek = useCallback((seconds: number) => {
if (!audio.current) return;
audio.current.currentTime = seconds;
if (state.current.onYouTube) youtube.current?.seek(seconds);
else if (audio.current) audio.current.currentTime = seconds;
// update now, or the controlled slider snaps back and its change event seeks back too
setTime(seconds);
}, []);
// load the current item
const previous = useCallback(() => {
const at = state.current.onYouTube ? youtube.current?.time ?? 0 : audio.current?.currentTime ?? 0;
if (at > 3) seek(0);
else setIndex((i) => Math.max(0, i - 1));
}, [seek]);
const toggle = useCallback(() => {
if (!state.current.queue.length) return;
if (state.current.onYouTube) {
const yt = youtube.current;
if (yt?.playing) yt.pause();
else yt?.play();
return;
}
const el = audio.current;
if (!el) return;
if (el.paused) void el.play().catch(() => undefined);
else el.pause();
}, []);
// ---------- YouTube ----------
const getYouTube = useCallback(
() =>
(youtube.current ??= new HiddenYouTubePlayer({
onState: (s) => youtubeEvents.current.onState(s),
onError: (code) => youtubeEvents.current.onError(code),
})),
[],
);
/** Look up videos for a suggestion and play the first that works */
const playYouTube = useCallback(
async (suggestionId: string, load: number, refresh: boolean) => {
try {
const found = await api.youtubeVideos(suggestionId, refresh);
if (load !== loads.current) return;
attempt.current = { suggestionId, videoIds: found.video_ids, at: 0, cached: found.cached };
await getYouTube().load(found.video_ids[0]);
} catch {
if (load === loads.current) failed();
}
},
[failed, getYouTube],
);
// the player's handlers, kept current for the player made on first use
const youtubeEvents = useRef<YouTubeEvents>({ onState: () => undefined, onError: () => undefined });
youtubeEvents.current = {
onState: (s) => {
if (!state.current.onYouTube) return;
if (s === State.Playing) {
setStatus("playing");
// the first video is the one playlistd already has
const a = attempt.current;
if (a && a.at > 0) {
void api.setYoutubeVideo(a.suggestionId, a.videoIds[a.at]).catch(() => undefined);
attempt.current = { ...a, videoIds: [a.videoIds[a.at]], at: 0 };
}
} else if (s === State.Paused) setStatus("paused");
else if (s === State.Buffering) setStatus("loading");
else if (s === State.Ended) next();
},
onError: () => {
// (no attempt: the previous song's video, while this one is being looked up)
const a = attempt.current;
if (!state.current.onYouTube || !a) return;
// usually a video that can't be embedded: try the next one
if (a.at + 1 < a.videoIds.length) {
attempt.current = { ...a, at: a.at + 1 };
void getYouTube().load(a.videoIds[a.at + 1]).catch(failed);
} else if (a.cached) {
attempt.current = null;
void playYouTube(a.suggestionId, loads.current, true);
} else {
failed();
}
},
};
// the embedded player has no time events
useEffect(() => {
if (!onYouTube || status !== "playing") return;
const update = () => {
setTime(youtube.current?.time ?? 0);
setDuration(youtube.current?.duration ?? 0);
};
update();
const t = window.setInterval(update, 250);
return () => window.clearInterval(t);
}, [onYouTube, status]);
// ---------- loading items ----------
useEffect(() => {
const el = audio.current;
if (!el || !current) return;
const load = ++loads.current;
window.clearTimeout(errorTimer.current);
setTime(0);
setDuration(0);
setStatus("loading");
el.src = current.src;
void el.play().catch(() => undefined);
if (current.source === "youtube" && current.suggestionId) {
el.pause();
el.removeAttribute("src");
el.load();
attempt.current = null;
void playYouTube(current.suggestionId, load, false);
} else {
youtube.current?.stop();
el.src = current.src;
void el.play().catch(() => undefined);
}
}, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const el = audio.current;
if (!el) return;
let errorTimer: number | undefined;
// ignore the audio element while YouTube is playing (e.g. its pause on switching over)
const forAudio = (handler: () => void) => () => {
if (!state.current.onYouTube) handler();
};
const handlers: Record<string, () => void> = {
playing: () => setStatus("playing"),
pause: () => setStatus((s) => (s === "error" ? s : "paused")),
@@ -80,23 +206,22 @@ export function usePlayer(onError: (item: QueueItem) => void) {
durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0),
ended: () => next(),
error: () => {
if (!el.src) return;
setStatus("error");
const { queue, index, onError } = state.current;
if (queue[index]) onError(queue[index]);
errorTimer = window.setTimeout(next, 1500);
if (el.getAttribute("src")) failed();
},
};
for (const [event, handler] of Object.entries(handlers)) el.addEventListener(event, handler);
const bound = Object.entries(handlers).map(([event, handler]) => [event, forAudio(handler)] as const);
for (const [event, handler] of bound) el.addEventListener(event, handler);
return () => {
window.clearTimeout(errorTimer);
for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler);
for (const [event, handler] of bound) el.removeEventListener(event, handler);
};
}, [next]);
}, [next, failed]);
// stop playing when the app goes away (e.g. on logging out)
useEffect(
() => () => {
window.clearTimeout(errorTimer.current);
youtube.current?.destroy();
youtube.current = null;
const el = audio.current;
if (!el) return;
el.pause();
+158
View File
@@ -0,0 +1,158 @@
// Plays YouTube videos for their audio, with YouTube's IFrame player API, in a player that's
// kept out of sight (see .youtube-host in styles.css).
/** The parts of YT.Player used here */
type YTPlayer = {
loadVideoById(videoId: string): void;
playVideo(): void;
pauseVideo(): void;
stopVideo(): void;
seekTo(seconds: number, allowSeekAhead: boolean): void;
getCurrentTime(): number;
getDuration(): number;
getPlayerState(): number;
destroy(): void;
};
type YTNamespace = {
Player: new (
element: HTMLElement,
options: {
width: number;
height: number;
playerVars: Record<string, number>;
events: {
onReady: () => void;
onStateChange: (e: { data: number }) => void;
onError: (e: { data: number }) => void;
};
},
) => YTPlayer;
};
declare global {
interface Window {
YT?: YTNamespace;
onYouTubeIframeAPIReady?: () => void;
}
}
/** YT.PlayerState */
export const State = { Unstarted: -1, Ended: 0, Playing: 1, Paused: 2, Buffering: 3, Cued: 5 } as const;
let api: Promise<YTNamespace> | null = null;
function loadApi(): Promise<YTNamespace> {
if (window.YT?.Player) return Promise.resolve(window.YT);
api ??= new Promise<YTNamespace>((resolve, reject) => {
const previous = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
previous?.();
resolve(window.YT!);
};
const script = document.createElement("script");
script.src = "https://www.youtube.com/iframe_api";
script.async = true;
script.onerror = () => {
script.remove();
api = null;
reject(new Error("Couldn't load YouTube's player"));
};
document.head.appendChild(script);
});
return api;
}
export type YouTubeEvents = {
onState: (state: number) => void;
/** YouTube's error code: 2 bad id, 5 HTML5 error, 100 not found, 101/150 can't be embedded */
onError: (code: number) => void;
};
export class HiddenYouTubePlayer {
private player: Promise<YTPlayer> | null = null;
private ready: YTPlayer | null = null;
private host: HTMLElement | null = null;
private destroyed = false;
constructor(private events: YouTubeEvents) {}
private create(): Promise<YTPlayer> {
if (this.player) return this.player;
this.player = loadApi().then(
(YT) =>
new Promise<YTPlayer>((resolve) => {
const host = document.createElement("div");
host.className = "youtube-host";
host.setAttribute("aria-hidden", "true");
const target = document.createElement("div");
host.appendChild(target);
document.body.appendChild(host);
this.host = host;
const player = new YT.Player(target, {
width: 200,
height: 200,
playerVars: { autoplay: 1, controls: 0, disablekb: 1, fs: 0, playsinline: 1, rel: 0 },
events: {
onReady: () => {
if (this.destroyed) {
player.destroy();
host.remove();
return;
}
this.ready = player;
resolve(player);
},
onStateChange: (e) => this.events.onState(e.data),
onError: (e) => this.events.onError(e.data),
},
});
}),
);
this.player.catch(() => (this.player = null));
return this.player;
}
/** Start playing a video. Rejects if YouTube's player can't be loaded. */
async load(videoId: string) {
(await this.create()).loadVideoById(videoId);
}
play() {
this.ready?.playVideo();
}
pause() {
this.ready?.pauseVideo();
}
stop() {
this.ready?.stopVideo();
}
seek(seconds: number) {
this.ready?.seekTo(seconds, true);
}
get playing() {
return this.ready?.getPlayerState() === State.Playing;
}
get time() {
return this.ready?.getCurrentTime() ?? 0;
}
get duration() {
return this.ready?.getDuration() ?? 0;
}
destroy() {
this.destroyed = true;
this.ready?.destroy();
this.host?.remove();
this.ready = null;
this.player = null;
this.host = null;
}
}