// deck-it - WAV for the assistant's voice questions // Copyright (C) 2026 Danilo M. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // The daemon takes a WAV (desktop-assistant checks its header and length), // and MediaRecorder gives webm/opus, so the clip is decoded, resampled to // 16 kHz mono and written as 16-bit PCM here. export function encodeWav(samples, rate) { const buf = new ArrayBuffer(44 + samples.length * 2); const v = new DataView(buf); const tag = (o, s) => { for (let i = 0; i < 4; i++) v.setUint8(o + i, s.charCodeAt(i)); }; tag(0, "RIFF"); v.setUint32(4, 36 + samples.length * 2, true); tag(8, "WAVE"); tag(12, "fmt "); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true); v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); tag(36, "data"); v.setUint32(40, samples.length * 2, true); for (let i = 0; i < samples.length; i++) { const s = Math.max(-1, Math.min(1, samples[i])); v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true); } return buf; } // The loudest sample of a 16-bit WAV from encodeWav, to tell silence. export function peak(wav) { const v = new DataView(wav); let p = 0; for (let i = 44; i + 1 < wav.byteLength; i += 2) p = Math.max(p, Math.abs(v.getInt16(i, true))); return p; } export async function toWav(blob, rate = 16000) { const ctx = new AudioContext(); try { const decoded = await ctx.decodeAudioData(await blob.arrayBuffer()); const off = new OfflineAudioContext(1, Math.ceil(decoded.duration * rate), rate); const src = off.createBufferSource(); src.buffer = decoded; src.connect(off.destination); src.start(); return encodeWav((await off.startRendering()).getChannelData(0), rate); } finally { ctx.close(); } }