Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(transcription): re-encode to WAV for Custom STT endpoints and retries (microsoft/mai-transcribe-2) (#2029)
Marcel-Felix Kraused771e56f5191
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex cdf8bbae9..9ebf28a9e 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -3,6 +3,7 @@ import logger from "../utils/logger";import { isAzureOpenAIEndpoint } from "../utils/urlUtils";import { withSessionRefresh } from "../lib/auth";import { getBaseLanguageCode, getLanguageLabel } from "../utils/languageSupport";+import { convertToWav, needsWavConversion } from "../utils/audioContainer";import {applyChineseScript,mergeWhisperPrompt,@@ -64,6 +65,7 @@ import {} from "../models/ModelRegistry";import { TINFOIL_PROXY_REQUIRED_ERROR } from "../services/transcriptionBaseUrl";import {+ byokFileSizeLimit,resolveByokModel,resolveTranscriptionRoute,STREAMING_ONLY_PROVIDERS,@@ -3603,9 +3605,45 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return { success: true, text, rawText: proxyText, source, timings };}+ // Some Custom endpoints decode the upload and reject anything that isn't+ // WAV/MP3/FLAC (Azure MAI-Transcribe via OpenRouter, for one), which+ // Chromium's WebM/Opus recordings always are. Re-encode for those rather+ // than failing the dictation; a conversion failure falls through to the+ // original bytes so this can only widen what works.+ let uploadAudio = optimizedAudio;+ if (needsWavConversion(provider, optimizedAudio.type, optimizedAudio.size)) {+ try {+ const wavAudio = await convertToWav(optimizedAudio);+ // Keep compressed recordings usable on endpoints that already accept+ // them when PCM expansion would exceed the upload limit.+ if (wavAudio.size <= byokFileSizeLimit(provider)) {+ uploadAudio = wavAudio;+ }+ logger.debug(+ "Prepared recording for custom endpoint",+ {+ fromType: optimizedAudio.type,+ fromSize: optimizedAudio.size,+ toType: uploadAudio.type,+ toSize: uploadAudio.size,+ },+ "transcription"+ );+ } catch (conversionError) {+ logger.warn(+ "WAV re-encode failed; uploading original container",+ { error: conversionError?.message, type: optimizedAudio.type },+ "transcription"+ );+ }+ }++ // Decoding can outlive cancellation and a newer recording's request.+ if (wasCancelled()) throw new DOMException("Transcription cancelled", "AbortError");+const formData = new FormData();// Determine the correct file extension based on the blob type- const mimeType = optimizedAudio.type || "audio/webm";+ const mimeType = uploadAudio.type || "audio/webm";const extension = audioExtensionForMime(mimeType);logger.debug(@@ -3613,13 +3651,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);{mimeType,extension,- optimizedSize: optimizedAudio.size,+ optimizedSize: uploadAudio.size,hasApiKey: !!apiKey,},"transcription");- formData.append("file", optimizedAudio, `audio.${extension}`);+ formData.append("file", uploadAudio, `audio.${extension}`);formData.append("model", model);if (language) {diff --git a/src/helpers/ffmpegUtils.js b/src/helpers/ffmpegUtils.jsindex 095ff3d3b..8d45a99a2 100644--- a/src/helpers/ffmpegUtils.js+++ b/src/helpers/ffmpegUtils.js@@ -232,6 +232,34 @@ function convertToMp3(inputPath, outputPath, options = {}) {);}+let reencodeSequence = 0;++// Buffer in, buffer out. convertToWav works on paths, but retry paths hold+// recordings in memory and should not repeat the temp-file handling.+async function convertBufferToWav(audioBuffer, options = {}) {+ const { getSafeTempDir } = require("./safeTempDir");+ const tempDir = getSafeTempDir();+ // process.pid is constant within a process and Date.now() only has+ // millisecond resolution, so concurrent retries need a sequence suffix.+ const stamp = `${Date.now()}-${process.pid}-${++reencodeSequence}`;+ const inputPath = path.join(tempDir, `ow-reencode-${stamp}.input`);+ const outputPath = path.join(tempDir, `ow-reencode-${stamp}.wav`);++ try {+ fs.writeFileSync(inputPath, audioBuffer);+ await convertToWav(inputPath, outputPath, { sampleRate: 16000, channels: 1, ...options });+ return fs.readFileSync(outputPath);+ } finally {+ for (const filePath of [inputPath, outputPath]) {+ try {+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);+ } catch {+ // A stale temp file should not hide the transcription result or error.+ }+ }+ }+}+function parseWavFormat(wavBuffer) {if (!isWavFormat(wavBuffer)) return null;@@ -517,6 +545,7 @@ module.exports = {parseWavFormat,isPcm16Mono16kWav,convertToWav,+ convertBufferToWav,convertToMp3,splitAudioFile,parseFfmpegDuration,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex e2b10f6dc..365b3eb58 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -6333,6 +6333,7 @@ class IPCHandlers {? preferredLanguage.split("-")[0]: undefined;const { resolveTranscriptionRoute } = await import("./transcriptionRoute.ts");+ const { convertBufferToWav, isWavFormat } = require("./ffmpegUtils");// Renderer pre-flight owns policy; retry re-routes stored audio through// whatever is selected NOW.const route = resolveTranscriptionRoute({@@ -6521,8 +6522,35 @@ class IPCHandlers {throw new Error(`${provider} API key not configured`);}+ // The renderer re-encodes WebM before uploading to a Custom endpoint+ // (src/utils/audioContainer.ts); retries re-upload stored audio from+ // the main process, so without the same step here every retry of a+ // dictation that failed for that reason fails again -- which is the+ // exact recovery a user reaches for after hitting it.+ let uploadBuffer = buffer;+ let uploadType = "audio/webm";+ let uploadName = "audio.webm";+ if (provider === "custom" && buffer.length && !isWavFormat(buffer)) {+ try {+ const wavBuffer = await convertBufferToWav(buffer);+ // Match fresh dictation: PCM expansion must not break an upload+ // that the endpoint could accept in its original container.+ if (wavBuffer.length <= route.sizeCapBytes) {+ uploadBuffer = wavBuffer;+ uploadType = "audio/wav";+ uploadName = "audio.wav";+ }+ } catch (conversionError) {+ // Fail open, matching the renderer: an unconverted retry is no+ // worse than today's behaviour.+ debugLogger.warn("WAV re-encode failed on retry; uploading stored container", {+ error: conversionError?.message,+ });+ }+ }+const formData = new FormData();- formData.append("file", new Blob([buffer], { type: "audio/webm" }), "audio.webm");+ formData.append("file", new Blob([uploadBuffer], { type: uploadType }), uploadName);if (provider === "xai") {// xAI STT does not accept a model field; the route pre-filters languageif (route.language) {diff --git a/src/utils/audioContainer.ts b/src/utils/audioContainer.tsnew file mode 100644index 000000000..98f4ff72c--- /dev/null+++ b/src/utils/audioContainer.ts@@ -0,0 +1,125 @@+// Chromium's MediaRecorder only offers WebM/Opus (and MP4/AAC) on the desktop+// platforms we ship, so every dictation reaches the upload path as WebM. Most+// OpenAI-compatible transcription backends accept that, but some decode the+// bytes themselves and reject anything outside WAV/MP3/FLAC — Azure's+// MAI-Transcribe, reached through OpenRouter, is one. Those endpoints are only+// selectable via the Custom provider, so the conversion is scoped there and+// every built-in provider keeps sending Opus untouched.+//+// The rejection is by content, not by labelling: renaming the part or rewriting+// its Content-Type does not help, so the audio has to actually be re-encoded.++const WAV_HEADER_BYTES = 44;+const BYTES_PER_SAMPLE = 2;++// Speech models resample to 16 kHz mono internally, and the main process+// already standardises on it (ffmpegUtils.convertToWav defaults to exactly+// this), so matching it here keeps the two conversion paths consistent and+// keeps the upload ~6x smaller than the decoded 48 kHz stream.+const TARGET_SAMPLE_RATE = 16000;++// Containers these backends already accept. Anything else is re-encoded --+// an allowlist rather than a list of known-bad containers, so a format we+// have not seen yet (MP4/AAC on some platforms) converts instead of being+// uploaded and rejected.+const ACCEPTED_CONTAINERS = ["wav", "x-wav", "wave", "mpeg", "mp3", "flac"];++export function needsWavConversion(+ provider: string | undefined,+ mimeType: string | undefined,+ size?: number+): boolean {+ if (provider !== "custom") return false;+ // An empty recording has nothing to decode; converting it would only turn a+ // silent no-op into a spurious "re-encode failed" warning.+ if (size === 0) return false;+ const type = (mimeType || "").toLowerCase();+ if (!type) return false;+ return !ACCEPTED_CONTAINERS.some((container) => type.includes(container));+}++// Interleaved 16-bit PCM in a RIFF container. Kept pure and free of Web Audio+// types so it can be unit-tested without a browser.+export function encodeWav(channels: Float32Array[], sampleRate: number): ArrayBuffer {+ if (!channels.length) throw new Error("encodeWav requires at least one channel");++ const channelCount = channels.length;+ const frameCount = channels[0].length;+ const dataBytes = frameCount * channelCount * BYTES_PER_SAMPLE;+ const buffer = new ArrayBuffer(WAV_HEADER_BYTES + dataBytes);+ const view = new DataView(buffer);++ const ascii = (offset: number, text: string) => {+ for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i));+ };++ ascii(0, "RIFF");+ view.setUint32(4, 36 + dataBytes, true);+ ascii(8, "WAVE");+ ascii(12, "fmt ");+ view.setUint32(16, 16, true);+ view.setUint16(20, 1, true); // PCM+ view.setUint16(22, channelCount, true);+ view.setUint32(24, sampleRate, true);+ view.setUint32(28, sampleRate * channelCount * BYTES_PER_SAMPLE, true);+ view.setUint16(32, channelCount * BYTES_PER_SAMPLE, true);+ view.setUint16(34, 8 * BYTES_PER_SAMPLE, true);+ ascii(36, "data");+ view.setUint32(40, dataBytes, true);++ let offset = WAV_HEADER_BYTES;+ for (let frame = 0; frame < frameCount; frame++) {+ for (let channel = 0; channel < channelCount; channel++) {+ // Clamp before scaling: decoded float samples can sit slightly outside+ // [-1, 1] and would otherwise wrap to the opposite rail.+ const sample = Math.max(-1, Math.min(1, channels[channel][frame]));+ view.setInt16(offset, Math.round(sample * (sample < 0 ? 0x8000 : 0x7fff)), true);+ offset += BYTES_PER_SAMPLE;+ }+ }++ return buffer;+}++// Averages channels into one. Speech backends gain nothing from stereo and it+// doubles the upload, so the mono mixdown happens before encoding.+export function downmixToMono(channels: Float32Array[]): Float32Array {+ if (!channels.length) throw new Error("downmixToMono requires at least one channel");+ if (channels.length === 1) return channels[0];++ const frameCount = channels[0].length;+ const mono = new Float32Array(frameCount);+ for (let frame = 0; frame < frameCount; frame++) {+ let sum = 0;+ for (let channel = 0; channel < channels.length; channel++) sum += channels[channel][frame];+ mono[frame] = sum / channels.length;+ }+ return mono;+}++// Renderer-side conversion, using Web Audio because ffmpeg is only reachable+// from the main process. Retries re-upload stored audio from there and cannot+// use this, so they go through ffmpegUtils.convertBufferToWav instead -- both+// paths target 16 kHz mono so the upload is identical either way.+export async function convertToWav(blob: Blob): Promise<Blob> {+ const OfflineCtor =+ (globalThis as any).OfflineAudioContext || (globalThis as any).webkitOfflineAudioContext;+ if (!OfflineCtor) throw new Error("Web Audio is unavailable in this context");++ // Decoding through an OfflineAudioContext resamples to the context rate, so+ // the 48 kHz recording arrives already downsampled -- and unlike a live+ // AudioContext it neither opens an output device nor inherits whatever rate+ // the hardware happens to run at.+ const context = new OfflineCtor(1, 1, TARGET_SAMPLE_RATE);+ const decoded = await context.decodeAudioData(await blob.arrayBuffer());++ // decodeAudioData honours the context's sample rate but not its channel+ // count, so a stereo input still decodes to two channels and has to be+ // downmixed explicitly.+ const channels: Float32Array[] = [];+ for (let i = 0; i < decoded.numberOfChannels; i++) channels.push(decoded.getChannelData(i));++ return new Blob([encodeWav([downmixToMono(channels)], decoded.sampleRate)], {+ type: "audio/wav",+ });+}diff --git a/test/helpers/audioManagerCustomUpload.test.js b/test/helpers/audioManagerCustomUpload.test.jsnew file mode 100644index 000000000..1814172d3--- /dev/null+++ b/test/helpers/audioManagerCustomUpload.test.js@@ -0,0 +1,135 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { loadAudioManager } = require("./harness/audioManager");+const { deferred } = require("./harness/deferred");++async function loadCustomManager(t, decode) {+ const originalContext = globalThis.OfflineAudioContext;+ globalThis.OfflineAudioContext = class {+ decodeAudioData() {+ return decode();+ }+ };+ t.after(() => {+ if (originalContext === undefined) delete globalThis.OfflineAudioContext;+ else globalThis.OfflineAudioContext = originalContext;+ });+ const { createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-custom-upload-test-",+ settingsKey: "__customUploadSettings",+ settings: {+ useLocalWhisper: false,+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://stt.example.com/v1",+ cloudTranscriptionModel: "whisper-1",+ allowLocalFallback: false,+ },+ });+ return createManager({+ isProcessing: true,+ _processingCancellationGeneration: 0,+ _streamingCancellationGeneration: 0,+ _streamingStopPromise: null,+ _activeTranscriptionAbortController: null,+ _localSpeechGateState: null,+ getEffectiveSttLanguage: () => "auto",+ getTranscriptionModel: () => "whisper-1",+ getAPIKey: async () => "test-key",+ getTranscriptionEndpoint: () => "https://stt.example.com/v1/audio/transcriptions",+ getWhisperPrompt: () => null,+ isDictionaryEcho: () => false,+ processTranscription: async (text) => text,+ isReasoningAvailable: async () => false,+ onStateChange() {},+ });+}++function decodedAudio(frameCount = 8) {+ const samples = new Float32Array(frameCount);+ return { sampleRate: 16000, numberOfChannels: 1, getChannelData: () => samples };+}++test("custom dictation preserves the original when WAV would exceed the upload limit", async (t) => {+ const originalAudio = new Blob(["original recording"], { type: "audio/webm" });+ for (const { wavBytes, expectedType } of [+ { wavBytes: 60, expectedType: "audio/wav" },+ { wavBytes: 25 * 1024 * 1024, expectedType: "audio/wav" },+ { wavBytes: 25 * 1024 * 1024 + 2, expectedType: "audio/webm" },+ ]) {+ await t.test(`${wavBytes} byte WAV uploads as ${expectedType}`, async (t) => {+ const manager = await loadCustomManager(t, async () => decodedAudio((wavBytes - 44) / 2));+ let uploadedPart;+ t.mock.method(globalThis, "fetch", async (_url, init) => {+ uploadedPart = init.body.get("file");+ return new Response(JSON.stringify({ text: "transcribed" }), { status: 200 });+ });++ const result = await manager.processWithOpenAIAPI(originalAudio);++ assert.equal(result.text, "transcribed");+ assert.equal(uploadedPart.type, expectedType);+ assert.equal(uploadedPart.name, expectedType === "audio/wav" ? "audio.wav" : "audio.webm");+ if (expectedType === "audio/webm") {+ assert.deepEqual(await uploadedPart.arrayBuffer(), await originalAudio.arrayBuffer());+ } else {+ assert.equal(uploadedPart.size, wavBytes);+ assert.equal(await uploadedPart.slice(0, 4).text(), "RIFF");+ }+ });+ }+});++for (const conversionFails of [false, true]) {+ test(`cancelled conversion cannot upload or replace a newer request (${conversionFails ? "failure" : "success"})`, async (t) => {+ const conversionStarted = deferred();+ const finishConversion = deferred();+ let decodeCalls = 0;+ const manager = await loadCustomManager(t, async () => {+ if (++decodeCalls === 1) {+ conversionStarted.resolve();+ await finishConversion.promise;+ if (conversionFails) throw new Error("Cannot decode recording");+ }+ return decodedAudio();+ });+ const requestStarted = deferred();+ const requests = [];+ t.mock.method(globalThis, "fetch", async (_url, init) => {+ requests.push(init);+ requestStarted.resolve();+ if (requests.length > 1) {+ return new Response(JSON.stringify({ text: "cancelled recording" }), { status: 200 });+ }+ return new Promise((_resolve, reject) => {+ init.signal.addEventListener("abort", () =>+ reject(new DOMException("Cancelled", "AbortError"))+ );+ });+ });+ const firstRun = manager.processAudio(new Blob(["first"], { type: "audio/webm" }));+ await conversionStarted.promise;+ assert.equal(manager.cancelProcessing(), true);+ manager.isProcessing = true;+ const secondRun = manager.processAudio(new Blob(["second"], { type: "audio/webm" }));+ await requestStarted.promise;+ const secondController = manager._activeTranscriptionAbortController;++ finishConversion.resolve();+ await firstRun;+ const requestCount = requests.length;+ const currentController = manager._activeTranscriptionAbortController;+ manager.cancelProcessing();+ const secondRequestAborted = requests[0].signal.aborted;+ secondController.abort();+ await Promise.all([firstRun, secondRun]);++ assert.equal(requestCount, 1, "cancelled audio must not be uploaded");+ assert.equal(+ currentController,+ secondController,+ "the newer request must retain cancellation ownership"+ );+ assert.equal(secondRequestAborted, true);+ });+}diff --git a/test/helpers/retryTranscriptionHandler.test.js b/test/helpers/retryTranscriptionHandler.test.jsindex 2bb5d7b53..57338f764 100644--- a/test/helpers/retryTranscriptionHandler.test.js+++ b/test/helpers/retryTranscriptionHandler.test.js@@ -56,6 +56,20 @@ const electronStub = {MessageChannelMain: class {},};+// A 44-byte RIFF header is enough for isWavFormat, which only sniffs the magic.+const WAV_BUFFER = Buffer.concat([+ Buffer.from("RIFF"),+ Buffer.alloc(4),+ Buffer.from("WAVE"),+ Buffer.alloc(32),+]);+const CONVERTED_WAV = Buffer.concat([WAV_BUFFER, Buffer.from("converted")]);++// Conversion is mocked rather than run: spawning ffmpeg from a unit test would+// make it slow and dependent on the runner having a usable binary.+const wavConversions = [];+let convertBehavior = async () => CONVERTED_WAV;+const cortiCalls = [];const tinfoilCalls = [];let cortiBehavior = async () => ({ text: "corti text" });@@ -85,6 +99,16 @@ Module._load = function loadWithMocks(request, parent, isMain) {if (request === "./windowBroadcast") {return { broadcastToWindows: () => {} };}+ if (request === "./ffmpegUtils") {+ const real = originalLoad.call(this, request, parent, isMain);+ return {+ ...real,+ convertBufferToWav: async (buffer, options) => {+ wavConversions.push(buffer);+ return convertBehavior(buffer, options);+ },+ };+ }}return originalLoad.call(this, request, parent, isMain);};@@ -103,10 +127,16 @@ function anything() {}function buildFakeThis() {- const dbRows = new Map([[7, { id: 7, audio_duration_ms: 1200 }]]);+ const dbRows = new Map([+ [7, { id: 7, audio_duration_ms: 1200 }],+ [8, { id: 8, audio_duration_ms: 1200 }],+ ]);const target = {sessionId: "test-session",- audioStorageManager: { getAudioBuffer: (id) => (id === 7 ? Buffer.from([1, 2, 3]) : null) },+ audioStorageManager: {+ // 7 is a stored WebM recording, 8 one already in WAV.+ getAudioBuffer: (id) => (id === 7 ? Buffer.from([1, 2, 3]) : id === 8 ? WAV_BUFFER : null),+ },databaseManager: {updateTranscriptionText: () => {},updateTranscriptionStatus: () => {},@@ -224,6 +254,101 @@ test("retry: plain custom endpoints use Bearer auth at the configured URL", asynassert.equal(fetches[0].init.headers.Authorization, "Bearer ck-custom");});+const CUSTOM_SETTINGS = {+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cloudTranscriptionBaseUrl: "https://stt.parasail.example.com/v1",+ cloudTranscriptionModel: "parasail-model",+};++const uploadedPart = () => fetches[0].init.body.get("file");++test("retry: a stored WebM is re-encoded before reaching a custom endpoint", async () => {+ // Without this the renderer-side fix covers fresh dictations only, and every+ // retry of a recording that failed for the container reason fails again.+ fetches.length = 0;+ wavConversions.length = 0;++ const result = await invoke(CUSTOM_SETTINGS);++ assert.equal(result.success, true);+ assert.equal(wavConversions.length, 1, "the stored container must be converted");+ const part = uploadedPart();+ assert.equal(part.name, "audio.wav");+ assert.equal(part.type, "audio/wav");+ assert.equal(part.size, CONVERTED_WAV.length, "the converted bytes are what gets uploaded");+});++test("retry: audio already in WAV is uploaded untouched", async () => {+ fetches.length = 0;+ wavConversions.length = 0;++ const result = await invoke(CUSTOM_SETTINGS, 8);++ assert.equal(result.success, true);+ assert.equal(wavConversions.length, 0, "re-encoding WAV would only cost time");+ assert.equal(uploadedPart().size, WAV_BUFFER.length);+});++test("retry: WAV expansion preserves uploads that fit the provider limit", async (t) => {+ for (const wavSize of [25 * 1024 * 1024, 25 * 1024 * 1024 + 1]) {+ await t.test(`${wavSize} converted bytes`, async () => {+ fetches.length = 0;+ const converted = Buffer.alloc(wavSize);+ WAV_BUFFER.copy(converted);+ convertBehavior = async () => converted;+ try {+ const result = await invoke(CUSTOM_SETTINGS);+ assert.equal(result.success, true);+ const part = uploadedPart();+ const fits = wavSize === 25 * 1024 * 1024;+ assert.equal(part.type, fits ? "audio/wav" : "audio/webm");+ assert.equal(part.name, fits ? "audio.wav" : "audio.webm");+ assert.deepEqual(+ Buffer.from(await part.arrayBuffer()),+ fits ? converted : Buffer.from([1, 2, 3])+ );+ } finally {+ convertBehavior = async () => CONVERTED_WAV;+ }+ });+ }+});++test("retry: built-in providers keep sending the stored container", async () => {+ fetches.length = 0;+ wavConversions.length = 0;++ await invoke({+ cloudTranscriptionProvider: "openai",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cloudTranscriptionModel: "whisper-1",+ });++ assert.equal(wavConversions.length, 0, "only custom endpoints need the re-encode");+ assert.equal(uploadedPart().name, "audio.webm");+});++test("retry: a conversion failure falls open to the stored container", async () => {+ fetches.length = 0;+ wavConversions.length = 0;+ convertBehavior = async () => {+ throw new Error("ffmpeg missing");+ };++ try {+ const result = await invoke(CUSTOM_SETTINGS);+ assert.equal(result.success, true, "a failed re-encode must not fail the retry");+ const part = uploadedPart();+ assert.equal(part.name, "audio.webm");+ assert.equal(part.type, "audio/webm");+ } finally {+ convertBehavior = async () => CONVERTED_WAV;+ }+});+test("retry: a custom URL on Tinfoil's host is refused in the main process", async () => {fetches.length = 0;const result = await invoke({diff --git a/test/utils/audioContainer.test.js b/test/utils/audioContainer.test.jsnew file mode 100644index 000000000..6b491492c--- /dev/null+++ b/test/utils/audioContainer.test.js@@ -0,0 +1,112 @@+const test = require("node:test");+const assert = require("node:assert/strict");++// The .ts import is stripped by tsx, which `npm test` loads via --import.++const load = () => import("../../src/utils/audioContainer.ts");++const readAscii = (view, offset, length) =>+ Array.from({ length }, (_, i) => String.fromCharCode(view.getUint8(offset + i))).join("");++test("only the custom provider re-encodes, and only for containers a WAV/MP3/FLAC backend refuses", async () => {+ const { needsWavConversion } = await load();++ assert.equal(needsWavConversion("custom", "audio/webm;codecs=opus"), true);+ assert.equal(needsWavConversion("custom", "audio/ogg"), true);++ // Allowlisted rather than blocklisted: MediaRecorder emits MP4/AAC on some+ // platforms, and AAC is no more acceptable to these backends than Opus.+ assert.equal(needsWavConversion("custom", "audio/mp4"), true);+ assert.equal(needsWavConversion("custom", "video/webm"), true);++ // Already acceptable — re-encoding would only cost bytes.+ assert.equal(needsWavConversion("custom", "audio/wav"), false);+ assert.equal(needsWavConversion("custom", "audio/x-wav"), false);+ assert.equal(needsWavConversion("custom", "audio/mpeg"), false);+ assert.equal(needsWavConversion("custom", "audio/flac"), false);++ // Built-in providers accept Opus today; leaving them alone keeps uploads small.+ for (const provider of ["openai", "groq", "mistral", "xai", "gemini", "corti", "tinfoil"]) {+ assert.equal(needsWavConversion(provider, "audio/webm"), false);+ }++ // Missing type must not trigger a pointless decode.+ assert.equal(needsWavConversion("custom", undefined), false);+ assert.equal(needsWavConversion("custom", ""), false);++ // An empty recording has nothing to decode; attempting it would only log a+ // misleading "re-encode failed" warning.+ assert.equal(needsWavConversion("custom", "audio/webm", 0), false);+ assert.equal(needsWavConversion("custom", "audio/webm", 1024), true);+});++test("downmixToMono averages channels and passes mono through untouched", async () => {+ const { downmixToMono } = await load();++ const mono = new Float32Array([0.25, -0.5]);+ assert.equal(downmixToMono([mono]), mono, "mono input is returned as-is, not copied");++ const mixed = downmixToMono([new Float32Array([1, -1]), new Float32Array([0, 1])]);+ assert.deepEqual(Array.from(mixed), [0.5, 0]);++ assert.throws(() => downmixToMono([]), /at least one channel/);+});++test("encodeWav writes a RIFF header the upstream decoder can read", async () => {+ const { encodeWav } = await load();++ const frames = 8;+ const buffer = encodeWav([new Float32Array(frames)], 48000);+ const view = new DataView(buffer);++ assert.equal(readAscii(view, 0, 4), "RIFF");+ assert.equal(readAscii(view, 8, 4), "WAVE");+ assert.equal(readAscii(view, 12, 4), "fmt ");+ assert.equal(readAscii(view, 36, 4), "data");++ assert.equal(view.getUint16(20, true), 1, "PCM format tag");+ assert.equal(view.getUint16(22, true), 1, "channel count");+ assert.equal(view.getUint32(24, true), 48000, "sample rate");+ assert.equal(view.getUint32(28, true), 48000 * 2, "byte rate");+ assert.equal(view.getUint16(32, true), 2, "block align");+ assert.equal(view.getUint16(34, true), 16, "bits per sample");++ const dataBytes = frames * 2;+ assert.equal(view.getUint32(40, true), dataBytes, "data chunk size");+ assert.equal(view.getUint32(4, true), 36 + dataBytes, "riff size");+ assert.equal(buffer.byteLength, 44 + dataBytes);+});++test("samples outside [-1, 1] clamp to the rails instead of wrapping", async () => {+ const { encodeWav } = await load();++ // decodeAudioData can return values slightly past full scale; a naive+ // multiply-and-truncate turns +1.2 into a large negative sample.+ const view = new DataView(encodeWav([new Float32Array([1.2, -1.2, 1, -1, 0])], 16000));++ assert.equal(view.getInt16(44, true), 32767);+ assert.equal(view.getInt16(46, true), -32768);+ assert.equal(view.getInt16(48, true), 32767);+ assert.equal(view.getInt16(50, true), -32768);+ assert.equal(view.getInt16(52, true), 0);+});++test("multi-channel audio is interleaved per frame", async () => {+ const { encodeWav } = await load();++ const left = new Float32Array([1, 0]);+ const right = new Float32Array([0, -1]);+ const view = new DataView(encodeWav([left, right], 44100));++ assert.equal(view.getUint16(22, true), 2, "channel count");+ assert.equal(view.getUint32(28, true), 44100 * 2 * 2, "byte rate");+ assert.equal(view.getInt16(44, true), 32767, "frame 0 left");+ assert.equal(view.getInt16(46, true), 0, "frame 0 right");+ assert.equal(view.getInt16(48, true), 0, "frame 1 left");+ assert.equal(view.getInt16(50, true), -32768, "frame 1 right");+});++test("encodeWav refuses an empty channel list rather than emitting a headerless file", async () => {+ const { encodeWav } = await load();+ assert.throws(() => encodeWav([], 16000), /at least one channel/);+});