import { Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js"; import { IconPause, IconPlay, IconSkipBack, IconSkipForward, IconVolume, IconVolumeLow, IconVolumeMute, } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { formatDurationClock } from "@/lib/format"; import { useT } from "@/stores/preferences-context"; const SKIP_SECS = 15; const RATES = [0.75, 1, 1.25, 1.5, 2] as const; const RATE_KEY = "hezarfen.audio.rate"; const VOLUME_KEY = "hezarfen.audio.volume"; // One episode plays at a time: starting a player pauses whichever other one // was playing, so a history list never talks over itself. const players = new Set(); function readStored(key: string, fallback: number, valid: (value: number) => boolean): number { if (typeof localStorage === "undefined") return fallback; const value = Number(localStorage.getItem(key)); return localStorage.getItem(key) != null && Number.isFinite(value) && valid(value) ? value : fallback; } function store(key: string, value: number) { if (typeof localStorage !== "undefined") localStorage.setItem(key, String(value)); } /** What a caller can drive from outside — the transcript seeks through it. */ export type AudioPlayerController = { seek: (secs: number) => void; play: () => void; }; export type AudioPlayerProps = { src: string; title?: string; subtitle?: string; /** * The server's own running time, shown until the file's metadata arrives — * and kept when a chunked stream never reports a finite duration. */ durationHint?: number | null; autoplay?: boolean; /** Trailing controls on the title row (download, …). */ actions?: JSX.Element; /** Extra controls at the end of the transport row (transcript toggle, …). */ extra?: JSX.Element; /** * Loads the whole file. Given, a seek the stream cannot serve (a server * that ignores `Range` leaves `seekable` empty) switches the player to a * local copy of it instead of snapping back to 0:00. */ loadBlob?: (signal: AbortSignal) => Promise; onTimeUpdate?: (secs: number) => void; controller?: (controller: AudioPlayerController) => void; class?: string; }; /** * The app's audio player: one play/pause, ±15 s skips, a draggable seek bar, * playback speed and volume — in place of the browser's own `controls` strip, * which looks different in every browser and offers no speed or skip. * * The seek bar and volume are native range inputs laid over a drawn track, so * keyboard and screen-reader behaviour comes from the platform. Speed and * volume are remembered across episodes on this device. */ export function AudioPlayer(props: AudioPlayerProps) { const t = useT(); let audio!: HTMLAudioElement; const [playing, setPlaying] = createSignal(false); const [buffering, setBuffering] = createSignal(false); const [current, setCurrent] = createSignal(0); const [mediaDuration, setMediaDuration] = createSignal(null); const [buffered, setBuffered] = createSignal(0); const [rate, setRate] = createSignal(readStored(RATE_KEY, 1, (v) => (RATES as readonly number[]).includes(v))); const [volume, setVolume] = createSignal(readStored(VOLUME_KEY, 1, (v) => v >= 0 && v <= 1)); const [muted, setMuted] = createSignal(false); const [failed, setFailed] = createSignal(false); // Seeking waits on the local copy; the seek bar already shows the target. const [seeking, setSeeking] = createSignal(false); // No src until the element is in the live document. A boundary // renders its children detached first, and Chromium refuses a media load // that starts off-document ("Media load rejected by URL safety check"). const [source, setSource] = createSignal(); let connected = false; let retriedLoad = false; let disposed = false; // The local copy of the file, loaded once per `src` on first play or on the // first seek the stream cannot serve. let objectUrl: string | null = null; let localLoad: Promise | null = null; let abort: AbortController | null = null; let pendingSeek: number | null = null; let resumeAfterSeek = false; let seekToken = 0; let afterLoad: (() => void) | null = null; const dropLocal = () => { abort?.abort(); abort = null; localLoad = null; if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; }; const loadLocal = (): Promise => { const load = props.loadBlob; if (!load) return Promise.resolve(null); if (!localLoad) { const controller = new AbortController(); abort = controller; localLoad = load(controller.signal).then( (blob) => { if (controller.signal.aborted) return null; objectUrl = URL.createObjectURL(blob); return objectUrl; }, () => { if (abort === controller) localLoad = null; return null; }, ); } return localLoad; }; // A seek is instant only where the audio is actually here: the local copy, // or a range the stream has already buffered. `seekable` is not trusted — // Safari reports the whole file as seekable on a stream that ignores Range, // then keeps playing from the old spot. const canSeekTo = (secs: number) => { if (objectUrl && source() === objectUrl) return true; const ranges = audio.buffered; for (let i = 0; i < ranges.length; i += 1) { if (secs >= ranges.start(i) && secs <= ranges.end(i) - 0.5) return true; } return false; }; const duration = () => mediaDuration() ?? (props.durationHint && props.durationHint > 0 ? props.durationHint : null); const fraction = (value: number) => { const total = duration(); return total ? Math.min(1, Math.max(0, value / total)) : 0; }; const seek = (secs: number) => { const total = duration(); const next = Math.max(0, total ? Math.min(total, secs) : secs); setCurrent(next); if (!props.loadBlob || canSeekTo(next)) { audio.currentTime = next; return; } // The stream cannot go there: hold the target, pause the stream at its // wrong position, and resume from the target on the local copy. const token = ++seekToken; pendingSeek = next; resumeAfterSeek ||= !audio.paused; audio.pause(); setSeeking(true); void loadLocal().then((url) => { if (token !== seekToken) return; const at = pendingSeek ?? next; const resume = resumeAfterSeek; pendingSeek = null; resumeAfterSeek = false; if (!url) { setSeeking(false); setCurrent(audio.currentTime); setFailed(true); return; } afterLoad = () => { audio.currentTime = at; setCurrent(at); setSeeking(false); if (resume) play(); }; if (source() === url) { const run = afterLoad; afterLoad = null; run(); } else { setSource(url); } }); }; const play = () => { if (pendingSeek != null) { resumeAfterSeek = true; return; } setFailed(false); void audio.play().catch(() => { // A refused autoplay or an aborted load is not a broken file; the // `error` event reports the latter on its own. setPlaying(false); }); }; const toggle = () => { if (pendingSeek != null) resumeAfterSeek = !resumeAfterSeek; else if (audio.paused) play(); else audio.pause(); }; // Skips stack on a pending seek's target, not on the stalled stream. const skip = (delta: number) => seek((pendingSeek ?? audio.currentTime) + delta); const cycleRate = () => { const index = RATES.indexOf(rate() as (typeof RATES)[number]); setRate(RATES[(index + 1) % RATES.length]); }; const toggleMute = () => { if (muted() || volume() === 0) { setMuted(false); if (volume() === 0) setVolume(1); } else { setMuted(true); } }; onMount(() => { const attach = () => { if (disposed) return; if (!audio.isConnected) { requestAnimationFrame(attach); return; } connected = true; setSource(objectUrl ?? props.src); }; attach(); players.add(audio); props.controller?.({ seek, play }); }); onCleanup(() => { disposed = true; players.delete(audio); audio?.pause(); dropLocal(); }); createEffect(() => { audio.playbackRate = rate(); store(RATE_KEY, rate()); }); createEffect(() => { audio.volume = volume(); audio.muted = muted(); store(VOLUME_KEY, volume()); }); // A new episode in the same player starts from its own beginning. createEffect(() => { const src = props.src; dropLocal(); seekToken += 1; pendingSeek = null; resumeAfterSeek = false; afterLoad = null; setSeeking(false); retriedLoad = false; if (connected) setSource(src); setCurrent(0); setMediaDuration(null); setBuffered(0); setFailed(false); }); const onKeyDown = (event: KeyboardEvent) => { if (event.altKey || event.ctrlKey || event.metaKey) return; const target = event.target as HTMLElement; if (target.tagName === "INPUT" && (target as HTMLInputElement).type !== "range") return; const key = event.key.toLowerCase(); if (key === "k" || (key === " " && target.tagName !== "BUTTON")) { event.preventDefault(); toggle(); } else if (key === "j") { skip(-SKIP_SECS); } else if (key === "l") { skip(SKIP_SECS); } else if (key === "m") { toggleMute(); } }; const syncDuration = () => { const value = audio.duration; setMediaDuration(Number.isFinite(value) && value > 0 ? value : null); }; const syncBuffered = () => { const ranges = audio.buffered; setBuffered(ranges.length ? ranges.end(ranges.length - 1) : 0); }; const volumeIcon = () => { if (muted() || volume() === 0) return ; if (volume() < 0.5) return ; return ; }; const rateLabel = () => `${rate().toLocaleString(undefined, { maximumFractionDigits: 2 })}×`; const ghostButton = "inline-flex h-8 items-center justify-center gap-1 rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"; return (