5~7단계 게임: 숨긴 유튜브 동기화 재생(전원 준비·버퍼링이면 모두 멈춤·30초 늦은 사람 제외·재생 오류 곡 교체), 정답 판정·점수·정답 블록, 입력 중·단축키, 힌트·스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기 + 마지막 사람이 나가면 방 바로 닫기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:11:14 +09:00
parent af2dce5b50
commit 7266fc8d25
27 changed files with 3461 additions and 46 deletions

444
apps/web/src/net/player.ts Normal file
View File

@@ -0,0 +1,444 @@
/**
* 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`; 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
* 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;
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;
usePlayer.setState({ unlocked: true, needsGesture: false });
const tk = token;
const release = () => held && held.tk === token && report(held.n, 'ready');
if (useFake()) return void release();
void waitFor(() => e.state() === 1, 5000, tk).then(async () => {
e.volume(usePlayer.getState().volume);
if (tk !== token || timeline) return;
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): Promise<void> {
const tk = ++token;
curN = n;
stopLoop();
timeline = null;
pendingReady = 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;
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;
e.volume(usePlayer.getState().volume);
e.mute(false);
if (Math.abs(e.time() - atSec) > 0.15) e.seek(atSec);
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();
},
pause(): void {
token++;
stopLoop();
timeline = null;
pendingReady = 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;
e.volume(usePlayer.getState().volume);
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 */
}
engine?.volume(vol);
},
time(): number {
return engine?.time() ?? 0;
},
};

View File

@@ -2,8 +2,9 @@
* One WebSocket per tab (docs/01): reconnects with backoff, re-joins the room, keeps the server clock offset (docs/12 Q1).
*/
import { create } from 'zustand';
import type { ChatLine, RoomView, ServerMessage } from '@mq/shared/lite';
import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
import { player } from './player';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
@@ -21,6 +22,12 @@ interface RoomState {
chat: ChatLine[];
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
pending: { n: string; text: string }[];
/** The running game (docs/05), null in the waiting room. */
game: GameView | null;
/** Who is typing (docs/06 입력 중). */
typing: string[];
/** Last 퀴즈 저장 result. */
saved: { id: number; name: string } | null;
}
const CHAT_KEEP = 200;
@@ -28,7 +35,7 @@ const CHAT_KEEP = 200;
const LAST_ROOM_KEY = 'mq:lastRoom';
export const ROOM_GONE_TEXT = '서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.';
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [] }));
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [], game: null, typing: [], saved: null }));
let ws: WebSocket | null = null;
let retry = 0;
@@ -37,6 +44,7 @@ let pingTimer: ReturnType<typeof setInterval> | null = null;
/** A join is on its way: the next error is the join's answer. */
let joining = false;
let nonce = 0;
let myId = '';
function lastRoom(): string | null {
try {
@@ -70,6 +78,7 @@ function syncClock(): void {
function onMessage(m: ServerMessage): void {
switch (m.t) {
case 'welcome': {
myId = m.userId;
useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() });
retry = 0;
syncClock();
@@ -99,13 +108,40 @@ function onMessage(m: ServerMessage): void {
case 'left':
if (m.code === useRoom.getState().code) {
setLastRoom(null);
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] });
player.stop();
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [], game: null, typing: [] });
}
return;
case 'chatlog':
// (Re)joined: the server's log is the truth; unconfirmed lines from before a drop are gone.
if (m.code === useRoom.getState().code) useRoom.setState({ chat: m.lines.slice(-CHAT_KEEP), pending: [] });
return;
case 'game': {
if (m.code !== useRoom.getState().code) return;
const prev = useRoom.getState().game;
const g = m.game;
if (!g || g.phase === 'result') player.stop();
else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150));
useRoom.setState({ game: g });
return;
}
case 'prepare':
if (m.code === useRoom.getState().code) void player.prepare(m.n, m.videoId, m.startSec, m.endSec);
return;
case 'play':
if (m.code === useRoom.getState().code) player.play(m.n, m.startAt, m.atSec, m.endSec);
return;
case 'pause':
if (m.code === useRoom.getState().code) player.pause();
return;
case 'typing':
if (m.code === useRoom.getState().code) useRoom.setState({ typing: m.ids });
return;
case 'saved':
useRoom.setState({ saved: { id: m.id, name: m.name } });
toast(`"${m.name}"(으)로 저장했어요.`);
return;
case 'answer':
case 'chat':
if (m.code === useRoom.getState().code) {
const st = useRoom.getState();
@@ -166,14 +202,15 @@ export const socket = {
join(code: string, pw?: string): void {
password = pw;
const st = useRoom.getState();
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [] }) });
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [], game: null, typing: [] }) });
socket.start();
sendJoin(code);
},
leave(): void {
send({ t: 'leave' });
setLastRoom(null);
useRoom.setState({ code: null, room: null, chat: [], pending: [] });
player.stop();
useRoom.setState({ code: null, room: null, chat: [], pending: [], game: null, typing: [] });
},
chat(text: string): void {
const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`;
@@ -185,3 +222,5 @@ export const socket = {
/** Server clock (ms) for countdowns and synced playback. */
export const serverNow = () => Date.now() + useRoom.getState().offset;
player.setup((n, ev, code) => send({ t: 'audio', n, ev, code }), serverNow);