UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

69 lines (68 loc) • 2.25 kB
import { i as mulawToPcm } from "./output-activity-tracker-B0aXImJ4.mjs"; //#region src/talk/audio-energy.ts const PCM16_MAX_AMPLITUDE = 32768; const MULAW_LINEAR_SAMPLES = (() => { const e = Buffer.from([...Array(256).keys()]); const t = mulawToPcm(e); return Int16Array.from(e, (e, n) => t.readInt16LE(n * 2)); })(); /** Ignore decoded transport silence below -66 dBFS while retaining quiet speech. */ function isRealtimeVoiceAudioAudible(e, t) { const n = 16; if (t.encoding === "g711_ulaw") return e.some((e) => Math.abs(MULAW_LINEAR_SAMPLES[e] ?? 0) >= n); for (let t = 0; t + 1 < e.byteLength; t += 2) if (Math.abs(e.readInt16LE(t)) >= n) return true; return false; } /** Read RMS and absolute peak from complete little-endian signed PCM16 samples. */ function readPcm16AudioStats(e) { let t = 0; let n = 0; const r = Math.floor(e.byteLength / 2); for (let i = 0; i < r; i += 1) { const r = e.readInt16LE(i * 2); n = Math.max(n, Math.abs(r)); t += r * r; } return { rms: r > 0 ? Math.sqrt(t / r) : 0, peak: n }; } /** Calculate normalized RMS from G.711 mu-law bytes. */ function calculateMulawRms(e) { if (e.length === 0) return 0; let t = 0; for (const n of e) { const e = (MULAW_LINEAR_SAMPLES[n] ?? 0) / PCM16_MAX_AMPLITUDE; t += e * e; } return Math.sqrt(t / e.length); } /** Build an OR-threshold gate with optional sustained onset, silence hold, and cooldown. */ function createSpeechThresholdGate(e) { const t = Math.max(1, Math.floor(e.speechFrames ?? 1)); const n = Math.max(0, Math.floor(e.silenceFrames ?? 0)); const r = Math.max(0, e.cooldownMs ?? 0); let i = 0; let a = 0; let o = false; let s = Number.NEGATIVE_INFINITY; return { accept(c, l = {}) { if (!(e.rmsThreshold !== void 0 && c.rms >= e.rmsThreshold || e.peakThreshold !== void 0 && c.peak >= e.peakThreshold)) { i = 0; if (o && ++a >= n) o = false; return false; } a = 0; i += 1; if (o || i < t) return false; const u = l.nowMs ?? Date.now(); if (u - s < r || l.onTrigger?.() === false) return false; s = u; o = n > 0; if (!o) i = 0; return true; } }; } //#endregion export { readPcm16AudioStats as i, createSpeechThresholdGate as n, isRealtimeVoiceAudioAudible as r, calculateMulawRms as t };