Files
music_quiz/apps/web/src/net/player.ts

497 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Hidden YouTube IFrame player with server-timed playback (docs/12 Q1, prototype tools/prototypes/iframe-sync).
* - prepare: load muted at the start position, wait until really PLAYING (an ad would come first), pause, seek back → ready
* (reloads by itself at 8s and 16s)
* - play: at server time `startAt` unmute and play from `atSec` (started late: from where everyone is now); stop by playback POSITION at `endSec`
* (checked every frame + 10ms); 0.3s drift correction every second; buffering > 0.5s → stall; muted / not playing
* 0.3s after the start → blocked
* - catchUp: back in a running question (refresh / reconnect): load muted where everyone is, then play along; a fresh
* page first waits for "참가 (소리 켜기)" (the browser blocks sound before a click), the others never stop for it
* A fake player (localStorage mq:fakePlayer = "1") lets e2e runs play 30 questions without YouTube.
*/
import { create } from 'zustand';
export type AudioEvent = 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error';
export interface PlayerState {
/** The browser let us play sound (entry click done). */
unlocked: boolean;
/** Sound was blocked: show the big "눌러서 소리 켜기" button. */
needsGesture: boolean;
/** Loading for this question (for "음원 준비 중…"). */
loading: boolean;
/** Playing right now (for the LP spin). */
playing: boolean;
/** Last known position / clip window for the progress bar. */
pos: number;
clip: { start: number; end: number | null } | null;
volume: number;
}
const VOLUME_KEY = 'mq:volume';
const readVolume = () => {
try {
const v = Number(localStorage.getItem(VOLUME_KEY));
return Number.isFinite(v) && localStorage.getItem(VOLUME_KEY) !== null ? Math.max(0, Math.min(100, v)) : 70;
} catch {
return 70;
}
};
export const usePlayer = create<PlayerState>(() => ({ unlocked: false, needsGesture: false, loading: false, playing: false, pos: 0, clip: null, volume: readVolume() }));
/** A harmless video the entry click plays at volume 0 to get sound permission (SG워너비 광, Topic — known to embed). */
const UNLOCK_VIDEO = 'VO88htcm09E';
interface Engine {
init(): Promise<void>;
unlock(): void;
load(id: string, startSec: number): void;
seek(sec: number): void;
play(): void;
pause(): void;
mute(on: boolean): void;
isMuted(): boolean;
volume(v: number): void;
time(): number;
/** YT.PlayerState: -1 unstarted, 0 ended, 1 playing, 2 paused, 3 buffering, 5 cued */
state(): number;
videoId(): string | null;
}
type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
// ---------------------------------------------------------------- real YouTube engine
declare global {
interface Window {
YT?: any;
onYouTubeIframeAPIReady?: () => void;
mqPlayer?: unknown;
}
}
function youtubeEngine(l: Listener): Engine {
let player: any = null;
let ready: Promise<void> | null = null;
let current: string | null = null;
// The player object exists before onReady, its methods only after.
const call = (m: string, ...a: unknown[]): unknown => (typeof player?.[m] === 'function' ? player[m](...a) : undefined);
return {
init() {
ready ??= new Promise<void>((resolve) => {
const host = document.createElement('div');
host.setAttribute('aria-hidden', 'true');
// Off screen, not display:none (a hidden iframe may not play).
host.style.cssText = 'position:fixed;left:-10000px;top:0;width:200px;height:200px;overflow:hidden;pointer-events:none';
const el = document.createElement('div');
host.appendChild(el);
document.body.appendChild(host);
const make = () => {
player = new window.YT.Player(el, {
width: 200,
height: 200,
playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, rel: 0, playsinline: 1, iv_load_policy: 3 },
events: {
onReady: () => resolve(),
onStateChange: (e: { data: number }) => l.onState?.(e.data),
onError: (e: { data: number }) => l.onError?.(e.data),
onAutoplayBlocked: () => l.onBlocked?.(),
},
});
};
if (window.YT?.Player) make();
else {
const prev = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
prev?.();
make();
};
const s = document.createElement('script');
s.src = 'https://www.youtube.com/iframe_api';
document.head.appendChild(s);
}
});
return ready;
},
unlock() {
if (typeof player?.loadVideoById !== 'function') return;
// Inside the click: play something with sound on (volume 0), so later starts are allowed (docs/12 Q1 소리 허용).
player.setVolume(0);
player.unMute();
if (current) player.playVideo();
else {
current = UNLOCK_VIDEO;
player.loadVideoById({ videoId: UNLOCK_VIDEO, startSeconds: 30 });
}
},
load(id, startSec) {
current = id;
player.loadVideoById({ videoId: id, startSeconds: startSec });
},
seek: (sec) => call('seekTo', sec, true),
play: () => call('playVideo'),
pause: () => call('pauseVideo'),
mute: (on) => call(on ? 'mute' : 'unMute'),
isMuted: () => !!call('isMuted'),
volume: (v) => call('setVolume', v),
time: () => (call('getCurrentTime') as number | undefined) ?? 0,
state: () => (call('getPlayerState') as number | undefined) ?? -1,
videoId: () => current,
};
}
// ---------------------------------------------------------------- fake engine for e2e (no network)
function fakeEngine(l: Listener): Engine {
let state = -1;
let base = 0;
let since = 0;
let current: string | null = null;
let muted = false;
const set = (s: number) => {
state = s;
l.onState?.(s);
};
const fake = { loadMs: 40, failNext: 0 as number, stallNext: false };
(window as unknown as { mqFake: typeof fake }).mqFake = fake;
const time = () => (state === 1 ? base + (performance.now() - since) / 1000 : base);
return {
init: () => Promise.resolve(),
unlock: () => {},
load(id, startSec) {
current = id;
base = startSec;
set(3);
if (fake.failNext) {
const code = fake.failNext;
fake.failNext = 0;
setTimeout(() => l.onError?.(code), 30);
return;
}
setTimeout(() => {
since = performance.now();
set(1);
}, fake.loadMs);
},
seek(sec) {
base = sec;
since = performance.now();
},
play() {
since = performance.now();
if (fake.stallNext) {
fake.stallNext = false;
set(3);
return;
}
if (fake.loadMs > 100) {
// slow network: buffers before playing
set(3);
setTimeout(() => {
since = performance.now();
set(1);
}, fake.loadMs);
return;
}
set(1);
},
pause() {
base = time();
set(2);
},
mute: (on) => (muted = on),
isMuted: () => muted,
volume: () => {},
time,
state: () => state,
videoId: () => current,
};
}
// ---------------------------------------------------------------- controller
let engine: Engine | null = null;
let report: (n: number, ev: AudioEvent, code?: number) => void = () => {};
let now: () => number = Date.now;
/** Every command bumps the token; async steps of older commands stop. */
let token = 0;
let curN = 0;
let loop: { raf: number; iv: ReturnType<typeof setInterval>; drift: ReturnType<typeof setInterval> } | null = null;
let bufferingSince: number | null = null;
let stallSent = false;
let pendingReady: { n: number; tk: number; at: number } | null = null;
let timeline: { startAt: number; atSec: number; endSec: number | null } | null = null;
/** catchUp loaded but this page has no click yet: play along right after "참가 (소리 켜기)". */
let pendingCatchUp: { n: number; tk: number; startAt: number; atSec: number; endSec: number | null } | null = null;
/** 소리 크기 맞추기: the current song's factor from the server (prepare / catchup); the player gets volume × gain. */
let gain = 1;
const applyVolume = (e: Engine) => e.volume(Math.round(usePlayer.getState().volume * gain));
const useFake = () => {
try {
return localStorage.getItem('mq:fakePlayer') === '1';
} catch {
return false;
}
};
function eng(): Engine {
if (!engine) {
const l: Listener = {
onState: (s) => {
if (s === 3 && timeline) bufferingSince ??= performance.now();
else bufferingSince = null;
if (s === 0 && timeline) clipEnded();
},
onError: (code) => {
usePlayer.setState({ loading: false });
report(curN, 'error', code);
},
onBlocked: () => blocked(),
};
engine = useFake() ? fakeEngine(l) : youtubeEngine(l);
window.mqPlayer = { pos: () => engine!.time(), state: () => engine!.state(), muted: () => engine!.isMuted(), video: () => engine!.videoId() };
}
return engine;
}
const waitFor = (pred: () => boolean, ms: number, tk: number) =>
new Promise<boolean>((res) => {
const t0 = performance.now();
const iv = setInterval(() => {
if (tk !== token) return (clearInterval(iv), res(false));
if (pred()) return (clearInterval(iv), res(true));
if (performance.now() - t0 > ms) return (clearInterval(iv), res(false));
}, 20);
});
function stopLoop(): void {
if (!loop) return;
cancelAnimationFrame(loop.raf);
clearInterval(loop.iv);
clearInterval(loop.drift);
loop = null;
}
function blocked(): void {
if (!timeline) return;
usePlayer.setState({ needsGesture: true, playing: false });
report(curN, 'blocked');
}
function clipEnded(): void {
if (!timeline) return;
const e = eng();
e.pause();
stopLoop();
timeline = null;
usePlayer.setState({ playing: false, pos: e.time() });
report(curN, 'clipEnd');
}
export const player = {
/** Wire reports to the server and the server clock. */
setup(r: typeof report, serverNow: () => number): void {
report = r;
now = serverNow;
},
/** Load the API early (waiting room), so the entry click can unlock at once. */
warm(): void {
void eng().init();
},
/** Call inside a click: "참가 (소리 켜기)" / "눌러서 소리 켜기". */
unlock(): void {
const e = eng();
e.unlock();
const held = pendingReady;
pendingReady = null;
const along = pendingCatchUp?.tk === token ? pendingCatchUp : null;
pendingCatchUp = null;
usePlayer.setState({ unlocked: true, needsGesture: false });
const tk = token;
const release = () => held && held.tk === token && report(held.n, 'ready');
if (useFake()) return void (along ? player.play(along.n, along.startAt, along.atSec, along.endSec) : release());
void waitFor(() => e.state() === 1, 5000, tk).then(async () => {
applyVolume(e);
if (tk !== token || timeline) return;
// Came back mid-question: join the music where everyone is now.
if (along) return player.play(along.n, along.startAt, along.atSec, along.endSec);
e.pause();
if (!held) return;
// The question was waiting for this click: back to the position everyone resumes from, then ready.
await waitFor(() => e.state() === 2, 2000, tk);
if (tk !== token) return;
e.seek(held.at);
release();
});
},
async prepare(n: number, videoId: string, startSec: number, endSec: number | null, g = 1): Promise<void> {
const tk = ++token;
curN = n;
gain = g;
stopLoop();
timeline = null;
pendingReady = null;
pendingCatchUp = null;
usePlayer.setState({ loading: true, playing: false, pos: startSec, clip: { start: startSec, end: endSec } });
const e = eng();
await e.init();
if (tk !== token) return;
e.mute(true);
const load = () => {
if (e.videoId() === videoId && e.state() !== -1 && e.state() !== 5) {
e.seek(startSec);
e.play();
} else e.load(videoId, startSec);
};
load();
// Not playing yet: reload at 8s and 16s (docs/12 Q1), then keep waiting for the host's decision.
let ok = await waitFor(() => e.state() === 1, 8000, tk);
if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 8000, tk)));
if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 600_000, tk)));
if (!ok || tk !== token) return;
e.pause();
await waitFor(() => e.state() === 2, 3000, tk);
if (tk !== token) return;
e.seek(startSec);
usePlayer.setState({ loading: false, pos: startSec });
if (usePlayer.getState().needsGesture) pendingReady = { n, tk, at: startSec };
else report(n, 'ready');
},
play(n: number, startAt: number, atSec: number, endSec: number | null): void {
const tk = ++token;
curN = n;
stopLoop();
pendingReady = null;
pendingCatchUp = null;
const e = eng();
timeline = { startAt, atSec, endSec };
stallSent = false;
bufferingSince = null;
usePlayer.setState({ clip: { start: usePlayer.getState().clip?.start ?? atSec, end: endSec }, pos: atSec });
const go = () => {
if (tk !== token) return;
applyVolume(e);
e.mute(false);
// On time this is atSec; joining a running timeline (catchUp, a late start) it is where everyone is now.
const at = atSec + Math.max(0, now() - startAt) / 1000;
if (Math.abs(e.time() - at) > 0.15) e.seek(at);
e.play();
usePlayer.setState({ playing: true });
// 소리 확인 (docs/12 Q1): 0.3s later it must be unmuted and playing.
setTimeout(() => {
if (tk !== token || !timeline) return;
if (e.isMuted() || (e.state() !== 1 && e.state() !== 3)) blocked();
}, 300);
const check = () => {
if (tk !== token || !timeline) return;
const t = e.time();
if (endSec !== null && t >= endSec) return clipEnded();
if (bufferingSince !== null && !stallSent && performance.now() - bufferingSince > 500) {
stallSent = true;
report(n, 'stall');
}
if (loop) loop.raf = requestAnimationFrame(check);
};
loop = {
raf: requestAnimationFrame(check),
iv: setInterval(check, 10),
drift: setInterval(() => {
if (tk !== token || !timeline || e.state() !== 1) return;
const expected = atSec + (now() - startAt) / 1000;
const t = e.time();
usePlayer.setState({ pos: t });
if (Math.abs(t - expected) > 0.3) e.seek(expected);
}, 1000),
};
};
const wait = startAt - now();
if (wait > 0) setTimeout(go, wait);
else go();
},
/** Back in a question whose music is running (refresh / reconnect): load muted where everyone is, then play along. */
async catchUp(n: number, videoId: string, clipStart: number, startAt: number, atSec: number, endSec: number | null, g = 1): Promise<void> {
const at = () => atSec + Math.max(0, now() - startAt) / 1000;
if (endSec !== null && at() >= endSec) return; // the clip is over: nothing to hear until the next question
const tk = ++token;
curN = n;
gain = g;
stopLoop();
timeline = null;
pendingReady = null;
pendingCatchUp = null;
usePlayer.setState({ loading: true, playing: false, pos: at(), clip: { start: clipStart, end: endSec } });
const e = eng();
await e.init();
if (tk !== token) return;
e.mute(true);
if (e.videoId() === videoId && e.state() !== -1 && e.state() !== 5) {
e.seek(at());
e.play();
} else e.load(videoId, at());
let ok = await waitFor(() => e.state() === 1, 8000, tk);
if (!ok && tk === token) (e.load(videoId, at()), (ok = await waitFor(() => e.state() === 1, 8000, tk)));
if (!ok || tk !== token) return;
usePlayer.setState({ loading: false });
const s = usePlayer.getState();
if (!s.unlocked || s.needsGesture) {
// A fresh page: the browser allows sound only after a click. Wait muted; "참가 (소리 켜기)" starts it in sync.
e.pause();
pendingCatchUp = { n, tk, startAt, atSec, endSec };
return;
}
player.play(n, startAt, atSec, endSec);
},
pause(): void {
token++;
stopLoop();
timeline = null;
pendingReady = null;
pendingCatchUp = null;
const e = engine;
if (e && e.state() === 1) e.pause();
usePlayer.setState({ playing: false, loading: false, pos: e?.time() ?? 0 });
},
/** 정답 공개: the music goes on for the reveal (docs/05 정답 공개), then stops. */
reveal(ms: number): void {
const tk = ++token;
stopLoop();
timeline = null;
const e = engine;
if (!e || !e.videoId() || e.videoId() === UNLOCK_VIDEO || usePlayer.getState().needsGesture) return;
applyVolume(e);
e.mute(false);
e.play();
usePlayer.setState({ playing: true, loading: false });
setTimeout(() => {
if (tk !== token) return;
e.pause();
usePlayer.setState({ playing: false });
}, ms);
},
stop(): void {
player.pause();
usePlayer.setState({ clip: null, pos: 0 });
},
setVolume(v: number): void {
const vol = Math.max(0, Math.min(100, Math.round(v)));
usePlayer.setState({ volume: vol });
try {
localStorage.setItem(VOLUME_KEY, String(vol));
} catch {
/* private mode */
}
if (engine) applyVolume(engine);
},
time(): number {
return engine?.time() ?? 0;
},
};