Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.
TypeScript ai-meeting-assistantai-notetakerelectrongranola-alternativelinuxllama-cpplocal-ailocal-firstmacosmcpmeeting-minutesmeeting-notesoffline-firstopen-sourceprivacyspeech-to-texttranscriptionwhisperwhisper-cppwindows
Mic echo: cancel the other side's voice on the mic before transcription (#148)
Christian Mathiesenc26e9d5b13ef
diff --git a/app/electron-builder.yml b/app/electron-builder.ymlindex 31ce0f66..9f3cd323 100644--- a/app/electron-builder.yml+++ b/app/electron-builder.yml@@ -29,7 +29,7 @@ extraResources:# the Mac's menu bar icon (tray.ts reads it from Resources; @2x is picked up next to it)- { from: resources, to: ., filter: ["tray.png", "[email protected]", "tray-titled.png", "[email protected]"] }# licenses of things bundled or downloaded: fonts, whisper.cpp, Silero VAD, libopus, the native recorders' crates,- # whisper-server's headers, animate-ui and the CUDA runtime+ # whisper-server's headers, animate-ui, the CUDA runtime and the echo canceller (webrtcaec3.js)- from: resources/licensesto: licenses# the Mac's About window shows Resources/Credits.html under the version, with its linkdiff --git a/app/package.json b/app/package.jsonindex 4fcbecde..c746ca18 100644--- a/app/package.json+++ b/app/package.json@@ -13,6 +13,7 @@"typecheck": "tsc -p ."},"dependencies": {+ "@ennuicastr/webrtcaec3.js": "0.3.0","bonjour-service": "1.4.4","chrono-node": "2.10.3","electron-updater": "6.8.10",diff --git a/app/resources/licenses/webrtcaec3.js-BSD-Apache.txt b/app/resources/licenses/webrtcaec3.js-BSD-Apache.txtnew file mode 100644index 00000000..a134b432--- /dev/null+++ b/app/resources/licenses/webrtcaec3.js-BSD-Apache.txt@@ -0,0 +1,107 @@+webrtcaec3.js 0.3.0 (https://github.com/ennuicastr/webrtcaec3.js, npm @ennuicastr/webrtcaec3.js)+WebRTC's echo canceller (AEC3) built for WebAssembly; it takes the other side's voice off the mic before transcription.+It carries the licences of WebRTC (BSD-3-Clause), abseil-cpp (Apache-2.0), Emscripten and musl (MIT), below as shipped.+++This software is compiled from several sources, the licenses for which are+included herein.++---++WebRTC:++Copyright (c) 2011-2022 The WebRTC project authors. All Rights Reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.++ * Neither the name of Google nor the names of its contributors may be used+ to endorse or promote products derived from this software without+ specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+POSSIBILITY OF SUCH DAMAGE.+++Additional IP Rights Grant (Patents)++"This implementation" means the copyrightable works distributed by Google as+part of the WebRTC code package.++Google hereby grants to you a perpetual, worldwide, non-exclusive,+no-charge, irrevocable (except as stated in this section) patent license to+make, have made, use, offer to sell, sell, import, transfer, and otherwise+run, modify and propagate the contents of this implementation of the WebRTC+code package, where such license applies only to those patent claims, both+currently owned by Google and acquired in the future, licensable by Google+that are necessarily infringed by this implementation of the WebRTC code+package. This grant does not include claims that would be infringed only as+a consequence of further modification of this implementation. If you or your+agent or exclusive licensee institute or order or agree to the institution+of patent litigation against any entity (including a cross-claim or+counterclaim in a lawsuit) alleging that this implementation of the WebRTC+code package or any code incorporated within this implementation of the+WebRTC code package constitutes direct or contributory patent infringement,+or inducement of patent infringement, then any patent rights granted to you+under this License for this implementation of the WebRTC code package shall+terminate as of the date such litigation is filed.++---++abseil-cpp:++Copyright 2017-2023 The Abseil Authors.++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++ https://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.++---++emscripten and musl:++Copyright (c) 2010-2023 Emscripten authors, see AUTHORS file.+Copyright © 2005-2023 Rich Felker, et al.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to+deal in the Software without restriction, including without limitation the+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or+sell copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS+IN THE SOFTWARE.+diff --git a/app/src/main/asr/aec.ts b/app/src/main/asr/aec.tsnew file mode 100644index 00000000..53a8b4e6--- /dev/null+++ b/app/src/main/asr/aec.ts@@ -0,0 +1,130 @@+import type { Track } from '../capture'++/**+ * Without headphones the mic hears the other side from the speakers. Their voice is on the computer's own track too,+ * clean, so an echo canceller (asr/aec3.ts) can take it off the mic before whisper reads it: it learns how the room+ * changes their voice on the way to the mic (late, duller, quieter) and takes that copy away, frame by frame, leaving+ * the person's own voice. echo.ts's word check stays behind it for what gets through.+ *+ * This lines the two tracks up on meeting time: their audio goes on at once and is kept as the reference; the mic waits+ * until their track has reached the same time, then each 10 ms mic frame goes in with their frame from the same moment+ * (the canceller finds the room's own delay itself). Only the copy for transcription is cancelled; the saved files stay+ * as recorded.+ */+export const FRAME = 160+const FRAME_MS = 10++/** One echo canceller for one meeting: 10 ms frames at 16 kHz (FRAME samples) */+export interface Canceller {+ /** what the speakers played (their track) */+ analyze(ref: Float32Array): void+ /** the mic's frame with the echo taken out, into out */+ process(mic: Float32Array, out: Float32Array): void+ free(): void+}++/** the mic is held at most this far behind its newest audio for their track to arrive; past it their track is taken as silent */+const MAX_WAIT_MS = 1500+/** their audio is kept this long behind its newest, for a mic that arrives late (with no mic at all it would pile up) */+const KEEP_REF_MS = 5000+/**+ * Their side silent this long (under -70 dB, a call's digital silence): no echo is left in the room, so the mic goes+ * through untouched and the canceller is not run, which saves its work while only the person talks+ */+const SILENT_FRAMES = 100+const SILENT = 1e-7+/** a mic piece starting this far from where the last ended is a new run (a pause, a restart) */+const GAP_MS = 1++export function createEchoCancel(p: {+ /** a canceller, or null while there is none (not loaded): the mic then goes through as it is */+ make: () => Canceller | null+ out: (track: Track, ms: number, samples: Float32Array) => void+ maxWaitMs?: number+}) {+ const maxWait = p.maxWaitMs ?? MAX_WAIT_MS+ let canceller: Canceller | null = null+ /** closed: anything later goes through as it is */+ let closed = false+ /** their audio not yet used as reference, on meeting time */+ let ref: Array<{ ms: number; samples: Float32Array }> = []+ let themEnd = -Infinity+ /** mic audio waiting: one run, back to back from ms */+ let mic: { ms: number; samples: Float32Array } | null = null+ /** their frames in a row that were silent */+ let silentFor = 0+ const refFrame = new Float32Array(FRAME)+ const outFrame = new Float32Array(FRAME)++ /** their audio over [ms, ms + 10 ms); silence where there is none */+ const fillRef = (ms: number) => {+ refFrame.fill(0)+ for (const r of ref) {+ const rEnd = r.ms + r.samples.length / 16+ if (rEnd <= ms || r.ms >= ms + FRAME_MS) continue+ const from = Math.round((ms - r.ms) * 16)+ for (let i = Math.max(0, -from); i < FRAME && from + i < r.samples.length; i++) refFrame[i] = r.samples[from + i]+ }+ }++ /** the waiting mic's whole frames up to meeting time `until` go through the canceller; the rest waits (all, when final) */+ const run = (until: number, final = false) => {+ if (!mic) return+ if (!canceller && !closed) canceller = p.make()+ const frames = Math.max(0, Math.floor(Math.min(mic.samples.length / FRAME, (until - mic.ms) / FRAME_MS)))+ const n = frames * FRAME+ if (n) {+ const done = new Float32Array(n)+ if (canceller) {+ for (let f = 0; f < frames; f++) {+ const frame = mic.samples.subarray(f * FRAME, (f + 1) * FRAME)+ fillRef(mic.ms + f * FRAME_MS)+ let e = 0+ for (let i = 0; i < FRAME; i++) e += refFrame[i] * refFrame[i]+ silentFor = e / FRAME < SILENT ? silentFor + 1 : 0+ if (silentFor >= SILENT_FRAMES) { done.set(frame, f * FRAME); continue }+ canceller.analyze(refFrame)+ canceller.process(frame, outFrame)+ done.set(outFrame, f * FRAME)+ }+ } else done.set(mic.samples.subarray(0, n))+ p.out('me', mic.ms, done)+ mic = { ms: mic.ms + frames * FRAME_MS, samples: mic.samples.subarray(n) }+ // their audio before the mic's position is not needed again+ ref = ref.filter((r) => r.ms + r.samples.length / 16 > mic!.ms)+ }+ if (final && mic.samples.length) { p.out('me', mic.ms, mic.samples.slice()); mic = null }+ if (mic && !mic.samples.length) mic = null+ }++ const drain = () => {+ if (!mic) return+ const micEnd = mic.ms + mic.samples.length / 16+ run(Math.max(themEnd, micEnd - maxWait))+ }++ return {+ push(track: Track, ms: number, samples: Float32Array) {+ if (!samples.length) return+ if (track === 'them') {+ p.out('them', ms, samples)+ ref.push({ ms, samples })+ themEnd = Math.max(themEnd, ms + samples.length / 16)+ while (ref.length && ref[0].ms + ref[0].samples.length / 16 < themEnd - KEEP_REF_MS) ref.shift()+ drain()+ return+ }+ // nothing of theirs heard yet (a mic-only recording, or the first moment), or no canceller (yet): nothing to wait for+ if (!canceller && !closed && themEnd > -Infinity) canceller = p.make()+ if (!canceller) { if (mic) run(Infinity, true); p.out('me', ms, samples); return }+ if (mic && Math.abs(ms - (mic.ms + mic.samples.length / 16)) > GAP_MS) run(Infinity, true)+ if (!mic) mic = { ms, samples: samples.slice() }+ else { const all = new Float32Array(mic.samples.length + samples.length); all.set(mic.samples); all.set(samples, mic.samples.length); mic = { ms: mic.ms, samples: all } }+ drain()+ },+ /** the meeting is over: all the mic audio waiting goes through now */+ flush() { run(Infinity, true) },+ close() { this.flush(); closed = true; canceller?.free(); canceller = null; ref = [] },+ }+}+export type EchoCancel = ReturnType<typeof createEchoCancel>diff --git a/app/src/main/asr/aec3.ts b/app/src/main/asr/aec3.tsnew file mode 100644index 00000000..9e0ff03f--- /dev/null+++ b/app/src/main/asr/aec3.ts@@ -0,0 +1,29 @@+import WebRtcAec3 from '@ennuicastr/webrtcaec3.js'+import { FRAME, type Canceller } from './aec'++/**+ * WebRTC's echo canceller (AEC3, the one Chrome, PulseAudio and PipeWire use), built for WebAssembly+ * (@ennuicastr/webrtcaec3.js, BSD; pinned in package.json, checked by the lockfile's hash). It runs inside Yogurt the+ * same way on Mac, Windows and Linux, on the 16 kHz audio going to whisper: about 2% of one core.+ * Loaded once (a few tens of ms); until then, or if it can't load, the mic goes to whisper as it is.+ */+let mod: WebRtcAec3.WebRtcAec3 | null = null+let loading: Promise<void> | undefined++export function loadAec3(): Promise<void> {+ loading ??= WebRtcAec3().then((m) => { mod = m }, (e) => { console.error('ASR the echo canceller could not load: the mic is transcribed as it is', e) })+ return loading+}++/** a canceller for one meeting, or null before it has loaded */+export function aec3(): Canceller | null {+ if (!mod) return null+ // 16 kHz, whisper's rate: AEC3 works at it directly (one band), as well as at 32 or 48 kHz on this audio and cheaper+ const a = new mod.AEC3(16000, 1, 1)+ const ref = [new Float32Array(FRAME)], mic = [new Float32Array(FRAME)], out = [new Float32Array(FRAME)]+ return {+ analyze: (x) => { ref[0].set(x); a.analyze(ref) },+ process: (x, o) => { mic[0].set(x); a.process(out, mic); o.set(out[0]) },+ free: () => a.free(),+ }+}diff --git a/app/src/main/asr/index.ts b/app/src/main/asr/index.tsindex 4a095ac4..6679ed9a 100644--- a/app/src/main/asr/index.ts+++ b/app/src/main/asr/index.ts@@ -6,6 +6,7 @@ import { isFake } from '../paths'import { feedRecording } from './backfill'import type { Meeting, Segment, Store } from '../store'import { createPipeline, type Pipeline } from './pipeline'+import { loadAec3 } from './aec3'import { echoConfidence } from './echo'import { appleSpeechAvailable, installSpeechLocale, readSpeechLocales, speechDisagrees, speechFits, wantedSpeechLocale, type SpeechHost, type SpeechLocales } from './appleSpeech'import { whisperLanguage, type Spoken } from '../../shared/spoken'@@ -193,6 +194,8 @@ export function hookTranscription(p: {queued?: (meetingId: string) => void}): () => void {idleMs = p.serverIdleMs ?? SERVER_IDLE_MS+ // the echo canceller is ready long before the first meeting: the mic's copy of their voice goes before whisper reads it+ void loadAec3()queuedListener = p.queuedspokenNow = p.spoken ?? (() => 'en')if (p.speech && appleSpeechAvailable(p.speech.host)) {diff --git a/app/src/main/asr/pipeline.ts b/app/src/main/asr/pipeline.tsindex f5543f0e..40b543d8 100644--- a/app/src/main/asr/pipeline.ts+++ b/app/src/main/asr/pipeline.ts@@ -5,6 +5,8 @@ import { afterFinal, joinWords, replaceWords, wordsOf, type Heard, type LiveWordimport { chunker, type Chunk } from './chunker'import { echoConfidence, isVerbatimCopy, type EchoCheck } from './echo'import { EchoDetector } from './echoDetect'+import { createEchoCancel, type Canceller } from './aec'+import { aec3 } from './aec3'import type { Line, Transcribe } from './transcribe'type Out = Omit<Segment, 'id'>@@ -38,6 +40,8 @@ export function createPipeline(p: {nameOf?: (startMs: number, endMs: number) => string | null/** the meeting's spellings of names and companies (vocab.ts respell) */respell?: (text: string) => string+ /** the echo canceller for the mic (asr/aec3.ts); null: none (the mic goes to whisper as it is) */+ cancelEcho?: () => Canceller | null}) {const hold = p.holdMs ?? 2000const extraWait = p.extraWaitMs ?? EXTRA_WAIT_MS@@ -194,6 +198,8 @@ export function createPipeline(p: {.finally(() => { lastPartialMs = Date.now() - t0; running[t] = false; pump(t) })}const cut = chunker(queue, p.emitPartial ? partial : undefined)+ // their voice taken off the mic before it is cut into chunks; the echo detector above hears the mic as recorded+ const aec = createEchoCancel({ make: p.cancelEcho ?? aec3, out: (track, ms, samples) => cut.push(track, ms, samples) })let finishing: Promise<void> | undefinedreturn {@@ -203,11 +209,12 @@ export function createPipeline(p: {if (closed) returnwallOffset = Date.now() - (ms + samples.length / 16)echo.push(track, ms, samples)- cut.push(track, ms, samples)+ aec.push(track, ms, samples)},/** the meeting is over: what is left is transcribed, held lines are checked and saved now */finish(): Promise<void> {finishing ??= (async () => {+ aec.close()cut.flush()await new Promise<void>((r) => { if (!queued('me') && !queued('them')) r(); else idle.push(r) })closed = truediff --git a/app/test/aec.test.ts b/app/test/aec.test.tsnew file mode 100644index 00000000..8d8d743c--- /dev/null+++ b/app/test/aec.test.ts@@ -0,0 +1,216 @@+import { beforeAll, describe, expect, it } from 'vitest'+import { createEchoCancel, FRAME, type Canceller } from '../src/main/asr/aec'+import { aec3, loadAec3 } from '../src/main/asr/aec3'+import { createPipeline } from '../src/main/asr/pipeline'+import type { Chunk } from '../src/main/asr/chunker'+import type { Track } from '../src/main/capture'++const RATE = 16000++/** a stand-in canceller: says which reference frame each mic frame was given, and takes away the reference */+function fakeCanceller() {+ const log: Array<{ ref: number; mic: number }> = []+ let lastRef = new Float32Array(FRAME)+ let freed = false+ const c: Canceller = {+ analyze: (ref) => { lastRef = ref.slice() },+ process: (mic, out) => { log.push({ ref: lastRef[0], mic: mic[0] }); for (let i = 0; i < FRAME; i++) out[i] = mic[i] - lastRef[i] },+ free: () => { freed = true },+ }+ return { c, log, freed: () => freed }+}++/** samples whose value is their meeting time in ms, so a frame says where it came from */+const timed = (ms: number, n: number) => Float32Array.from({ length: n }, (_, i) => ms + Math.floor(i / 16))++function rig(make: () => Canceller | null, maxWaitMs?: number) {+ const out: Array<{ track: Track; ms: number; samples: Float32Array }> = []+ const aec = createEchoCancel({ make, out: (track, ms, samples) => out.push({ track, ms, samples }), maxWaitMs })+ return { aec, out, mic: () => out.filter((o) => o.track === 'me'), them: () => out.filter((o) => o.track === 'them') }+}++describe('echo cancel: lining the tracks up', () => {+ it('passes their track on at once and holds the mic until their track has reached the same time', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('them', 0, timed(0, 1600))+ expect(r.them()).toHaveLength(1)+ r.aec.push('me', 0, timed(0, 1600)); r.aec.push('me', 100, timed(100, 1600))+ expect(r.mic()).toHaveLength(1)+ r.aec.push('them', 100, timed(100, 1600))+ expect(r.mic()).toHaveLength(2)+ expect(r.mic()[1].ms).toBe(100)+ expect(r.mic()[1].samples).toHaveLength(1600)+ })++ it('lets the mic straight through while nothing of theirs has been heard (a mic-only recording)', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('me', 0, timed(0, 1600))+ expect(r.mic()).toHaveLength(1)+ expect(f.log).toHaveLength(0)+ })++ it('gives each 10 ms mic frame the reference from the same meeting time', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('them', 0, timed(0, 1600)); r.aec.push('them', 100, timed(100, 1600))+ r.aec.push('me', 0, timed(0, 1600)); r.aec.push('me', 100, timed(100, 1600))+ expect(f.log).toHaveLength(20)+ expect(f.log.every((x) => x.ref === x.mic)).toBe(true)+ // the stand-in takes the reference away: the same audio on both tracks comes out as silence+ expect(r.mic().every((o) => o.samples.every((v) => v === 0))).toBe(true)+ })++ it('reads the reference as silence where their track has a hole', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('them', 0, timed(0, 1600)); r.aec.push('them', 300, timed(300, 1600))+ r.aec.push('me', 100, timed(100, 1600))+ expect(f.log.every((x) => x.ref === 0)).toBe(true)+ expect(r.mic()[0].samples[0]).toBe(100)+ })++ it('keeps only the last few seconds of their track when no mic comes', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ for (let ms = 0; ms < 10_000; ms += 100) r.aec.push('them', ms, timed(ms, 1600))+ r.aec.push('me', 9000, timed(9000, 1600))+ expect(f.log.every((x) => x.ref === x.mic)).toBe(true)+ r.aec.push('me', 0, timed(0, 1600))+ r.aec.flush()+ expect(f.log.slice(10).every((x) => x.ref === 0)).toBe(true)+ })++ it('lets the mic go on alone when their track stops coming', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c, 1000)+ r.aec.push('them', -100, timed(-100, 1600))+ for (let ms = 0; ms <= 1500; ms += 100) r.aec.push('me', ms, timed(ms, 1600))+ // held no more than about a second behind the newest mic audio+ expect(r.mic().length).toBeGreaterThanOrEqual(5)+ expect(r.mic()[0].ms).toBe(0)+ })++ it('leaves the mic untouched, without running the canceller, once their side has been silent for a second', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ for (let ms = 0; ms < 3000; ms += 100) { r.aec.push('them', ms, new Float32Array(1600)); r.aec.push('me', ms, timed(ms, 1600)) }+ // the first second still goes through it (the room's echo dies away), the rest does not+ expect(f.log).toHaveLength(99)+ expect(r.mic().at(-1)!.samples).toEqual(timed(2900, 1600))+ r.aec.push('them', 3000, timed(3000, 1600)); r.aec.push('me', 3000, timed(3000, 1600))+ expect(f.log).toHaveLength(109)+ })++ it('keeps pieces that are not whole frames, and gives out what is left at the end', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('them', 0, timed(0, 1000)); r.aec.push('me', 0, timed(0, 1000))+ r.aec.push('them', 62.5, timed(62.5, 1000)); r.aec.push('me', 62.5, timed(62.5, 1000))+ r.aec.flush()+ const n = r.mic().reduce((s, o) => s + o.samples.length, 0)+ expect(n).toBe(2000)+ // pieces come out in order and back to back+ let at = 0+ for (const o of r.mic()) { expect(o.ms).toBeCloseTo(at, 5); at += o.samples.length / 16 }+ })++ it('starts a fresh run after a pause in the mic', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('them', 0, timed(0, 1000)); r.aec.push('me', 0, timed(0, 1000))+ r.aec.push('them', 5000, timed(5000, 1600)); r.aec.push('me', 5000, timed(5000, 1600))+ r.aec.flush()+ expect(r.mic().map((o) => o.ms)).toEqual([0, 960 / 16, 5000])+ })++ it('without a canceller the mic goes straight through, not held', () => {+ const r = rig(() => null)+ r.aec.push('me', 0, timed(0, 1600))+ expect(r.mic()).toHaveLength(1)+ expect(r.mic()[0].samples).toEqual(timed(0, 1600))+ })++ it('without a canceller yet, the mic goes through until one is there', () => {+ const f = fakeCanceller()+ let ready = false+ const r = rig(() => (ready ? f.c : null))+ r.aec.push('me', 0, timed(0, 1600))+ expect(r.mic()).toHaveLength(1)+ ready = true+ r.aec.push('them', 100, timed(100, 1600))+ r.aec.push('me', 100, timed(100, 1600))+ expect(r.mic()).toHaveLength(2)+ expect(f.log).toHaveLength(10)+ })++ it('frees the canceller when it closes', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c)+ r.aec.push('them', 0, timed(0, 1600)); r.aec.push('me', 0, timed(0, 1600))+ r.aec.close()+ expect(f.freed()).toBe(true)+ })+})++/** a voice-like noise: bursts of syllables */+function talk(sec: number, seed: number, gain: number) {+ let s = seed+ const rnd = () => ((s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff) * 2 - 1+ return Float32Array.from({ length: sec * RATE }, (_, i) => gain * rnd() * Math.max(0, Math.sin((2 * Math.PI * 3 * i) / RATE)))+}+const db = (x: Float32Array, from: number, to: number) => { let e = 0; for (let i = from * RATE; i < to * RATE; i++) e += x[i] * x[i]; return 10 * Math.log10(e / ((to - from) * RATE) + 1e-12) }++describe('echo cancel: WebRTC AEC3', () => {+ beforeAll(async () => { await loadAec3() })++ it('loads', () => { expect(aec3()).not.toBeNull() })++ it('takes their voice off the mic by at least 20 dB and keeps the person speaking', () => {+ const SEC = 24+ const ref = talk(SEC, 7, 0.3)+ // the person: alone from 14 s to 17 s (their side quiet), and over them from 19 s to 22 s+ const near = new Float32Array(SEC * RATE)+ const voice = talk(3, 99, 0.08)+ near.set(voice, 14 * RATE); near.set(voice, 19 * RATE)+ for (let i = 14 * RATE; i < 17 * RATE; i++) ref[i] = 0+ // the room: 60 ms late, duller and quieter, plus a second, weaker path+ const mic = new Float32Array(SEC * RATE)+ let lp = 0+ for (let i = 0; i < mic.length; i++) {+ const x = i >= 960 ? ref[i - 960] : 0+ lp = 0.7 * lp + 0.3 * x+ mic[i] = 0.4 * lp + (i >= 1500 ? 0.1 * ref[i - 1500] : 0) + near[i]+ }+ const got = new Float32Array(mic.length)+ let at = 0+ const aec = createEchoCancel({ make: aec3, out: (track, ms, samples) => { if (track === 'me') { got.set(samples, at); at += samples.length } } })+ for (let i = 0; i < mic.length; i += 1600) { aec.push('them', i / 16, ref.subarray(i, i + 1600)); aec.push('me', i / 16, mic.subarray(i, i + 1600)) }+ aec.flush(); aec.close()+ expect(at).toBe(mic.length)+ // once it has learned the room (a few seconds), their voice alone is 20 dB quieter+ expect(db(mic, 6, 13) - db(got, 6, 13)).toBeGreaterThanOrEqual(20)+ // the person alone is untouched, and over them comes through nearly at full level+ expect(Math.abs(db(got, 14, 17) - db(near, 14, 17))).toBeLessThan(1.5)+ expect(Math.abs(db(got, 19, 22) - db(near, 19, 22))).toBeLessThan(3)+ })+})++describe('echo cancel in the pipeline', () => {+ it('transcribes the cancelled mic, their track as it is, and gives out held mic audio when the meeting ends', async () => {+ const heard: Chunk[] = []+ // a canceller that turns the mic to a quiet copy of itself+ const halve: Canceller = { analyze: () => {}, process: (mic, out) => { for (let i = 0; i < FRAME; i++) out[i] = mic[i] / 2 }, free: () => {} }+ const p = createPipeline({ meetingId: 'm1', holdMs: 10, transcribe: async (c) => { heard.push(c); return [] }, save: () => {}, emit: () => {}, cancelEcho: () => halve })+ const tone = Float32Array.from({ length: RATE }, (_, i) => 0.3 * Math.sin(i / 10))+ const all = Float32Array.from([...tone, ...new Float32Array(RATE * 1.5)])+ for (let i = 0; i < all.length; i += 1600) { p.push('them', i / 16, all.subarray(i, i + 1600)); p.push('me', i / 16, all.subarray(i, i + 1600)) }+ // the mic's last piece is held until their track catches up; the end of the meeting lets it go+ p.push('me', all.length / 16, tone.subarray(0, 1600))+ await p.finish()+ const peak = (t: Track) => Math.max(...heard.filter((c) => c.track === t).flatMap((c) => [...c.samples]))+ expect(peak('them')).toBeCloseTo(0.3, 2)+ expect(peak('me')).toBeCloseTo(0.15, 2)+ })+})diff --git a/app/test/transcription.test.ts b/app/test/transcription.test.tsindex 8444df6a..17d261b8 100644--- a/app/test/transcription.test.ts+++ b/app/test/transcription.test.ts@@ -10,6 +10,10 @@ import { openStore, type Meeting, type Store } from '../src/main/store'import type { Line } from '../src/main/asr/transcribe'import type { Chunk } from '../src/main/asr/chunker'+// these tests are about the session around the pipeline; the echo canceller is tested on its own (aec.test.ts), and its+// work on minutes of test audio would only make them slow on CI+vi.mock('../src/main/asr/aec3', () => ({ loadAec3: async () => {}, aec3: () => null }))+const RATE = 16000const tone = (sec: number) => Float32Array.from({ length: Math.round(sec * RATE) }, (_, i) => 0.3 * Math.sin(i / 10))const tick = () => new Promise((r) => setTimeout(r, 15))diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dee48da8..d1e73d4c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -15,6 +15,9 @@ importers:app:dependencies:+ '@ennuicastr/webrtcaec3.js':+ specifier: 0.3.0+ version: 0.3.0bonjour-service:specifier: 1.4.4version: 1.4.4@@ -335,6 +338,9 @@ packages:engines: {node: '>=14.14'}hasBin: true+ '@ennuicastr/[email protected]':+ resolution: {integrity: sha512-ZfijX3Pzqr2zY2nTBE+APGB4X8q3up5vqQgmuolCvC2WTYYWvivf3GGVFZnTr6n/kZa9w3Y5P4ugwcrOmsqXZQ==}+'@esbuild/[email protected]':resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}engines: {node: '>=18'}@@ -3083,6 +3089,8 @@ snapshots:- supports-coloroptional: true+ '@ennuicastr/[email protected]': {}+'@esbuild/[email protected]':optional: true