Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(export): synthesise and cache narration clips

davbiob1ad629a7d80
diff --git a/src/core/export/voiceover/__tests__/audio.test.ts b/src/core/export/voiceover/__tests__/audio.test.ts
new file mode 100644
index 0000000..6235434
--- /dev/null
+++ b/src/core/export/voiceover/__tests__/audio.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import { type PlacedClip, voiceTrackPieces } from '@/core/export/voiceover/audio';
+
+const RATE = 100;
+
+const clip = (startSec: number, samples: number): PlacedClip => ({
+ startSec,
+ buffer: { length: samples } as AudioBuffer,
+});
+
+const layout = (pieces: ReturnType<typeof voiceTrackPieces>) =>
+ pieces.map((piece) => (piece.kind === 'clip' ? `clip:${piece.buffer.length}` : `gap:${piece.samples}`));
+
+describe('voiceTrackPieces', () => {
+ it('pads to each clip and out to the end of the video', () => {
+ expect(layout(voiceTrackPieces([clip(1, 50)], 3, RATE))).toEqual(['gap:100', 'clip:50', 'gap:150']);
+ });
+
+ it('measures gaps from absolute positions, so rounding cannot accumulate', () => {
+ const pieces = voiceTrackPieces([clip(0.333, 10), clip(0.666, 10), clip(0.999, 10)], 2, RATE);
+ const total = pieces.reduce((sum, p) => sum + (p.kind === 'clip' ? p.buffer.length : p.samples), 0);
+ expect(total).toBe(200);
+ expect(layout(pieces)).toEqual(['gap:33', 'clip:10', 'gap:24', 'clip:10', 'gap:23', 'clip:10', 'gap:90']);
+ });
+
+ it('never cuts a clip that outruns its slot', () => {
+ const pieces = voiceTrackPieces([clip(0, 250), clip(1, 50)], 4, RATE);
+ expect(layout(pieces)).toEqual(['clip:250', 'clip:50', 'gap:100']);
+ });
+
+ it('is pure silence when nothing was narrated', () => {
+ expect(layout(voiceTrackPieces([], 2, RATE))).toEqual(['gap:200']);
+ });
+
+ it('orders clips by their place on the clock, not by the map they came from', () => {
+ expect(layout(voiceTrackPieces([clip(2, 10), clip(1, 20)], 3, RATE))).toEqual([
+ 'gap:100',
+ 'clip:20',
+ 'gap:80',
+ 'clip:10',
+ 'gap:90',
+ ]);
+ });
+});
diff --git a/src/core/export/voiceover/__tests__/script.test.ts b/src/core/export/voiceover/__tests__/script.test.ts
new file mode 100644
index 0000000..834cfe0
--- /dev/null
+++ b/src/core/export/voiceover/__tests__/script.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+import { COVER_SEGMENT, MAX_SEGMENT_CHARS, narrationText, voiceoverScript } from '@/core/export/voiceover/script';
+import type { Guide, Step } from '@/core/guides/types';
+
+const guide = { id: 'g', title: 'Reset your password' } as Guide;
+
+function step(id: string, description: string, blockType?: Step['blockType']): Step {
+ return { id, description, blockType } as Step;
+}
+
+describe('narrationText', () => {
+ it('collapses the whitespace a description picked up from the DOM', () => {
+ expect(narrationText(' Click the\n Save button ')).toBe('Click the Save button');
+ });
+
+ it('is empty for a step nobody described', () => {
+ expect(narrationText(undefined)).toBe('');
+ expect(narrationText(' ')).toBe('');
+ });
+
+ it('truncates a runaway description at a sentence break so the clip stays bounded', () => {
+ const text = `${'Open the settings panel. '.repeat(40)}end`;
+ const spoken = narrationText(text);
+ expect(spoken.length).toBeLessThanOrEqual(MAX_SEGMENT_CHARS);
+ expect(spoken.endsWith('.')).toBe(true);
+ });
+});
+
+describe('voiceoverScript', () => {
+ const steps = [step('a', 'Click Save'), step('b', ' '), step('c', 'Heads up', 'callout')];
+
+ it('opens with the guide title when the cover card is on', () => {
+ expect(voiceoverScript(guide, steps, true)[0]).toEqual({ index: COVER_SEGMENT, text: 'Reset your password' });
+ });
+
+ it('leaves the cover unnarrated when the card is off', () => {
+ expect(voiceoverScript(guide, steps, false).some((s) => s.index === COVER_SEGMENT)).toBe(false);
+ });
+
+ it('indexes segments by frame position, skipping the steps with nothing to say', () => {
+ expect(voiceoverScript(guide, steps, false)).toEqual([
+ { index: 0, text: 'Click Save' },
+ { index: 2, text: 'Heads up' },
+ ]);
+ });
+});
diff --git a/src/core/export/voiceover/audio.ts b/src/core/export/voiceover/audio.ts
new file mode 100644
index 0000000..ce1bc6d
--- /dev/null
+++ b/src/core/export/voiceover/audio.ts
@@ -0,0 +1,79 @@
+export const VOICE_SAMPLE_RATE = 44100;
+
+export type VoiceCodec = 'aac' | 'opus';
+
+let context: OfflineAudioContext | null = null;
+
+export function audioContext(): OfflineAudioContext {
+ if (!context) context = new OfflineAudioContext(1, 1, VOICE_SAMPLE_RATE);
+ return context;
+}
+
+export async function decodeClip(bytes: ArrayBuffer): Promise<AudioBuffer> {
+ return toMono(await audioContext().decodeAudioData(bytes.slice(0)));
+}
+
+export function toMono(buffer: AudioBuffer): AudioBuffer {
+ if (buffer.numberOfChannels === 1) return buffer;
+ const mono = audioContext().createBuffer(1, buffer.length, buffer.sampleRate);
+ const mixed = mono.getChannelData(0);
+ for (let channel = 0; channel < buffer.numberOfChannels; channel++) {
+ const data = buffer.getChannelData(channel);
+ for (let sample = 0; sample < data.length; sample++) mixed[sample] += data[sample] / buffer.numberOfChannels;
+ }
+ return mono;
+}
+
+export function silence(samples: number, sampleRate = VOICE_SAMPLE_RATE): AudioBuffer {
+ return audioContext().createBuffer(1, Math.max(1, samples), sampleRate);
+}
+
+export interface PlacedClip {
+ startSec: number;
+ buffer: AudioBuffer;
+}
+
+const CHUNK_SAMPLES = VOICE_SAMPLE_RATE * 5;
+
+export type TrackPiece = { kind: 'silence'; samples: number } | { kind: 'clip'; buffer: AudioBuffer };
+
+export function voiceTrackPieces(clips: PlacedClip[], totalSec: number, sampleRate = VOICE_SAMPLE_RATE): TrackPiece[] {
+ const pieces: TrackPiece[] = [];
+ let cursor = 0;
+
+ const pad = (until: number) => {
+ let remaining = until - cursor;
+ while (remaining > 0) {
+ const span = Math.min(remaining, CHUNK_SAMPLES);
+ pieces.push({ kind: 'silence', samples: span });
+ remaining -= span;
+ }
+ cursor = Math.max(cursor, until);
+ };
+
+ for (const clip of [...clips].sort((a, b) => a.startSec - b.startSec)) {
+ pad(Math.round(clip.startSec * sampleRate));
+ pieces.push({ kind: 'clip', buffer: clip.buffer });
+ cursor += clip.buffer.length;
+ }
+
+ pad(Math.round(totalSec * sampleRate));
+ return pieces;
+}
+
+export async function writeVoiceTrack(
+ clips: PlacedClip[],
+ totalSec: number,
+ add: (buffer: AudioBuffer) => Promise<void>,
+ sampleRate = VOICE_SAMPLE_RATE,
+): Promise<void> {
+ for (const piece of voiceTrackPieces(clips, totalSec, sampleRate)) {
+ await add(piece.kind === 'clip' ? piece.buffer : silence(piece.samples, sampleRate));
+ }
+}
+
+export async function pickVoiceCodec(container: 'mp4' | 'webm'): Promise<VoiceCodec | null> {
+ const { canEncodeAudio } = await import('mediabunny');
+ const codec: VoiceCodec = container === 'mp4' ? 'aac' : 'opus';
+ return (await canEncodeAudio(codec, { numberOfChannels: 1, sampleRate: VOICE_SAMPLE_RATE })) ? codec : null;
+}
diff --git a/src/core/export/voiceover/cache.ts b/src/core/export/voiceover/cache.ts
new file mode 100644
index 0000000..7deaa41
--- /dev/null
+++ b/src/core/export/voiceover/cache.ts
@@ -0,0 +1,43 @@
+import { db } from '@/core/guides/db';
+import { logger } from '@/lib/logger';
+
+const MAX_CLIPS = 500;
+
+export async function clipKey(provider: string, voiceId: string, modelId: string, text: string): Promise<string> {
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
+ const hash = Array.from(new Uint8Array(digest))
+ .slice(0, 16)
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join('');
+ return `${provider}:${voiceId}:${modelId}:${hash}`;
+}
+
+export async function readClip(id: string): Promise<ArrayBuffer | null> {
+ try {
+ const row = await db.voiceClips.get(id);
+ return row?.bytes ?? null;
+ } catch (error) {
+ logger.error('[voiceover] cache read failed', error);
+ return null;
+ }
+}
+
+export async function writeClip(id: string, bytes: ArrayBuffer): Promise<void> {
+ try {
+ await db.voiceClips.put({ id, bytes, createdAt: Date.now() });
+ const count = await db.voiceClips.count();
+ if (count > MAX_CLIPS) {
+ const stale = await db.voiceClips
+ .orderBy('createdAt')
+ .limit(count - MAX_CLIPS)
+ .primaryKeys();
+ await db.voiceClips.bulkDelete(stale);
+ }
+ } catch (error) {
+ logger.error('[voiceover] cache write failed', error);
+ }
+}
+
+export async function clearClips(): Promise<void> {
+ await db.voiceClips.clear();
+}
diff --git a/src/core/export/voiceover/render.ts b/src/core/export/voiceover/render.ts
new file mode 100644
index 0000000..d8f9bdc
--- /dev/null
+++ b/src/core/export/voiceover/render.ts
@@ -0,0 +1,74 @@
+import { logger } from '@/lib/logger';
+import { decodeClip } from './audio';
+import { clipKey, readClip, writeClip } from './cache';
+import { synthesizeSpeech } from './client';
+import type { VoiceoverConfig } from './config';
+import type { VoiceoverSegment } from './script';
+
+export interface VoiceoverControls {
+ signal?: AbortSignal;
+ onProgress?: (done: number, total: number) => void;
+}
+
+const RETRY_DELAY_MS = 1500;
+
+function aborted(error: unknown): boolean {
+ return error instanceof DOMException && error.name === 'AbortError';
+}
+
+function wait(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer);
+ reject(new DOMException('Voiceover was aborted', 'AbortError'));
+ },
+ { once: true },
+ );
+ });
+}
+
+async function clipBytes(
+ segment: VoiceoverSegment,
+ config: VoiceoverConfig,
+ signal?: AbortSignal,
+): Promise<ArrayBuffer> {
+ const key = await clipKey(config.provider, config.voiceId, config.modelId, segment.text);
+ const cached = await readClip(key);
+ if (cached) return cached;
+
+ let bytes: ArrayBuffer;
+ try {
+ bytes = await synthesizeSpeech(config, segment.text, signal);
+ } catch (error) {
+ if (aborted(error)) throw error;
+ logger.error('[voiceover] synthesis retrying', error);
+ await wait(RETRY_DELAY_MS, signal);
+ bytes = await synthesizeSpeech(config, segment.text, signal);
+ }
+
+ await writeClip(key, bytes);
+ return bytes;
+}
+
+export async function renderVoiceover(
+ segments: VoiceoverSegment[],
+ config: VoiceoverConfig,
+ controls: VoiceoverControls = {},
+): Promise<Map<number, AudioBuffer>> {
+ const { signal, onProgress } = controls;
+ const clips = new Map<number, AudioBuffer>();
+ let done = 0;
+
+ onProgress?.(0, segments.length);
+
+ for (const segment of segments) {
+ if (signal?.aborted) throw new DOMException('Voiceover was aborted', 'AbortError');
+ clips.set(segment.index, await decodeClip(await clipBytes(segment, config, signal)));
+ onProgress?.(++done, segments.length);
+ }
+
+ return clips;
+}
diff --git a/src/core/export/voiceover/script.ts b/src/core/export/voiceover/script.ts
new file mode 100644
index 0000000..a3e2bf5
--- /dev/null
+++ b/src/core/export/voiceover/script.ts
@@ -0,0 +1,38 @@
+import type { Guide, Step } from '@/core/guides/types';
+
+export const COVER_SEGMENT = -1;
+
+export const MAX_SEGMENT_CHARS = 600;
+
+export interface VoiceoverSegment {
+ index: number;
+ text: string;
+}
+
+export function narrationText(value: string | undefined): string {
+ const text = (value ?? '').replace(/\s+/g, ' ').trim();
+ if (text.length <= MAX_SEGMENT_CHARS) return text;
+ const cut = text.slice(0, MAX_SEGMENT_CHARS);
+ const stop = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf(', '), cut.lastIndexOf(' '));
+ return (stop > MAX_SEGMENT_CHARS / 2 ? cut.slice(0, stop) : cut).trim();
+}
+
+export function stepNarration(step: Step): string {
+ return narrationText(step.description);
+}
+
+export function voiceoverScript(guide: Guide, frames: Step[], cover: boolean): VoiceoverSegment[] {
+ const segments: VoiceoverSegment[] = [];
+
+ if (cover) {
+ const title = narrationText(guide.title);
+ if (title) segments.push({ index: COVER_SEGMENT, text: title });
+ }
+
+ frames.forEach((step, index) => {
+ const text = stepNarration(step);
+ if (text) segments.push({ index, text });
+ });
+
+ return segments;
+}