Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

reuse audioRecorder's WAV helpers in voiceClient (#6829)

[._.]/ Adam Eivy5ec059745e87
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e69e96f470..f6dd9fd565 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -122,7 +122,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `avatarStyles.js` | Re-export of `server/lib/avatarStyles.js` — the CoS avatar-style vocabulary (#6253): `AVATAR_STYLES`, `AVATAR_STYLE_IDS`, `AVATAR_STYLE_LABELS`, `WEBGL_AVATAR_STYLE_IDS`. The picker labels, the lazy-load map / WebGL-stage set, and the server's `avatarStyle` zod enum all read the one list. |
| `assessmentTuningNotice.js` | `tuningNoticeChip(entry)` — the short form of how a measured local-model assessment says its launch configuration did NOT take effect. `tuningApplied === false` covers two opposite cases and `tuningKey` separates them: a TUNED run whose knobs never reached the daemon (`tuning not applied`), versus an UNTUNED run PortOS could not put back on backend defaults (`not at defaults`) — #4759. Shared by `ModelThroughputReport.jsx`'s table cell and `LocalModelAssessments.jsx`'s result toast; the long form is the server's exclusion reason in `getAssessmentReport`. |
| `callAudioBridge.js` | Pure device/format helpers for the call-host page (`pages/VoiceCallHost.jsx`, #5308 + #5311) — shared by its Call mode (FaceTime Audio) and its Capture system audio mode (meeting transcription). `missingCallHostApis(scope)` lists every required browser API this browser lacks (MediaStreamTrackProcessor/Generator, AudioWorklet, `enumerateDevices`, `setSinkId`, Web Locks) so the page names all the gaps at once instead of one per reload; `findAudioDevice(devices, label, kind)` matches a device label EXACTLY after trim+case-fold (a substring match would resolve "BlackHole 1" to the 16ch device, indistinguishable from a dead call); `describeDeviceProblem(devices, {inputLabel, outputLabel})` returns the one blocking message or `null`, and deliberately blames MICROPHONE PERMISSION rather than a missing driver when every label comes back blank — an ungranted tab enumerates unlabeled devices, and "reinstall BlackHole" would send the user to fix the wrong thing; `outputLabel` is OPTIONAL — capture mode only listens, so omitting it skips the output-device check entirely rather than reporting a device named "undefined" as missing. Format side: `downmixToMono(channels)` (BlackHole 16ch carries the call on all channels; truncates to the shortest rather than reading past one), `resampleTo16k(samples, fromRate)` (linear, 48k→16k for whisper), `floatToInt16` (CLAMPED — wrapping would flip a hot sample's sign into an audible click), `rmsLevel` for the input meter, and `buildTestTone` (faded in/out so it cannot click through the call). Plus `CALL_HOST_LOCK` (the Web Lock name that stops a second tab double-answering — shared by both modes, since they read the same physical device) and `CALL_FRAME_SAMPLES`. |
-| `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. **`openAnalysisMic({ getUserMedia })`** → `{ stream, processing }` is the ONE way a pitch-analysis surface opens a mic: it requests `ANALYSIS_AUDIO_CONSTRAINTS` (echo cancellation / noise suppression / AGC off — plain booleans, never `{ exact }`, so a browser that can't honor one still opens the mic) and reads `track.getSettings()` back so the UI can say what actually stuck. `readAppliedProcessing(stream)` reports each stage as `true` / `false` / `null` (browser didn't say — never collapse unknown into off) and `hasUnwantedProcessing(p)` gates the warning. Memo capture deliberately keeps the speech-tuned defaults; Whisper wants them. |
+| `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k` (decode a recorded blob → `{ wav, peak }`), `float32ToWav16k(samples, sourceRate)` (resample a raw Float32 PCM buffer, e.g. an AudioWorklet capture, → `{ wav, peak }`; `{ wav: null, peak: 0 }` for empty input), `encodePcmToWav`, `TARGET_SAMPLE_RATE` (16000), `pickRecordingMimeType`, `arrayBufferToBase64`. Shared WAV-encode/resample path for both this standalone memo-capture flow AND the live voice-agent recorder in `services/voiceClient.js`. **`openAnalysisMic({ getUserMedia })`** → `{ stream, processing }` is the ONE way a pitch-analysis surface opens a mic: it requests `ANALYSIS_AUDIO_CONSTRAINTS` (echo cancellation / noise suppression / AGC off — plain booleans, never `{ exact }`, so a browser that can't honor one still opens the mic) and reads `track.getSettings()` back so the UI can say what actually stuck. `readAppliedProcessing(stream)` reports each stage as `true` / `false` / `null` (browser didn't say — never collapse unknown into off) and `hasUnwantedProcessing(p)` gates the warning. Memo capture deliberately keeps the speech-tuned defaults; Whisper wants them. |
| `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Re-exported from `server/lib/bareUrl.js`, the rule the brain-capture route applies. |
| `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` re-exported from `server/lib/youtubeUrl.js`, so Quick Capture can only offer the ingest path for a URL the server accepts. Also the client-only `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. |
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
diff --git a/client/src/lib/audioRecorder.js b/client/src/lib/audioRecorder.js
index 9c0114da0b..d0b03c174a 100644
--- a/client/src/lib/audioRecorder.js
+++ b/client/src/lib/audioRecorder.js
@@ -2,13 +2,16 @@
// capture (catalog voice ingest). whisper.cpp accepts WAV only, so we decode
// whatever MediaRecorder produced and resample to 16 kHz mono before encoding.
//
-// This is deliberately NOT coupled to services/voiceClient.js — that module's
-// recorder is wired to the live voice-agent socket pipeline (echo gating, VAD,
-// streaming TTS). This is a standalone "record a clip, get a WAV" helper.
+// `startMemoRecording` and the analysis-mic helpers below are standalone
+// "record a clip, get a WAV" plumbing — NOT wired to the live voice-agent
+// socket pipeline (echo gating, VAD, streaming TTS) that owns
+// services/voiceClient.js. The WAV-encode/resample helpers (`encodePcmToWav`,
+// `blobToWav16k`, `float32ToWav16k`) ARE shared with that module — it imports
+// them rather than keeping its own copy.
import { resumeAudioContext, acquireAudioSession } from './audioContext.js';
-const TARGET_SAMPLE_RATE = 16000;
+export const TARGET_SAMPLE_RATE = 16000;
// Pick a MediaRecorder mime the browser supports; Safari lands on mp4, others
// on webm/opus. We re-decode to WAV regardless, so the intermediate codec
@@ -74,6 +77,31 @@ export async function blobToWav16k(blob) {
return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
}
+// Encode a Float32 PCM buffer captured at `sourceRate` (e.g. an AudioWorklet's
+// continuous-mode capture) → 16 kHz mono WAV. Same resample path as
+// `blobToWav16k`, but the source is already raw PCM rather than an encoded
+// blob. Returns `{ wav: null, peak: 0 }` for an empty buffer — nothing to
+// render — so callers can skip a zero-length OfflineAudioContext.
+export async function float32ToWav16k(samples, sourceRate) {
+ if (!samples.length) return { wav: null, peak: 0 };
+ const frames = Math.ceil(samples.length * TARGET_SAMPLE_RATE / sourceRate);
+ const offline = new OfflineAudioContext(1, frames, TARGET_SAMPLE_RATE);
+ const buf = offline.createBuffer(1, samples.length, sourceRate);
+ buf.getChannelData(0).set(samples);
+ const src = offline.createBufferSource();
+ src.buffer = buf;
+ src.connect(offline.destination);
+ src.start();
+ const rendered = await offline.startRendering();
+ const pcm = rendered.getChannelData(0);
+ let peak = 0;
+ for (let i = 0; i < pcm.length; i++) {
+ const a = Math.abs(pcm[i]);
+ if (a > peak) peak = a;
+ }
+ return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
+}
+
// Base64-encode an ArrayBuffer in chunks (avoids the call-stack blowup of
// String.fromCharCode(...bigArray) on multi-second recordings).
export function arrayBufferToBase64(buffer) {
diff --git a/client/src/lib/audioRecorder.test.js b/client/src/lib/audioRecorder.test.js
index 380b23146f..ad8cbc7b0c 100644
--- a/client/src/lib/audioRecorder.test.js
+++ b/client/src/lib/audioRecorder.test.js
@@ -4,9 +4,10 @@
// reports what the browser actually did. The rest of audioRecorder.js is Web
// Audio / MediaRecorder plumbing exercised through its component callers.
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
import {
ANALYSIS_AUDIO_CONSTRAINTS,
+ float32ToWav16k,
hasUnwantedProcessing,
openAnalysisMic,
readAppliedProcessing,
@@ -75,3 +76,40 @@ describe('hasUnwantedProcessing', () => {
expect(hasUnwantedProcessing({ echoCancellation: null, noiseSuppression: true, autoGainControl: null })).toBe(true);
});
});
+
+describe('float32ToWav16k', () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('encodes a resampled PCM buffer into a WAV with a correct header and peak', async () => {
+ const rendered = new Float32Array([0, 0.5, -1, 0.25]);
+ class FakeOfflineAudioContext {
+ createBuffer(channels, length) {
+ return { getChannelData: () => new Float32Array(length) };
+ }
+ createBufferSource() {
+ return { buffer: null, connect: () => {}, start: () => {} };
+ }
+ async startRendering() {
+ return { getChannelData: () => rendered };
+ }
+ }
+ vi.stubGlobal('OfflineAudioContext', FakeOfflineAudioContext);
+
+ const { wav, peak } = await float32ToWav16k(new Float32Array([0, 1, -1, 0.5]), 48000);
+
+ expect(peak).toBe(1);
+ const view = new DataView(wav);
+ const readStr = (off, len) => String.fromCharCode(...Array.from({ length: len }, (_, i) => view.getUint8(off + i)));
+ expect(readStr(0, 4)).toBe('RIFF');
+ expect(readStr(8, 4)).toBe('WAVE');
+ expect(view.getUint32(24, true)).toBe(16000); // sample rate in the fmt chunk
+ expect(view.getUint32(40, true)).toBe(rendered.length * 2); // data chunk byte size
+ expect(wav.byteLength).toBe(44 + rendered.length * 2);
+ });
+
+ it('skips rendering and returns a null wav for an empty buffer', async () => {
+ const { wav, peak } = await float32ToWav16k(new Float32Array(0), 48000);
+ expect(wav).toBeNull();
+ expect(peak).toBe(0);
+ });
+});
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index 5a9d11920e..a44d45a5a8 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -9,6 +9,7 @@ import socket from './socket';
import { subscribeVisibility } from '../hooks/useVisibilityEvent.js';
import { sleep } from '../utils/sleep.js';
import { resumeAudioContext, acquireAudioSession } from '../lib/audioContext.js';
+import { blobToWav16k, float32ToWav16k } from '../lib/audioRecorder.js';
import { ECHO_WINDOW_MS, MIN_TOKENS_FOR_ECHO_CHECK, MIN_SHARED_TRIGRAMS, tokenize, trigramsOf } from '../../../server/lib/voiceEcho.js';
// iOS audio-session claims held while a mic stream is open — one per capture
@@ -78,71 +79,6 @@ const stopPlayback = () => {
synthGen += 1;
};
-// whisper.cpp only accepts 16-bit PCM WAV — it has no built-in audio decoder.
-// Decode whatever MediaRecorder produced, downmix to mono, resample to 16 kHz,
-// and hand-encode a minimal WAV header.
-const TARGET_SAMPLE_RATE = 16000;
-
-const encodePcmToWav = (float32, sampleRate) => {
- const n = float32.length;
- const buffer = new ArrayBuffer(44 + n * 2);
- const view = new DataView(buffer);
- const writeStr = (off, s) => { for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i)); };
-
- writeStr(0, 'RIFF');
- view.setUint32(4, 36 + n * 2, true);
- writeStr(8, 'WAVE');
- writeStr(12, 'fmt ');
- view.setUint32(16, 16, true);
- view.setUint16(20, 1, true);
- view.setUint16(22, 1, true);
- view.setUint32(24, sampleRate, true);
- view.setUint32(28, sampleRate * 2, true);
- view.setUint16(32, 2, true);
- view.setUint16(34, 16, true);
- writeStr(36, 'data');
- view.setUint32(40, n * 2, true);
-
- let off = 44;
- for (let i = 0; i < n; i++) {
- const s = Math.max(-1, Math.min(1, float32[i]));
- view.setInt16(off, s < 0 ? s * 0x8000 : s * 0x7fff, true);
- off += 2;
- }
- return buffer;
-};
-
-const blobToWav16k = async (blob) => {
- const bytes = await blob.arrayBuffer();
- const decodeCtx = new (window.AudioContext || window.webkitAudioContext)();
- // Chain .finally() so a decode failure (unsupported codec, corrupt blob)
- // still releases the AudioContext — otherwise repeated failures leak a
- // context per retry.
- const decoded = await decodeCtx.decodeAudioData(bytes).finally(() => {
- decodeCtx.close().catch(() => {});
- });
-
- // OfflineAudioContext handles resampling natively when we render at the target rate.
- const frames = Math.ceil(decoded.duration * TARGET_SAMPLE_RATE);
- const offline = new OfflineAudioContext(1, frames, TARGET_SAMPLE_RATE);
- const src = offline.createBufferSource();
- src.buffer = decoded;
- src.connect(offline.destination);
- src.start();
- const rendered = await offline.startRendering();
- const pcm = rendered.getChannelData(0);
-
- // Peak amplitude surfaces dead-mic / too-quiet situations that whisper would
- // otherwise silently transcribe as [BLANK_AUDIO].
- let peak = 0;
- for (let i = 0; i < pcm.length; i++) {
- const a = Math.abs(pcm[i]);
- if (a > peak) peak = a;
- }
-
- return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
-};
-
const enqueuePlay = async (bytes) => {
const generation = playbackGeneration;
const ctx = ensureCtx();
@@ -801,27 +737,6 @@ class VADProcessor extends AudioWorkletProcessor {
registerProcessor('vad-processor', VADProcessor);
`;
-const float32ToWav16k = async (samples, sourceRate) => {
- if (!samples.length) return { wav: null, peak: 0 };
- const frames = Math.ceil(samples.length * TARGET_SAMPLE_RATE / sourceRate);
- const offline = new OfflineAudioContext(1, frames, TARGET_SAMPLE_RATE);
- const buf = offline.createBuffer(1, samples.length, sourceRate);
- buf.getChannelData(0).set(samples);
- const src = offline.createBufferSource();
- src.buffer = buf;
- src.connect(offline.destination);
- src.start();
- const rendered = await offline.startRendering();
- const pcm = rendered.getChannelData(0);
-
- let peak = 0;
- for (let i = 0; i < pcm.length; i++) {
- const a = Math.abs(pcm[i]);
- if (a > peak) peak = a;
- }
- return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
-};
-
const submitUtterance = async () => {
if (!speechChunks.length) return;
const chunksToSubmit = speechChunks;