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(voice): capture the microphone in an offscreen document

Luis Ortiz8e32f08be578
diff --git a/public/pcm-processor.js b/public/pcm-processor.js
new file mode 100644
index 0000000..522a0e8
--- /dev/null
+++ b/public/pcm-processor.js
@@ -0,0 +1,25 @@
+const CHUNK = 4800;
+
+class PCMProcessor extends AudioWorkletProcessor {
+ constructor() {
+ super();
+ this.buffer = new Int16Array(CHUNK);
+ this.index = 0;
+ }
+
+ process(inputs) {
+ const channel = inputs[0] && inputs[0][0];
+ if (!channel) return true;
+ for (const sample of channel) {
+ this.buffer[this.index++] = sample > 1 ? 32767 : sample < -1 ? -32767 : (sample * 32767) | 0;
+ if (this.index >= CHUNK) {
+ this.port.postMessage(this.buffer.buffer, [this.buffer.buffer]);
+ this.buffer = new Int16Array(CHUNK);
+ this.index = 0;
+ }
+ }
+ return true;
+ }
+}
+
+registerProcessor('pcm-processor', PCMProcessor);
diff --git a/src/entrypoints/offscreen/index.html b/src/entrypoints/offscreen/index.html
new file mode 100644
index 0000000..7082ae9
--- /dev/null
+++ b/src/entrypoints/offscreen/index.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="wxt.exclude" content="['firefox']" />
+ <title>Mimik Microphone</title>
+ </head>
+ <body>
+ <script type="module" src="./index.ts"></script>
+ </body>
+</html>
diff --git a/src/entrypoints/offscreen/index.ts b/src/entrypoints/offscreen/index.ts
new file mode 100644
index 0000000..b23551a
--- /dev/null
+++ b/src/entrypoints/offscreen/index.ts
@@ -0,0 +1,195 @@
+import { detectSpeechByEnergy } from '@/core/capture/voice/energy-gate';
+import { runNarrationPipeline } from '@/core/capture/voice/pipeline';
+import { buildStepWindows } from '@/core/capture/voice/step-windows';
+import { createTranscriber, type VoiceProvider } from '@/core/capture/voice/transcribe';
+import type { NarrationResult } from '@/core/capture/voice/types';
+import { getExtensionURL, localStorage, onMessage, sendMessage } from '@/lib/browser-api';
+import { logger } from '@/lib/logger';
+import {
+ isVoiceMessageFor,
+ VOICE_BACKGROUND_TARGET,
+ VOICE_OFFSCREEN_TARGET,
+ VOICE_SIDEPANEL_TARGET,
+ type VoiceEpochEvent,
+ type VoiceErrorEvent,
+ type VoiceErrorReason,
+ type VoiceEvent,
+ type VoiceLevelEvent,
+ VoiceMessage,
+ type VoicePermissionQueryResponse,
+ type VoicePermissionState,
+ type VoiceRequest,
+ type VoiceStartRequest,
+ type VoiceStartResponse,
+ type VoiceStatusResponse,
+ type VoiceStopRequest,
+ type VoiceStopResponse,
+ voiceMessage,
+} from '@/lib/voice-messages';
+import { MicRecorder } from './mic-recorder';
+
+const VOICE_PROVIDERS: VoiceProvider[] = ['openai', 'groq'];
+
+const EMPTY_RESULT: NarrationResult = {
+ descriptions: [],
+ stats: {
+ batches: 0,
+ failedBatches: 0,
+ droppedBatches: 0,
+ verbatimSegments: 0,
+ splitSegments: 0,
+ rejectedSegments: 0,
+ },
+};
+
+function emit(event: VoiceEvent): void {
+ void sendMessage(event as unknown as Record<string, unknown>).catch(() => undefined);
+}
+
+function describe(error: unknown): string {
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
+}
+
+function startFailureReason(error: unknown): VoiceErrorReason {
+ if (!(error instanceof Error)) return 'unknown';
+ if (error.name === 'NotAllowedError' || error.name === 'SecurityError') return 'permission-denied';
+ if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return 'no-device';
+ if (error.name === 'NotSupportedError') return 'unsupported';
+ return 'unknown';
+}
+
+const recorder = new MicRecorder(getExtensionURL('/pcm-processor.js'), {
+ onEpoch: (audioEpochMs) =>
+ emit(
+ voiceMessage<VoiceEpochEvent>({
+ type: VoiceMessage.VOICE_EPOCH,
+ target: VOICE_BACKGROUND_TARGET,
+ audioEpochMs,
+ }),
+ ),
+ onLevel: (level, speaking) =>
+ emit(
+ voiceMessage<VoiceLevelEvent>({
+ type: VoiceMessage.VOICE_LEVEL,
+ target: VOICE_SIDEPANEL_TARGET,
+ level,
+ speaking,
+ }),
+ ),
+ onStreamEnded: () =>
+ emit(
+ voiceMessage<VoiceErrorEvent>({
+ type: VoiceMessage.VOICE_ERROR,
+ target: VOICE_BACKGROUND_TARGET,
+ reason: 'stream-ended',
+ error: 'The microphone stream ended before recording stopped',
+ }),
+ ),
+});
+
+async function readVoiceSettings(): Promise<{ provider: VoiceProvider; apiKey: string; language?: string }> {
+ const stored = await localStorage.get(['voiceProvider', 'voiceApiKey', 'voiceLanguage', 'aiLanguage']);
+ const provider = stored.voiceProvider as VoiceProvider;
+ const locale = (stored.voiceLanguage ?? stored.aiLanguage) as string | undefined;
+ return {
+ provider: VOICE_PROVIDERS.includes(provider) ? provider : 'openai',
+ apiKey: typeof stored.voiceApiKey === 'string' ? stored.voiceApiKey.trim() : '',
+ language: locale ? locale.split('-')[0] : undefined,
+ };
+}
+
+async function handleStart(request: VoiceStartRequest): Promise<VoiceStartResponse> {
+ if (recorder.recording) {
+ return { started: false, reason: 'already-recording', error: 'Microphone capture is already running' };
+ }
+ try {
+ const stream = await recorder.start(request.deviceId);
+ logger.info('voice: microphone capture started', stream);
+ return { started: true, ...stream };
+ } catch (error) {
+ recorder.release();
+ logger.error('voice: microphone capture failed to start', error);
+ return { started: false, reason: startFailureReason(error), error: describe(error) };
+ }
+}
+
+async function handleStop(request: VoiceStopRequest): Promise<VoiceStopResponse> {
+ if (!recorder.recording) {
+ return { ok: false, reason: 'not-recording', error: 'Microphone capture is not running' };
+ }
+
+ const recording = recorder.stop();
+ if (recording.audioEpochMs === null || recording.pcm.length === 0) {
+ return { ok: false, reason: 'no-audio', error: 'No microphone audio was captured' };
+ }
+
+ const audioEpochMs = recording.audioEpochMs;
+ if (request.steps.length === 0) {
+ return { ok: true, result: EMPTY_RESULT, audioEpochMs, durationSeconds: recording.durationSeconds };
+ }
+
+ const settings = await readVoiceSettings();
+ if (!settings.apiKey) {
+ return { ok: false, reason: 'missing-api-key', error: 'No transcription API key is configured' };
+ }
+
+ try {
+ const result = await runNarrationPipeline({
+ pcm: recording.pcm,
+ sampleRate: recording.sampleRate,
+ steps: buildStepWindows(request.steps, audioEpochMs),
+ detectSpeech: detectSpeechByEnergy,
+ transcribe: createTranscriber(settings),
+ });
+ logger.info('voice: narration pipeline finished', result.stats);
+ return { ok: true, result, audioEpochMs, durationSeconds: recording.durationSeconds };
+ } catch (error) {
+ logger.error('voice: narration pipeline failed', error);
+ return { ok: false, reason: 'unknown', error: describe(error) };
+ }
+}
+
+async function permissionState(): Promise<VoicePermissionQueryResponse> {
+ try {
+ const result = await navigator.permissions.query({ name: 'microphone' as PermissionName });
+ return { state: result.state as VoicePermissionState };
+ } catch {
+ return { state: 'unknown' };
+ }
+}
+
+function status(): VoiceStatusResponse {
+ return {
+ recording: recorder.recording,
+ audioEpochMs: recorder.audioEpochMs,
+ sampleRate: recorder.sampleRate,
+ samples: recorder.sampleCount,
+ durationSeconds: recorder.durationSeconds,
+ };
+}
+
+onMessage((message, _sender, sendResponse) => {
+ if (!isVoiceMessageFor(VOICE_OFFSCREEN_TARGET, message)) return undefined;
+ const request = message as VoiceRequest;
+
+ switch (request.type) {
+ case VoiceMessage.VOICE_START:
+ void handleStart(request).then(sendResponse);
+ return true;
+ case VoiceMessage.VOICE_STOP:
+ void handleStop(request).then(sendResponse);
+ return true;
+ case VoiceMessage.VOICE_ABORT:
+ recorder.release();
+ sendResponse({ ok: true });
+ return undefined;
+ case VoiceMessage.VOICE_STATUS:
+ sendResponse(status());
+ return undefined;
+ case VoiceMessage.VOICE_PERMISSION_QUERY:
+ void permissionState().then(sendResponse);
+ return true;
+ default:
+ return undefined;
+ }
+});
diff --git a/src/entrypoints/offscreen/mic-recorder.ts b/src/entrypoints/offscreen/mic-recorder.ts
new file mode 100644
index 0000000..4fd0187
--- /dev/null
+++ b/src/entrypoints/offscreen/mic-recorder.ts
@@ -0,0 +1,197 @@
+import { SPEECH_RMS_THRESHOLD } from '@/core/capture/voice/energy-gate';
+
+export const TARGET_SAMPLE_RATE = 16000;
+export const PCM_WORKLET_NAME = 'pcm-processor';
+
+const ANALYSER_FFT_SIZE = 2048;
+const LEVEL_FLOOR_DB = -60;
+const LEVEL_SMOOTHING = 0.6;
+const MS_PER_S = 1000;
+
+const AUDIO_CONSTRAINTS: MediaTrackConstraints = {
+ channelCount: 1,
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+};
+
+const DEVICE_ERRORS = ['OverconstrainedError', 'NotFoundError', 'NotReadableError'];
+
+export interface MicRecorderEvents {
+ onEpoch(audioEpochMs: number): void;
+ onLevel(level: number, speaking: boolean): void;
+ onStreamEnded(): void;
+}
+
+export interface MicStreamInfo {
+ deviceId: string | null;
+ usedFallbackDevice: boolean;
+}
+
+export interface MicRecording {
+ pcm: Int16Array;
+ sampleRate: number;
+ audioEpochMs: number | null;
+ durationSeconds: number;
+}
+
+function isDeviceError(error: unknown): boolean {
+ return error instanceof Error && DEVICE_ERRORS.includes(error.name);
+}
+
+async function openStream(deviceId?: string): Promise<{ stream: MediaStream; usedFallbackDevice: boolean }> {
+ if (deviceId) {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: { ...AUDIO_CONSTRAINTS, deviceId: { exact: deviceId } },
+ });
+ return { stream, usedFallbackDevice: false };
+ } catch (error) {
+ if (!isDeviceError(error)) throw error;
+ }
+ }
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: AUDIO_CONSTRAINTS });
+ return { stream, usedFallbackDevice: deviceId !== undefined };
+}
+
+function concat(chunks: Int16Array[], samples: number): Int16Array {
+ const pcm = new Int16Array(samples);
+ let offset = 0;
+ for (const chunk of chunks) {
+ pcm.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return pcm;
+}
+
+export class MicRecorder {
+ private stream: MediaStream | null = null;
+ private context: AudioContext | null = null;
+ private source: MediaStreamAudioSourceNode | null = null;
+ private worklet: AudioWorkletNode | null = null;
+ private analyser: AnalyserNode | null = null;
+ private analyserFrame: Float32Array | null = null;
+ private chunks: Int16Array[] = [];
+ private samples = 0;
+ private epochMs: number | null = null;
+ private rate = TARGET_SAMPLE_RATE;
+ private level = 0;
+ private active = false;
+
+ constructor(
+ private readonly workletUrl: string,
+ private readonly events: MicRecorderEvents,
+ ) {}
+
+ get recording(): boolean {
+ return this.active;
+ }
+
+ get audioEpochMs(): number | null {
+ return this.epochMs;
+ }
+
+ get sampleRate(): number {
+ return this.rate;
+ }
+
+ get sampleCount(): number {
+ return this.samples;
+ }
+
+ get durationSeconds(): number {
+ return this.samples / this.rate;
+ }
+
+ async start(deviceId?: string): Promise<MicStreamInfo> {
+ if (this.active) throw new Error('Microphone capture is already running');
+
+ const { stream, usedFallbackDevice } = await openStream(deviceId);
+ this.stream = stream;
+
+ const context = new AudioContext({ sampleRate: TARGET_SAMPLE_RATE });
+ this.context = context;
+ this.rate = context.sampleRate;
+ await context.audioWorklet.addModule(this.workletUrl);
+ if (context.state === 'suspended') await context.resume();
+
+ this.source = context.createMediaStreamSource(stream);
+ this.analyser = context.createAnalyser();
+ this.analyser.fftSize = ANALYSER_FFT_SIZE;
+ this.analyserFrame = new Float32Array(this.analyser.fftSize);
+ this.worklet = new AudioWorkletNode(context, PCM_WORKLET_NAME);
+ this.worklet.port.onmessage = (event: MessageEvent<ArrayBuffer>) => this.appendFrame(event.data);
+
+ this.source.connect(this.analyser);
+ this.analyser.connect(this.worklet);
+ this.worklet.connect(context.destination);
+
+ for (const track of stream.getAudioTracks()) {
+ track.addEventListener('ended', () => {
+ if (this.active) this.events.onStreamEnded();
+ });
+ }
+
+ this.active = true;
+ return { deviceId: stream.getAudioTracks()[0]?.getSettings().deviceId ?? null, usedFallbackDevice };
+ }
+
+ stop(): MicRecording {
+ const recording: MicRecording = {
+ pcm: concat(this.chunks, this.samples),
+ sampleRate: this.rate,
+ audioEpochMs: this.epochMs,
+ durationSeconds: this.durationSeconds,
+ };
+ this.release();
+ return recording;
+ }
+
+ release(): void {
+ if (this.worklet) {
+ this.worklet.port.onmessage = null;
+ this.worklet.disconnect();
+ }
+ this.source?.disconnect();
+ this.analyser?.disconnect();
+ void this.context?.close().catch(() => undefined);
+ for (const track of this.stream?.getTracks() ?? []) track.stop();
+
+ this.worklet = null;
+ this.source = null;
+ this.analyser = null;
+ this.analyserFrame = null;
+ this.context = null;
+ this.stream = null;
+ this.chunks = [];
+ this.samples = 0;
+ this.epochMs = null;
+ this.level = 0;
+ this.active = false;
+ }
+
+ private appendFrame(buffer: ArrayBuffer): void {
+ const frame = new Int16Array(buffer);
+ if (this.epochMs === null) {
+ this.epochMs = Date.now() - Math.round((frame.length / this.rate) * MS_PER_S);
+ this.events.onEpoch(this.epochMs);
+ }
+ this.chunks.push(frame);
+ this.samples += frame.length;
+ this.emitLevel();
+ }
+
+ private emitLevel(): void {
+ if (!this.analyser || !this.analyserFrame) return;
+ this.analyser.getFloatTimeDomainData(this.analyserFrame);
+
+ let sum = 0;
+ for (const sample of this.analyserFrame) sum += sample * sample;
+ const rms = Math.sqrt(sum / this.analyserFrame.length);
+
+ const db = rms > 0 ? 20 * Math.log10(rms) : LEVEL_FLOOR_DB;
+ const normalised = Math.min(1, Math.max(0, (db - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB));
+ this.level = this.level * LEVEL_SMOOTHING + normalised * (1 - LEVEL_SMOOTHING);
+ this.events.onLevel(this.level, rms > SPEECH_RMS_THRESHOLD);
+ }
+}
diff --git a/src/lib/offscreen.ts b/src/lib/offscreen.ts
new file mode 100644
index 0000000..eed3092
--- /dev/null
+++ b/src/lib/offscreen.ts
@@ -0,0 +1,131 @@
+import { createTab, getExtensionURL, sendMessage } from './browser-api';
+import { logger } from './logger';
+import {
+ VOICE_OFFSCREEN_TARGET,
+ type VoiceAbortRequest,
+ type VoiceAbortResponse,
+ VoiceMessage,
+ type VoicePermissionQueryRequest,
+ type VoicePermissionQueryResponse,
+ type VoiceRequest,
+ type VoiceStartRequest,
+ type VoiceStartResponse,
+ type VoiceStatusRequest,
+ type VoiceStatusResponse,
+ type VoiceStepMark,
+ type VoiceStopRequest,
+ type VoiceStopResponse,
+ voiceMessage,
+} from './voice-messages';
+
+const OFFSCREEN_PATH = '/offscreen.html';
+const MIC_PERMISSION_PATH = '/mic-permission.html';
+const OFFSCREEN_REASON = 'USER_MEDIA';
+const OFFSCREEN_JUSTIFICATION = 'Recording microphone narration while a guide is being captured';
+const OFFSCREEN_CONTEXT = 'OFFSCREEN_DOCUMENT';
+
+interface OffscreenApi {
+ createDocument(options: { url: string; reasons: string[]; justification: string }): Promise<void>;
+ closeDocument(): Promise<void>;
+}
+
+interface ContextsApi {
+ getContexts(filter: { contextTypes: string[] }): Promise<unknown[]>;
+}
+
+function offscreenApi(): OffscreenApi | undefined {
+ return (globalThis as { chrome?: { offscreen?: OffscreenApi } }).chrome?.offscreen;
+}
+
+function contextsApi(): ContextsApi | undefined {
+ const runtime = (globalThis as { chrome?: { runtime?: Partial<ContextsApi> } }).chrome?.runtime;
+ return typeof runtime?.getContexts === 'function' ? (runtime as ContextsApi) : undefined;
+}
+
+let creating: Promise<void> | null = null;
+
+export function supportsOffscreen(): boolean {
+ return offscreenApi() !== undefined;
+}
+
+export async function hasOffscreenDocument(): Promise<boolean> {
+ const api = contextsApi();
+ if (!api) return false;
+ try {
+ const contexts = await api.getContexts({ contextTypes: [OFFSCREEN_CONTEXT] });
+ return contexts.length > 0;
+ } catch {
+ return false;
+ }
+}
+
+export async function ensureOffscreenDocument(): Promise<boolean> {
+ const api = offscreenApi();
+ if (!api) return false;
+ if (await hasOffscreenDocument()) return true;
+
+ creating ??= api.createDocument({
+ url: getExtensionURL(OFFSCREEN_PATH),
+ reasons: [OFFSCREEN_REASON],
+ justification: OFFSCREEN_JUSTIFICATION,
+ });
+
+ try {
+ await creating;
+ return true;
+ } catch (error) {
+ logger.error('voice: failed to create the offscreen document', error);
+ return hasOffscreenDocument();
+ } finally {
+ creating = null;
+ }
+}
+
+export async function closeOffscreenDocument(): Promise<void> {
+ const api = offscreenApi();
+ if (!api) return;
+ if (!(await hasOffscreenDocument())) return;
+ try {
+ await api.closeDocument();
+ } catch (error) {
+ logger.error('voice: failed to close the offscreen document', error);
+ }
+}
+
+export function openMicPermissionPage(tabId?: number): Promise<unknown> {
+ const url = getExtensionURL(tabId === undefined ? MIC_PERMISSION_PATH : `${MIC_PERMISSION_PATH}?tabId=${tabId}`);
+ return createTab({ url, active: true });
+}
+
+function request<T>(message: VoiceRequest): Promise<T> {
+ return sendMessage(message as unknown as Record<string, unknown>) as Promise<T>;
+}
+
+export function startVoiceCapture(deviceId?: string): Promise<VoiceStartResponse> {
+ return request(
+ voiceMessage<VoiceStartRequest>({ type: VoiceMessage.VOICE_START, target: VOICE_OFFSCREEN_TARGET, deviceId }),
+ );
+}
+
+export function stopVoiceCapture(steps: VoiceStepMark[]): Promise<VoiceStopResponse> {
+ return request(
+ voiceMessage<VoiceStopRequest>({ type: VoiceMessage.VOICE_STOP, target: VOICE_OFFSCREEN_TARGET, steps }),
+ );
+}
+
+export function abortVoiceCapture(): Promise<VoiceAbortResponse> {
+ return request(voiceMessage<VoiceAbortRequest>({ type: VoiceMessage.VOICE_ABORT, target: VOICE_OFFSCREEN_TARGET }));
+}
+
+export function getVoiceStatus(): Promise<VoiceStatusResponse> {
+ return request(voiceMessage<VoiceStatusRequest>({ type: VoiceMessage.VOICE_STATUS, target: VOICE_OFFSCREEN_TARGET }));
+}
+
+export function queryMicPermission(): Promise<VoicePermissionQueryResponse> {
+ return request(
+ voiceMessage<VoicePermissionQueryRequest>({
+ type: VoiceMessage.VOICE_PERMISSION_QUERY,
+ target: VOICE_OFFSCREEN_TARGET,
+ }),
+ );
+}
diff --git a/wxt.config.ts b/wxt.config.ts
index 6be87fe..3cffd9b 100644
--- a/wxt.config.ts
+++ b/wxt.config.ts
@@ -47,7 +47,7 @@ export default defineConfig({
"scripting",
"unlimitedStorage",
"webNavigation",
- ...(isFirefox ? [] : ["sidePanel"]),
+ ...(isFirefox ? [] : ["sidePanel", "offscreen"]),
],
...(isFirefox
? { optional_host_permissions: ["<all_urls>"] }