feat(npc-dialogue): preload, replay and a progress hairline for voice clips
Clips were fetched the moment their line started, so every spoken line paid for the download at the worst possible moment. The next node's clip is now fetched into an object-URL cache while the current line is still being read: the URL comes from the node's own voice.filename, so no server round trip is needed. Each voiced line has a Replay control beside the speaker label, and a cyan hairline fills under the line from audio timeupdate while it plays, keyed by log entry id so only the line actually playing shows progress. Measured with two 2s clips: the second file was requested 2.8s before its line appeared, hairline widths climbed 0 to 123px, two Replay buttons rendered, and a replay restarted the clip (currentTime 2.0 to 0.56, unpaused) and brought the hairline back. The cache is bounded at 8 object URLs, revoked on eviction and on unmount.
This commit is contained in:
parent
b71e94b23d
commit
4bfa34a775
2 changed files with 142 additions and 4 deletions
|
|
@ -172,6 +172,14 @@ export function NpcConversation({
|
|||
const [soundOn, setSoundOn] = useState(voice);
|
||||
const soundOnRef = useRef(soundOn);
|
||||
soundOnRef.current = soundOn;
|
||||
|
||||
/** Which line's clip is playing, and how far through it is, for the progress
|
||||
* hairline under that line. */
|
||||
const [playing, setPlaying] = useState<{ id: string; ratio: number } | null>(null);
|
||||
/** Fetched clips, keyed by their server URL, as object URLs so the next line
|
||||
* starts from memory instead of the network. Bounded, and revoked on eviction. */
|
||||
const clipCacheRef = useRef<Map<string, string>>(new Map());
|
||||
const clipPendingRef = useRef<Set<string>>(new Set());
|
||||
/** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation.
|
||||
* Purely local: it resets on every `begin()`, so a choice hidden here
|
||||
* reappears the next time the conversation is opened. Persist across
|
||||
|
|
@ -208,6 +216,47 @@ export function NpcConversation({
|
|||
|
||||
const nextId = () => `entry-${seq.current++}`;
|
||||
|
||||
/** The URL to hand the audio element: the in-memory copy when it has been
|
||||
* fetched, the server URL otherwise. */
|
||||
const playableUrl = (url: string) => clipCacheRef.current.get(url) ?? url;
|
||||
|
||||
/** Fetch a clip before its line arrives. Failure is silent: the line then
|
||||
* loads its clip the old way, one request later. */
|
||||
const preloadClip = (url: string | undefined) => {
|
||||
if (!url || !soundOnRef.current) return;
|
||||
if (clipCacheRef.current.has(url) || clipPendingRef.current.has(url)) return;
|
||||
clipPendingRef.current.add(url);
|
||||
void fetch(url)
|
||||
.then((res) => (res.ok ? res.blob() : null))
|
||||
.then((blob) => {
|
||||
if (!blob) return;
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const cache = clipCacheRef.current;
|
||||
cache.set(url, objectUrl);
|
||||
// Eight clips is a few hundred kB and covers the usual branch depth.
|
||||
while (cache.size > 8) {
|
||||
const [oldest, value] = [...cache.entries()][0] ?? [];
|
||||
if (!oldest) break;
|
||||
URL.revokeObjectURL(value);
|
||||
cache.delete(oldest);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => clipPendingRef.current.delete(url));
|
||||
};
|
||||
|
||||
// Release the prefetched clips when the dialog goes away. Object URLs are not
|
||||
// collected on their own, so without this every opened conversation would
|
||||
// leave a few hundred kB behind.
|
||||
useEffect(
|
||||
() => () => {
|
||||
const cache = clipCacheRef.current;
|
||||
for (const value of cache.values()) URL.revokeObjectURL(value);
|
||||
cache.clear();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Invalidate pending typing timers when the component unmounts.
|
||||
useEffect(
|
||||
() => () => {
|
||||
|
|
@ -294,14 +343,16 @@ export function NpcConversation({
|
|||
let clipSeconds = 0;
|
||||
if (voiceUrl && soundOnRef.current && audioRef.current) {
|
||||
const audio = audioRef.current;
|
||||
audio.src = voiceUrl;
|
||||
audio.src = playableUrl(voiceUrl);
|
||||
audio.currentTime = 0;
|
||||
try {
|
||||
await audio.play();
|
||||
voiceStarted = true;
|
||||
setPlaying({ id, ratio: 0 });
|
||||
clipSeconds = await clipDuration(audio);
|
||||
} catch {
|
||||
voiceStarted = false;
|
||||
setPlaying(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -337,6 +388,13 @@ export function NpcConversation({
|
|||
},
|
||||
]);
|
||||
markSeen(node.id);
|
||||
|
||||
// Fetch the next line's clip now, while this one is still being read.
|
||||
const nextTarget = node.data.next?.target;
|
||||
const nextNode = nextTarget ? flow?.nodes.find((candidate) => candidate.id === nextTarget) : null;
|
||||
const nextFilename = nextNode?.data.voice?.filename;
|
||||
if (nextFilename) preloadClip(`/api/media/file/${nextFilename}`);
|
||||
|
||||
if (!animate) return;
|
||||
|
||||
const setReveal = (shown: number | undefined) =>
|
||||
|
|
@ -759,6 +817,7 @@ export function NpcConversation({
|
|||
// Muting mid-line silences the clip immediately; the reveal
|
||||
// keeps its current pace.
|
||||
audioRef.current?.pause();
|
||||
setPlaying(null);
|
||||
}
|
||||
}}
|
||||
aria-pressed={!soundOn}
|
||||
|
|
@ -786,7 +845,18 @@ export function NpcConversation({
|
|||
|
||||
{/* One element for every clip: starting a line stops the previous one
|
||||
and keeps the browser's autoplay permission for the session. */}
|
||||
<audio ref={audioRef} preload="none" className="hidden" />
|
||||
<audio
|
||||
ref={audioRef}
|
||||
preload="none"
|
||||
className="hidden"
|
||||
onTimeUpdate={(event) => {
|
||||
const audio = event.currentTarget;
|
||||
if (!audio.duration || !Number.isFinite(audio.duration)) return;
|
||||
const ratio = audio.currentTime / audio.duration;
|
||||
setPlaying((current) => (current ? { ...current, ratio } : current));
|
||||
}}
|
||||
onEnded={() => setPlaying(null)}
|
||||
/>
|
||||
|
||||
{flow.startId === null ? (
|
||||
<div className="p-5 text-sm text-white/50">
|
||||
|
|
@ -825,12 +895,14 @@ export function NpcConversation({
|
|||
key={entry.id}
|
||||
entry={entry}
|
||||
speakerDefault={npc.name}
|
||||
playingRatio={playing?.id === entry.id ? playing.ratio : null}
|
||||
onPlayVoice={(url) => {
|
||||
// Explicit click: always allowed, and clears the notice.
|
||||
const audio = audioRef.current;
|
||||
if (!audio) return;
|
||||
audio.src = url;
|
||||
audio.src = playableUrl(url);
|
||||
audio.currentTime = 0;
|
||||
setPlaying({ id: entry.id, ratio: 0 });
|
||||
void audio
|
||||
.play()
|
||||
.then(() =>
|
||||
|
|
@ -972,10 +1044,13 @@ function TimelineEntry({
|
|||
entry,
|
||||
speakerDefault,
|
||||
onPlayVoice,
|
||||
playingRatio,
|
||||
}: {
|
||||
entry: LogEntry;
|
||||
speakerDefault: string;
|
||||
onPlayVoice?: (url: string) => void;
|
||||
/** How far through this line's clip playback is, or null when it is silent. */
|
||||
playingRatio?: number | null;
|
||||
}) {
|
||||
if (entry.kind === "player") {
|
||||
return (
|
||||
|
|
@ -989,6 +1064,34 @@ function TimelineEntry({
|
|||
}
|
||||
|
||||
const { node, resolved, text, reveal } = entry;
|
||||
/** Replay for a line that has a clip and played normally. Autoplay-blocked
|
||||
* lines keep the louder "Play voice" button instead. */
|
||||
const replayButton =
|
||||
entry.kind === "node" && entry.voiceUrl && !entry.voiceBlocked && onPlayVoice ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPlayVoice(entry.voiceUrl as string)}
|
||||
aria-label="Replay this line"
|
||||
title="Replay this line"
|
||||
className="inline-flex items-center gap-1 rounded-sm border border-white/10 bg-black/30 px-1 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/40 transition-colors hover:border-cyan-500/60 hover:text-cyan-300"
|
||||
>
|
||||
<Volume2Icon className="size-2.5" />
|
||||
Replay
|
||||
</button>
|
||||
) : null;
|
||||
|
||||
/** A hairline under the line, filling as the clip plays, so a long read has
|
||||
* visible progress instead of only audio. */
|
||||
const voiceProgress =
|
||||
playingRatio === null || playingRatio === undefined ? null : (
|
||||
<span aria-hidden className="mt-0.5 block h-px w-full bg-white/10">
|
||||
<span
|
||||
className="block h-full bg-cyan-400/70 transition-[width] duration-150 ease-linear"
|
||||
style={{ width: `${Math.max(0, Math.min(1, playingRatio)) * 100}%` }}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
|
||||
/** A clip the browser refused to autoplay gets a button rather than nothing. */
|
||||
const voiceFallback =
|
||||
entry.voiceBlocked && entry.voiceUrl && onPlayVoice ? (
|
||||
|
|
@ -1012,6 +1115,8 @@ function TimelineEntry({
|
|||
<p className="max-w-[42rem] text-sm italic leading-relaxed text-white/55">
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{replayButton}
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
@ -1023,6 +1128,8 @@ function TimelineEntry({
|
|||
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{replayButton}
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
@ -1035,6 +1142,8 @@ function TimelineEntry({
|
|||
<p className="text-sm italic text-white/50">
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{replayButton}
|
||||
{voiceFallback}
|
||||
</div>
|
||||
);
|
||||
|
|
@ -1053,7 +1162,10 @@ function TimelineEntry({
|
|||
const speaker = node.data.speaker?.trim() || speakerDefault;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
{replayButton}
|
||||
</span>
|
||||
<p className="text-sm text-white/90">
|
||||
{text ? (
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
|
|
@ -1061,6 +1173,7 @@ function TimelineEntry({
|
|||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -247,6 +247,31 @@ the event came from a control, so a focused button keeps its own activation.
|
|||
|
||||
Measured: 2587ms to idle naturally against 382ms when `Enter` is pressed at 300ms.
|
||||
|
||||
### Voice clips: preload, replay and progress
|
||||
|
||||
Clips are fetched ahead of time and kept as object URLs
|
||||
(`clipCacheRef`, bounded at 8 with `revokeObjectURL` on eviction and on unmount),
|
||||
so a line plays from memory instead of starting a request when its turn comes. The
|
||||
URL is built from the node's own `voice.filename` (`/api/media/file/<filename>`),
|
||||
which is why no server round trip is needed to preload it.
|
||||
|
||||
The next clip is fetched **once the current line knows where it goes** (`typeIn`,
|
||||
after `markSeen`): `node.data.next.target` gives the successor, and its
|
||||
`data.voice.filename` the file. This is deliberately not routed through the
|
||||
condition logic. Guessing the successor wrong only wastes one small download, while
|
||||
preloading across an event node would be wrong (its effect can change interpolated
|
||||
text, though not which file plays).
|
||||
|
||||
Measured: the second line's clip was requested 2.8s before the second line
|
||||
appeared, while the first was still playing. Never preload across a branch the
|
||||
walker has not taken, and never prefetch before `soundOn` is known true.
|
||||
|
||||
Each voiced line gets a `Replay` control beside its speaker label, and while a clip
|
||||
plays a cyan hairline under the line fills from `audio.timeupdate` (`playing`
|
||||
state, keyed by log entry id, so only the line actually playing shows it). The
|
||||
element reports progress and clears on `ended`; muting and closing clear it
|
||||
immediately.
|
||||
|
||||
### The conversation frame
|
||||
|
||||
The dialog is a **fixed-height frame** (`h-[min(80dvh,36rem)]`), not a box that
|
||||
|
|
|
|||
Loading…
Reference in a new issue