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(settings): let users pick and test the narration microphone

Luis Ortiz6606c300176f
diff --git a/src/locales/en.yml b/src/locales/en.yml
index f43d3ac..19f4c08 100644
--- a/src/locales/en.yml
+++ b/src/locales/en.yml
@@ -86,6 +86,17 @@ settings:
voiceNarration: Voice Narration
voiceDescription: Narrate out loud while you record and your words become the step descriptions.
voiceDataNotice: Your recorded audio is sent to the provider you choose above, using your own API key. This is the one part of Mimik that sends anything out of your browser.
+ microphone: Microphone
+ microphoneDefault: System default
+ microphoneNeedsAccess: Allow microphone access to see your device names.
+ microphoneGrantAccess: Allow microphone access
+ microphoneNone: No microphone was found. Plug one in and it will show up here.
+ microphoneUnavailable: Unavailable microphone
+ microphoneMissing: The microphone you picked is not available right now, so Mimik will use the system default.
+ microphoneTest: Test microphone
+ microphoneTestStop: Stop test
+ microphoneTestHint: "Having mic issues? Start a test and say something to check that your microphone is working."
+ microphoneTestFailed: That microphone could not be opened. Pick another one and try again.
saveSettings: Save Settings
saved: Saved
smartBlur: Smart Blur
diff --git a/src/locales/es.yml b/src/locales/es.yml
index b4193dd..6e5aa63 100644
--- a/src/locales/es.yml
+++ b/src/locales/es.yml
@@ -86,6 +86,17 @@ settings:
voiceNarration: "Narración por voz"
voiceDescription: "Narra en voz alta mientras grabas y tus palabras se convierten en las descripciones de los pasos."
voiceDataNotice: "El audio que grabes se envía al proveedor que elijas arriba, usando tu propia clave API. Es la única parte de Mimik que saca algo de tu navegador."
+ microphone: "Micrófono"
+ microphoneDefault: Predeterminado del sistema
+ microphoneNeedsAccess: "Permite el acceso al micrófono para ver los nombres de tus dispositivos."
+ microphoneGrantAccess: "Permitir acceso al micrófono"
+ microphoneNone: "No se encontró ningún micrófono. Conecta uno y aparecerá aquí."
+ microphoneUnavailable: "Micrófono no disponible"
+ microphoneMissing: "El micrófono que elegiste no está disponible ahora mismo, así que Mimik usará el predeterminado del sistema."
+ microphoneTest: "Probar micrófono"
+ microphoneTestStop: Detener prueba
+ microphoneTestHint: "¿Problemas con el micro? Empieza una prueba y di algo para comprobar que funciona."
+ microphoneTestFailed: "No se pudo abrir ese micrófono. Elige otro e inténtalo de nuevo."
saveSettings: Guardar ajustes
saved: Guardado
smartBlur: Desenfoque inteligente
diff --git a/src/locales/fr.yml b/src/locales/fr.yml
index 762412a..69e79df 100644
--- a/src/locales/fr.yml
+++ b/src/locales/fr.yml
@@ -86,6 +86,17 @@ settings:
voiceNarration: "Narration vocale"
voiceDescription: "Commentez à voix haute pendant l'enregistrement : vos mots deviennent les descriptions des étapes."
voiceDataNotice: "L'audio enregistré est envoyé au fournisseur choisi ci-dessus, avec votre propre clé API. C'est la seule partie de Mimik qui fait sortir quelque chose de votre navigateur."
+ microphone: Microphone
+ microphoneDefault: "Micro par défaut du système"
+ microphoneNeedsAccess: "Autorisez l'accès au micro pour voir le nom de vos appareils."
+ microphoneGrantAccess: "Autoriser l'accès au micro"
+ microphoneNone: "Aucun micro n'a été trouvé. Branchez-en un et il apparaîtra ici."
+ microphoneUnavailable: "Micro indisponible"
+ microphoneMissing: "Le micro que vous avez choisi n'est pas disponible pour le moment : Mimik utilisera celui par défaut du système."
+ microphoneTest: "Tester le micro"
+ microphoneTestStop: "Arrêter le test"
+ microphoneTestHint: "Un souci de micro ? Lancez un test et dites quelque chose pour vérifier qu'il fonctionne."
+ microphoneTestFailed: "Ce micro n'a pas pu être ouvert. Choisissez-en un autre et réessayez."
saveSettings: "Enregistrer"
saved: "Enregistré"
smartBlur: Flou intelligent
diff --git a/src/locales/pt-BR.yml b/src/locales/pt-BR.yml
index 1996673..837a943 100644
--- a/src/locales/pt-BR.yml
+++ b/src/locales/pt-BR.yml
@@ -86,6 +86,17 @@ settings:
voiceNarration: "Narração por voz"
voiceDescription: "Narre em voz alta enquanto grava e suas palavras viram as descrições dos passos."
voiceDataNotice: "O áudio gravado é enviado pro provedor que você escolher acima, usando sua própria chave API. É a única parte do Mimik que manda algo pra fora do seu navegador."
+ microphone: Microfone
+ microphoneDefault: "Padrão do sistema"
+ microphoneNeedsAccess: "Libere o acesso ao microfone pra ver o nome dos seus dispositivos."
+ microphoneGrantAccess: Permitir acesso ao microfone
+ microphoneNone: Nenhum microfone encontrado. Conecte um e ele aparece aqui.
+ microphoneUnavailable: "Microfone indisponível"
+ microphoneMissing: "O microfone que você escolheu não está disponível agora, então o Mimik vai usar o padrão do sistema."
+ microphoneTest: Testar microfone
+ microphoneTestStop: Parar teste
+ microphoneTestHint: "Problema com o microfone? Inicia um teste e fala alguma coisa pra ver se ele tá funcionando."
+ microphoneTestFailed: "Não deu pra abrir esse microfone. Escolhe outro e tenta de novo."
saveSettings: Salvar ajustes
saved: Salvo
smartBlur: Desfoque inteligente
diff --git a/src/ui/shared/MicrophonePicker.tsx b/src/ui/shared/MicrophonePicker.tsx
new file mode 100644
index 0000000..5e360b3
--- /dev/null
+++ b/src/ui/shared/MicrophonePicker.tsx
@@ -0,0 +1,231 @@
+import { Mic, Square, TriangleAlert } from 'lucide-react';
+import { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { i18n } from '#imports';
+import { getActiveTab } from '@/lib/browser-api';
+import { openMicPermissionPage } from '@/lib/offscreen';
+import { Button } from '@/ui/components/ui/button';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
+import {
+ isMicrophoneMissing,
+ type MicrophoneDevice,
+ microphoneListState,
+ nextMicLevel,
+ SPEAKING_LEVEL,
+ SYSTEM_DEFAULT_VALUE,
+ toMicrophoneOptions,
+ toSelectValue,
+ toStoredMicrophoneId,
+} from './microphones';
+
+interface MicrophonePickerProps {
+ value: string;
+ onChange: (deviceId: string) => void;
+}
+
+interface MicTest {
+ stream: MediaStream;
+ context: AudioContext;
+ timer: number;
+}
+
+const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName };
+const ANALYSER_FFT_SIZE = 2048;
+const METER_INTERVAL_MS = 80;
+
+export default function MicrophonePicker({ value, onChange }: MicrophonePickerProps) {
+ const [devices, setDevices] = useState<MicrophoneDevice[]>([]);
+ const [testing, setTesting] = useState(false);
+ const [level, setLevel] = useState(0);
+ const [testFailed, setTestFailed] = useState(false);
+ const test = useRef<MicTest | null>(null);
+ const triggerId = useId();
+
+ const refresh = useCallback(async () => {
+ const media = navigator.mediaDevices;
+ if (!media?.enumerateDevices) return;
+ setDevices(await media.enumerateDevices().catch(() => [] as MediaDeviceInfo[]));
+ }, []);
+
+ const stopTest = useCallback(() => {
+ const running = test.current;
+ test.current = null;
+ setTesting(false);
+ setLevel(0);
+ if (!running) return;
+ window.clearInterval(running.timer);
+ for (const track of running.stream.getTracks()) track.stop();
+ void running.context.close().catch(() => undefined);
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ const media = navigator.mediaDevices;
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') void refresh();
+ };
+ media?.addEventListener('devicechange', refresh);
+ document.addEventListener('visibilitychange', onVisible);
+
+ let status: PermissionStatus | undefined;
+ navigator.permissions
+ ?.query(MICROPHONE)
+ .then((result) => {
+ status = result;
+ result.addEventListener('change', refresh);
+ })
+ .catch(() => undefined);
+
+ return () => {
+ media?.removeEventListener('devicechange', refresh);
+ document.removeEventListener('visibilitychange', onVisible);
+ status?.removeEventListener('change', refresh);
+ };
+ }, [refresh]);
+
+ useEffect(() => stopTest, [stopTest]);
+
+ const requestAccess = useCallback(async () => {
+ const tab = await getActiveTab().catch(() => undefined);
+ await openMicPermissionPage(tab?.id).catch(() => undefined);
+ await refresh();
+ }, [refresh]);
+
+ const startTest = useCallback(async () => {
+ stopTest();
+ setTestFailed(false);
+ const deviceId = value.trim();
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: deviceId ? { deviceId: { exact: deviceId } } : true,
+ });
+ const context = new AudioContext();
+ if (context.state === 'suspended') await context.resume();
+ const analyser = context.createAnalyser();
+ analyser.fftSize = ANALYSER_FFT_SIZE;
+ const mute = context.createGain();
+ mute.gain.value = 0;
+ context.createMediaStreamSource(stream).connect(analyser);
+ analyser.connect(mute);
+ mute.connect(context.destination);
+
+ const frame = new Float32Array(analyser.fftSize);
+ let current = 0;
+ const timer = window.setInterval(() => {
+ analyser.getFloatTimeDomainData(frame);
+ let sum = 0;
+ for (const sample of frame) sum += sample * sample;
+ current = nextMicLevel(Math.sqrt(sum / frame.length), current);
+ setLevel(current);
+ }, METER_INTERVAL_MS);
+
+ test.current = { stream, context, timer };
+ setTesting(true);
+ } catch {
+ setTestFailed(true);
+ }
+ }, [stopTest, value]);
+
+ const state = microphoneListState(devices);
+ const options = toMicrophoneOptions(devices);
+ const missing = isMicrophoneMissing(value, options);
+
+ return (
+ <div>
+ <label
+ htmlFor={state === 'ready' ? triggerId : undefined}
+ className="block text-[11px] font-semibold text-foreground mb-1"
+ >
+ {i18n.t('settings.microphone')}
+ </label>
+
+ {state === 'no-devices' && (
+ <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('settings.microphoneNone')}</p>
+ )}
+
+ {state === 'unlabelled' && (
+ <div className="space-y-2">
+ <p className="text-[10px] text-muted-foreground leading-relaxed">
+ {i18n.t('settings.microphoneNeedsAccess')}
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void requestAccess()}
+ className="w-full text-[11px] font-semibold"
+ >
+ <Mic size={12} />
+ {i18n.t('settings.microphoneGrantAccess')}
+ </Button>
+ </div>
+ )}
+
+ {state === 'ready' && (
+ <div className="space-y-2">
+ <Select
+ value={toSelectValue(value)}
+ onValueChange={(next) => {
+ stopTest();
+ onChange(toStoredMicrophoneId(next));
+ }}
+ >
+ <SelectTrigger
+ id={triggerId}
+ aria-label={i18n.t('settings.microphone')}
+ className="rounded-lg border-border bg-card text-[13px] font-medium text-foreground"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={SYSTEM_DEFAULT_VALUE}>{i18n.t('settings.microphoneDefault')}</SelectItem>
+ {options.map((option) => (
+ <SelectItem key={option.deviceId} value={option.deviceId}>
+ {option.label}
+ </SelectItem>
+ ))}
+ {missing && (
+ <SelectItem value={toSelectValue(value)}>{i18n.t('settings.microphoneUnavailable')}</SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+
+ {missing && (
+ <p className="flex items-start gap-1.5 text-[10px] text-destructive leading-relaxed">
+ <TriangleAlert size={11} className="shrink-0 mt-0.5" />
+ <span>{i18n.t('settings.microphoneMissing')}</span>
+ </p>
+ )}
+
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => (testing ? stopTest() : void startTest())}
+ className="w-full text-[11px] font-semibold"
+ >
+ {testing ? <Square size={11} /> : <Mic size={11} />}
+ {i18n.t(testing ? 'settings.microphoneTestStop' : 'settings.microphoneTest')}
+ </Button>
+
+ {testing ? (
+ <div className="space-y-1">
+ <div aria-hidden="true" className="h-1.5 w-full rounded-full bg-secondary overflow-hidden">
+ <div
+ className="h-full rounded-full bg-accent transition-[width] duration-100 motion-reduce:transition-none"
+ style={{ width: `${Math.round(level * 100)}%` }}
+ />
+ </div>
+ <p aria-live="polite" className="text-[10px] text-muted-foreground">
+ {i18n.t(level > SPEAKING_LEVEL ? 'voice.micHearing' : 'voice.micQuiet')}
+ </p>
+ </div>
+ ) : (
+ <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('settings.microphoneTestHint')}</p>
+ )}
+
+ {testFailed && (
+ <p className="text-[10px] text-destructive leading-relaxed">{i18n.t('settings.microphoneTestFailed')}</p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index f0a26dd..787ed5a 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -8,6 +8,7 @@ import type { VoiceProvider } from '@/core/capture/voice/transcribe';
import { localStorage } from '@/lib/browser-api';
import { Button } from '@/ui/components/ui/button';
import { Input } from '@/ui/components/ui/input';
+import MicrophonePicker from '@/ui/shared/MicrophonePicker';
interface SettingsViewProps {
onBack?: () => void;
@@ -218,6 +219,10 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
/>
</div>
+ {import.meta.env.BROWSER !== 'firefox' && (
+ <MicrophonePicker value={voiceMicrophoneId} onChange={setVoiceMicrophoneId} />
+ )}
+
<div className="flex items-start gap-2 px-3 py-2.5 rounded-lg bg-secondary text-[10px] text-muted-foreground leading-relaxed">
<Shield size={12} className="shrink-0 mt-0.5 text-accent" />
<span>{i18n.t('settings.voiceDataNotice')}</span>
diff --git a/src/ui/shared/__tests__/microphones.test.ts b/src/ui/shared/__tests__/microphones.test.ts
new file mode 100644
index 0000000..198fa94
--- /dev/null
+++ b/src/ui/shared/__tests__/microphones.test.ts
@@ -0,0 +1,193 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import {
+ isMicrophoneMissing,
+ type MicrophoneOption,
+ microphoneListState,
+ nextMicLevel,
+ SPEAKING_LEVEL,
+ SYSTEM_DEFAULT_VALUE,
+ toMicrophoneOptions,
+ toSelectValue,
+ toStoredMicrophoneId,
+} from '../microphones';
+
+const LOCALES = ['en', 'es', 'fr', 'pt-BR'];
+
+const MICROPHONE_KEYS = [
+ 'settings.microphone',
+ 'settings.microphoneDefault',
+ 'settings.microphoneNeedsAccess',
+ 'settings.microphoneGrantAccess',
+ 'settings.microphoneNone',
+ 'settings.microphoneUnavailable',
+ 'settings.microphoneMissing',
+ 'settings.microphoneTest',
+ 'settings.microphoneTestStop',
+ 'settings.microphoneTestHint',
+ 'settings.microphoneTestFailed',
+ 'voice.micHearing',
+ 'voice.micQuiet',
+];
+
+function device(kind: MediaDeviceKind, deviceId: string, label: string) {
+ return { kind, deviceId, label };
+}
+
+function option(deviceId: string, label: string): MicrophoneOption {
+ return { deviceId, label };
+}
+
+function localeKeys(locale: string): Set<string> {
+ const keys = new Set<string>();
+ let section = '';
+ for (const line of readFileSync(join(process.cwd(), 'src/locales', `${locale}.yml`), 'utf8').split('\n')) {
+ const top = /^([\w-]+):/.exec(line);
+ if (top) {
+ section = top[1];
+ continue;
+ }
+ const nested = /^ {2}([\w-]+):/.exec(line);
+ if (nested && section) keys.add(`${section}.${nested[1]}`);
+ }
+ return keys;
+}
+
+describe('toMicrophoneOptions', () => {
+ it('keeps only audio inputs', () => {
+ const options = toMicrophoneOptions([
+ device('audioinput', 'mic-1', 'Built-in Microphone'),
+ device('audiooutput', 'speaker-1', 'Built-in Output'),
+ device('videoinput', 'cam-1', 'FaceTime HD Camera'),
+ ]);
+ expect(options).toEqual([option('mic-1', 'Built-in Microphone')]);
+ });
+
+ it('drops the aliases the system default option already covers', () => {
+ const options = toMicrophoneOptions([
+ device('audioinput', 'default', 'Default - Headset'),
+ device('audioinput', 'communications', 'Communications - Headset'),
+ device('audioinput', 'mic-1', 'Headset'),
+ ]);
+ expect(options).toEqual([option('mic-1', 'Headset')]);
+ });
+
+ it('drops devices without an id and repeated ids', () => {
+ const options = toMicrophoneOptions([
+ device('audioinput', '', 'Nameless'),
+ device('audioinput', 'mic-1', 'Headset'),
+ device('audioinput', 'mic-1', 'Headset'),
+ ]);
+ expect(options).toEqual([option('mic-1', 'Headset')]);
+ });
+
+ it('keeps the blank labels the browser reports before permission is granted', () => {
+ expect(toMicrophoneOptions([device('audioinput', 'mic-1', '')])).toEqual([option('mic-1', '')]);
+ });
+});
+
+describe('microphoneListState', () => {
+ it('reports no devices when nothing is plugged in', () => {
+ expect(microphoneListState([])).toBe('no-devices');
+ });
+
+ it('reports no devices when only outputs and cameras are present', () => {
+ expect(microphoneListState([device('audiooutput', 'speaker-1', 'Speakers')])).toBe('no-devices');
+ });
+
+ it('reports unlabelled for the blank placeholder Chrome returns before permission', () => {
+ expect(microphoneListState([device('audioinput', '', '')])).toBe('unlabelled');
+ });
+
+ it('reports unlabelled when ids are exposed but names are withheld', () => {
+ expect(microphoneListState([device('audioinput', 'mic-1', ''), device('audioinput', 'mic-2', '')])).toBe(
+ 'unlabelled',
+ );
+ });
+
+ it('reports unlabelled when even one name is missing', () => {
+ expect(microphoneListState([device('audioinput', 'mic-1', 'Headset'), device('audioinput', 'mic-2', '')])).toBe(
+ 'unlabelled',
+ );
+ });
+
+ it('reports ready once every input has an id and a name', () => {
+ expect(microphoneListState([device('audioinput', 'mic-1', 'Headset'), device('audiooutput', '', '')])).toBe(
+ 'ready',
+ );
+ });
+});
+
+describe('select value round trip', () => {
+ it('shows the system default option for the empty stored id', () => {
+ expect(toSelectValue('')).toBe(SYSTEM_DEFAULT_VALUE);
+ expect(toSelectValue(' ')).toBe(SYSTEM_DEFAULT_VALUE);
+ });
+
+ it('shows the stored device id when one is chosen', () => {
+ expect(toSelectValue('mic-1')).toBe('mic-1');
+ });
+
+ it('stores the empty string the voice host reads as system default', () => {
+ expect(toStoredMicrophoneId(SYSTEM_DEFAULT_VALUE)).toBe('');
+ });
+
+ it('stores the device id for a real choice', () => {
+ expect(toStoredMicrophoneId('mic-1')).toBe('mic-1');
+ });
+
+ it('never produces the empty value Radix rejects for an item', () => {
+ expect(toSelectValue(toStoredMicrophoneId(SYSTEM_DEFAULT_VALUE))).toBe(SYSTEM_DEFAULT_VALUE);
+ });
+});
+
+describe('isMicrophoneMissing', () => {
+ it('treats system default as always present', () => {
+ expect(isMicrophoneMissing('', [])).toBe(false);
+ });
+
+ it('finds the stored device in the current list', () => {
+ expect(isMicrophoneMissing('mic-1', [option('mic-1', 'Headset')])).toBe(false);
+ });
+
+ it('flags a stored device that has been unplugged', () => {
+ expect(isMicrophoneMissing('mic-1', [option('mic-2', 'Built-in')])).toBe(true);
+ });
+});
+
+describe('nextMicLevel', () => {
+ it('floors silence at zero', () => {
+ expect(nextMicLevel(0, 0)).toBe(0);
+ });
+
+ it('clamps a hot signal to one', () => {
+ expect(nextMicLevel(4, 1)).toBe(1);
+ });
+
+ it('smooths towards the new reading instead of jumping', () => {
+ const level = nextMicLevel(1, 0);
+ expect(level).toBeGreaterThan(0);
+ expect(level).toBeLessThan(1);
+ });
+
+ it('crosses the speaking threshold for speech and not for room noise', () => {
+ const speech = 10 ** (-30 / 20);
+ const noise = 10 ** (-55 / 20);
+ let speaking = 0;
+ let quiet = 0;
+ for (let i = 0; i < 20; i += 1) {
+ speaking = nextMicLevel(speech, speaking);
+ quiet = nextMicLevel(noise, quiet);
+ }
+ expect(speaking).toBeGreaterThan(SPEAKING_LEVEL);
+ expect(quiet).toBeLessThan(SPEAKING_LEVEL);
+ });
+});
+
+describe('microphone picker copy', () => {
+ it.each(LOCALES)('%s carries every key the picker renders', (locale) => {
+ const keys = localeKeys(locale);
+ for (const key of MICROPHONE_KEYS) expect(keys).toContain(key);
+ });
+});
diff --git a/src/ui/shared/microphones.ts b/src/ui/shared/microphones.ts
new file mode 100644
index 0000000..0e5351f
--- /dev/null
+++ b/src/ui/shared/microphones.ts
@@ -0,0 +1,61 @@
+export const SYSTEM_DEFAULT_VALUE = 'mimik-system-default';
+
+const GENERIC_DEVICE_IDS = new Set(['default', 'communications']);
+
+export interface MicrophoneOption {
+ deviceId: string;
+ label: string;
+}
+
+export type MicrophoneListState = 'no-devices' | 'unlabelled' | 'ready';
+
+export type MicrophoneDevice = Pick<MediaDeviceInfo, 'kind' | 'deviceId' | 'label'>;
+
+function audioInputs(devices: readonly MicrophoneDevice[]): MicrophoneDevice[] {
+ return devices.filter((device) => device.kind === 'audioinput');
+}
+
+export function toMicrophoneOptions(devices: readonly MicrophoneDevice[]): MicrophoneOption[] {
+ const seen = new Set<string>();
+ const options: MicrophoneOption[] = [];
+ for (const device of audioInputs(devices)) {
+ const deviceId = device.deviceId.trim();
+ if (!deviceId || GENERIC_DEVICE_IDS.has(deviceId) || seen.has(deviceId)) continue;
+ seen.add(deviceId);
+ options.push({ deviceId, label: device.label.trim() });
+ }
+ return options;
+}
+
+export function microphoneListState(devices: readonly MicrophoneDevice[]): MicrophoneListState {
+ const inputs = audioInputs(devices);
+ if (inputs.length === 0) return 'no-devices';
+ const withheld = inputs.some((device) => !device.deviceId.trim() || !device.label.trim());
+ return withheld ? 'unlabelled' : 'ready';
+}
+
+export function toSelectValue(storedId: string): string {
+ return storedId.trim() || SYSTEM_DEFAULT_VALUE;
+}
+
+export function toStoredMicrophoneId(value: string): string {
+ return value === SYSTEM_DEFAULT_VALUE ? '' : value.trim();
+}
+
+export function isMicrophoneMissing(storedId: string, options: readonly MicrophoneOption[]): boolean {
+ const id = storedId.trim();
+ if (!id) return false;
+ return !options.some((option) => option.deviceId === id);
+}
+
+const LEVEL_FLOOR_DB = -60;
+const SPEAKING_FLOOR_DB = -45;
+const LEVEL_SMOOTHING = 0.6;
+
+export const SPEAKING_LEVEL = (SPEAKING_FLOOR_DB - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB;
+
+export function nextMicLevel(rms: number, previous: number): number {
+ 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));
+ return previous * LEVEL_SMOOTHING + normalised * (1 - LEVEL_SMOOTHING);
+}