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
Find and hide the mic's echo when its track sits up to 2 s behind the call audio, and hold the echo canceller's reference back to match (#181)
christianmatdf49dbd74c28
diff --git a/app/src/main/asr/aec.ts b/app/src/main/asr/aec.tsindex cc3c79e9..c0cc3849 100644--- a/app/src/main/asr/aec.ts+++ b/app/src/main/asr/aec.ts@@ -33,6 +33,16 @@ const KEEP_REF_MS = 5000*/const SILENT_FRAMES = 100const SILENT = 1e-7+/**+ * AEC3 finds the room's delay itself, but only out to about half a second. With the mic track a steady way behind+ * theirs (asr/echoDetect.ts offsetMs, #181), their audio is held back by the offset less this much, so what is left for+ * AEC3 to find is short and their audio still arrives before its copy on the mic. Changed only by a real move: AEC3+ * starts its search again each time.+ */+const LEAD_MS = 100+/** as far as the echo detector looks */+const MAX_DELAY_MS = 2000+const MOVE_MS = 50/** a mic piece starting this far from where the last ended is a new run (a pause, a restart) */const GAP_MS = 1@@ -41,6 +51,8 @@ export function createEchoCancel(p: {make: () => Canceller | nullout: (track: Track, ms: number, samples: Float32Array) => voidmaxWaitMs?: number+ /** how far the mic track sits behind theirs, once the echo detector knows (past the room's own lags) */+ offsetMs?: () => number | undefined}) {const maxWait = p.maxWaitMs ?? MAX_WAIT_MSlet canceller: Canceller | null = null@@ -53,6 +65,13 @@ export function createEchoCancel(p: {let mic: { ms: number; samples: Float32Array } | null = null/** their frames in a row that were silent */let silentFor = 0+ /** their audio is taken from this much before the mic's moment */+ let refDelay = 0+ const updateDelay = () => {+ const o = p.offsetMs?.()+ const want = o ? Math.max(0, Math.round((o - LEAD_MS) / FRAME_MS) * FRAME_MS) : 0+ if (Math.abs(want - refDelay) >= MOVE_MS || (want === 0) !== (refDelay === 0)) refDelay = want+ }const refFrame = new Float32Array(FRAME)const outFrame = new Float32Array(FRAME)@@ -71,6 +90,7 @@ export function createEchoCancel(p: {const run = (until: number, final = false) => {if (!mic) returnif (!canceller && !closed) canceller = p.make()+ updateDelay()const frames = Math.max(0, Math.floor(Math.min(mic.samples.length / FRAME, (until - mic.ms) / FRAME_MS)))const n = frames * FRAMEif (n) {@@ -78,7 +98,7 @@ export function createEchoCancel(p: {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)+ fillRef(mic.ms + f * FRAME_MS - refDelay)let e = 0for (let i = 0; i < FRAME; i++) e += refFrame[i] * refFrame[i]silentFor = e / FRAME < SILENT ? silentFor + 1 : 0@@ -90,8 +110,8 @@ export function createEchoCancel(p: {} 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)+ // their audio from before the mic's position, less the furthest the tracks can sit apart, is not needed again+ ref = ref.filter((r) => r.ms + r.samples.length / 16 > mic!.ms - Math.max(refDelay, MAX_DELAY_MS))}if (final && mic.samples.length) { p.out('me', mic.ms, mic.samples.slice()); mic = null }if (mic && !mic.samples.length) mic = nulldiff --git a/app/src/main/asr/echo.ts b/app/src/main/asr/echo.tsindex 433e36a0..bb51a04f 100644--- a/app/src/main/asr/echo.ts+++ b/app/src/main/asr/echo.ts@@ -29,7 +29,16 @@ export type Moment = { correlated: boolean; loud: boolean; pure: boolean }* Echo in this meeting: heard in the audio (asr/echoDetect.ts); whether the mic echoed in the 2 s window holding a* moment; and what a line's own span says (undefined before the room's lag is known)*/-export type EchoCheck = { echo?: boolean; correlatedAt?: (ms: number) => boolean; over?: (startMs: number, endMs: number) => Moment | undefined }+export type EchoCheck = {+ echo?: boolean; correlatedAt?: (ms: number) => boolean; over?: (startMs: number, endMs: number) => Moment | undefined+ /** the mic track sits this far behind theirs on meeting time (asr/echoDetect.ts offsetMs): their lines are set against the mic's that much later */+ offsetMs?: number+}++/** their lines on the mic's time: where their copy lands on it */+function onMicTime<T extends Seg>(them: T[], o: EchoCheck): T[] {+ return o.offsetMs ? them.map((s) => ({ ...s, startMs: s.startMs + o.offsetMs!, endMs: s.endMs + o.offsetMs! })) : them+}/** Words, lowercased and without punctuation. Text without spaces (Japanese, Chinese) is compared by character. */export function tokens(text: string): string[] {@@ -113,7 +122,7 @@ const always = () => true/** Pure audio spans or strong word matches can be quiet; weak matches remain reviewable. */export function echoConfidence(m: Seg, them: Seg[], o: EchoCheck = {}): false | 'high' | 'uncertain' {- return o.echo ? echoMatch(m, them, o.correlatedAt ?? always, o.over) : false+ return o.echo ? echoMatch(m, onMicTime(them, o), o.correlatedAt ?? always, o.over) : false}/**@@ -124,7 +133,8 @@ export function echoConfidence(m: Seg, them: Seg[], o: EchoCheck = {}): false |export function dropEcho<T extends Seg>(me: T[], them: Seg[], o: EchoCheck = {}): T[] {if (!o.echo) return meconst at = o.correlatedAt ?? always- return me.filter((m) => !echoMatch(m, them, at, o.over))+ const theirs = onMicTime(them, o)+ return me.filter((m) => !echoMatch(m, theirs, at, o.over))}/**@@ -133,7 +143,7 @@ export function dropEcho<T extends Seg>(me: T[], them: Seg[], o: EchoCheck = {})* echo heard in the audio; the lines found are hidden, never deleted.*/export function echoIds<T extends Seg & { id: number; track: 'me' | 'them' }>(segs: T[], o: EchoCheck = {}): number[] {- const them = segs.filter((s) => s.track === 'them')+ const them = onMicTime(segs.filter((s) => s.track === 'them'), o)if (!them.length || !o.echo) return []const at = o.correlatedAt ?? alwaysreturn segs.filter((s) => s.track === 'me' && echoMatch(s, them, at, o.over)).map((s) => s.id)diff --git a/app/src/main/asr/echoDetect.ts b/app/src/main/asr/echoDetect.tsindex 725039b7..8232e2c8 100644--- a/app/src/main/asr/echoDetect.ts+++ b/app/src/main/asr/echoDetect.ts@@ -13,11 +13,18 @@ import type { Moment } from './echo'* voice for a moment in an otherwise quiet 2 s), and the leak's level on the mic tells the person's own voice apart* from their copy. The envelopes of the last two hours are kept (10 ms blocks, 2.9 MB a track) and every verdict given* is remembered, so the sweep after the meeting gets the same answers for lines judged live.+ *+ * The two tracks can also sit apart on meeting time, the mic a steady way behind theirs for a whole meeting (830 ms in+ * #181, on built-in speakers). Windows that follow at none of the room's lags are looked at again out to 2 s. Over that+ * many lags chance gives plenty of windows a lag, each a different one, so an offset is believed only when a good share+ * of the windows agree on one lag, strongly; from then on the meeting is judged at it (`offsetMs`).*/const BLOCK_MS = 10const WINDOW_BLOCKS = 200const WINDOW_MS = WINDOW_BLOCKS * BLOCK_MSconst MAX_LAG_BLOCKS = 30+/** the far search, for tracks that sit apart: 310 ms to 2 s */+const FAR_MAX_LAG_BLOCKS = 200/** two hours of envelope; a line is judged within seconds of being said and its verdict kept */const RING_BLOCKS = 2 * 3600 * 100/** them is talking in a window from this mean level up; the mic shows something from this up */@@ -32,6 +39,12 @@ const MIN_ACTIVE = 10const MIN_RATE = 0.4const MIN_STEADY = 0.7const STRONG_RATE = 0.55+/**+ * an offset between the tracks: this many windows looked at far, a good share of them (MIN_RATE) at one lag (within a+ * block), most of the far-correlated ones (MIN_STEADY) there, and following closely on average+ */+const FAR_MIN_ACTIVE = 15+const FAR_STRONG = 0.7/** a line is judged on its own audio only with this much of their speech inside it (blocks of 10 ms) */const LINE_MIN_SPEAKING = 20/** a lag behind this share of the correlated windows is one the room has (a second path from the speakers) */@@ -56,6 +69,10 @@ export class EchoDetector {private correlated = new Set<number>()/** every span judged, by `start:end`: the sweep after the meeting asks about lines whose audio may be gone */private verdicts = new Map<string, Moment>()+ /** windows the room's lags did not explain, waiting for the mic to reach 2 s past them; and what the far search found in them */+ private farPending: number[] = []+ private farActive = 0+ private far: Array<{ lag: number; corr: number; ratio: number; win: number }> = []/** long lines copied almost word for word, found by the words (echo.ts); counted, but no evidence on their own */verbatim = 0@@ -83,6 +100,9 @@ export class EchoDetector {if (this.latest.them > this.nextCheck + 2 * WINDOW_BLOCKS) { this.nextCheck += WINDOW_BLOCKS; continue }break}+ while (this.farPending.length && this.latest.me >= this.farPending[0] + WINDOW_BLOCKS + FAR_MAX_LAG_BLOCKS - 1) this.checkFar(this.farPending.shift()!)+ // a mic that stopped: an hour of windows at most waits for it+ if (this.farPending.length > 1800) this.farPending.shift()}/** still in the ring: recorded, and within the last two hours */@@ -107,13 +127,67 @@ export class EchoDetector {let best = 0, bestLag = 0for (let lag = 0; lag <= MAX_LAG_BLOCKS; lag++) { const c = pearson(t, pick(me[lag])); if (c > best) { best = c; bestLag = lag } }if (best >= CORRELATED) { this.lags.push(bestLag); this.ratios.push(mean(pick(me[bestLag])) / mean(t)); this.correlated.add(Math.floor(from / WINDOW_BLOCKS)) }+ else this.farPending.push(from)+ }++ /** an active window the room's lags did not explain, against the mic 310 ms to 2 s later */+ private checkFar(from: number) {+ const t: number[] = [], idx: number[] = []+ for (let i = from; i < from + WINDOW_BLOCKS; i++) { const v = this.at('them', i); if (v >= THEM_LOUD) { t.push(v); idx.push(i) } }+ if (t.length < 20) return+ this.farActive+++ let best = 0, bestLag = 0, bestMe: number[] = []+ for (let lag = MAX_LAG_BLOCKS + 1; lag <= FAR_MAX_LAG_BLOCKS; lag++) {+ const me = idx.map((i) => this.at('me', i + lag))+ const c = pearson(t, me)+ if (c > best) { best = c; bestLag = lag; bestMe = me }+ }+ if (best >= CORRELATED) this.far.push({ lag: bestLag, corr: best, ratio: mean(bestMe) / mean(t), win: Math.floor(from / WINDOW_BLOCKS) })+ }++ /** the far windows at the tracks' offset, when there is one */+ private steadyFar(): typeof this.far {+ // asked for every line in the sweep: worked out again only when a window has been added+ const at = `${this.farActive}:${this.far.length}:${this.lags.length}`+ if (this.steadyAt !== at) {+ this.steadyAt = at; this.steadyMemo = this.findSteadyFar()+ // the offset: the lag most of those windows found+ const count = new Map<number, number>()+ for (const f of this.steadyMemo) count.set(f.lag, (count.get(f.lag) ?? 0) + 1)+ this.offsetMemo = [...count.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]?.[0] ?? 0+ }+ return this.steadyMemo+ }+ private steadyAt = ''+ private steadyMemo: typeof this.far = []+ private offsetMemo = 0+ private findSteadyFar(): typeof this.far {+ if (this.farActive < FAR_MIN_ACTIVE || this.far.length / this.farActive < MIN_RATE) return []+ const count = new Map<number, number>()+ for (const f of this.far) count.set(f.lag, (count.get(f.lag) ?? 0) + 1)+ // the lag with most windows within a block of it+ let mode = 0, most = 0+ for (const l of count.keys()) { const n = (count.get(l - 1) ?? 0) + count.get(l)! + (count.get(l + 1) ?? 0); if (n > most) { most = n; mode = l } }+ const steady = this.far.filter((f) => Math.abs(f.lag - mode) <= 1)+ if (steady.length / this.farActive < MIN_RATE || steady.length / this.far.length < MIN_STEADY) return []+ if (mean(steady.map((f) => f.corr)) < FAR_STRONG) return []+ // the room's own lags explain more of the meeting: no offset+ if (this.lags.length >= steady.length) return []+ return steady}+ /** the tracks' offset (blocks), the mic behind theirs; 0 when they are together */+ private offset(): number { this.steadyFar(); return this.offsetMemo }++ /** how far the mic track sits behind theirs on meeting time, when it is past the room's own lags (ms); undefined: together */+ offsetMs(): number | undefined { const o = this.offset(); return o ? o * BLOCK_MS : undefined }+/** a line of theirs found copied almost word for word on the mic (kept for the record; the audio decides) */noteVerbatim() { this.verbatim++ }/** echo has been heard in this meeting: a steady share of the active windows, at one lag */present(): boolean {+ if (this.offset()) return trueif (this.active < MIN_ACTIVE || this.lags.length / this.active < MIN_RATE) return falseif (this.lags.length / this.active >= STRONG_RATE) return trueconst count = new Map<number, number>()@@ -124,16 +198,27 @@ export class EchoDetector {}/** the mic followed the system track in the window holding this moment */- correlatedAt(ms: number): boolean { return this.correlated.has(Math.floor(ms / WINDOW_MS)) }+ correlatedAt(ms: number): boolean {+ const steady = this.steadyFar()+ // the mic at ms copies their window from the offset earlier+ if (steady.length) { const w = Math.floor((ms - this.offset() * BLOCK_MS) / WINDOW_MS); return steady.some((f) => f.win === w) }+ return this.correlated.has(Math.floor(ms / WINDOW_MS))+ }- /** the lags the room has shown (blocks) */+ /** the lags the room has shown (blocks), or the tracks' offset */private knownLags(): number[] {+ const o = this.offset()+ if (o) return [o]const count = new Map<number, number>()for (const l of this.lags) count.set(l, (count.get(l) ?? 0) + 1)return [...count.entries()].filter(([, n]) => n / this.lags.length >= KNOWN_LAG_SHARE).map(([l]) => l)}/** the leak's usual level on the mic, as a share of their track's: the middle of the correlated windows */- private gain(): number { const r = [...this.ratios].sort((a, b) => a - b); return r.length ? r[Math.floor(r.length / 2)] : 0 }+ private gain(): number {+ const steady = this.steadyFar()+ const r = (steady.length ? steady.map((f) => f.ratio) : [...this.ratios]).sort((a, b) => a - b)+ return r.length ? r[Math.floor(r.length / 2)] : 0+ }/*** A mic line judged by its own audio. Over its span: does the mic follow their track at the room's lag (correlated);@@ -143,13 +228,16 @@ export class EchoDetector {* audio older than two hours that was never asked about. Their voice hardly inside the line: none of these.*/over(startMs: number, endMs: number): Moment | undefined {- const key = `${startMs}:${endMs}`+ const shift = this.offset()+ // a verdict given before the offset was known was judged at the wrong lag: asked again+ const key = `${shift}:${startMs}:${endMs}`const known = this.verdicts.get(key)if (known) return knownconst lagsKnown = this.knownLags()if (!lagsKnown.length) return undefined- const a = Math.floor(startMs / BLOCK_MS), b = Math.ceil(endMs / BLOCK_MS)- if (!this.inRing('them', a) || !this.inRing('me', a)) return undefined+ // their audio that the mic's span copies: the offset earlier+ const a = Math.floor(startMs / BLOCK_MS) - shift, b = Math.ceil(endMs / BLOCK_MS) - shift+ if (!this.inRing('them', a) || !this.inRing('me', a + shift)) return undefinedconst remember = (m: Moment) => { this.verdicts.set(key, m); return m }const speaking: number[] = []for (let i = a; i < b; i++) if (this.at('them', i) >= THEM_LOUD) speaking.push(i)@@ -158,7 +246,7 @@ export class EchoDetector {const them: number[] = []for (let i = a; i < b; i++) them.push(this.at('them', i))let best = 0, bestLag = lagsKnown[0]- for (const known of lagsKnown) for (let lag = Math.max(0, known - LAG_SLACK); lag <= Math.min(MAX_LAG_BLOCKS, known + LAG_SLACK); lag++) {+ for (const known of lagsKnown) for (let lag = Math.max(0, known - LAG_SLACK); lag <= Math.min(shift ? FAR_MAX_LAG_BLOCKS : MAX_LAG_BLOCKS, known + LAG_SLACK); lag++) {const me: number[] = []for (let i = a; i < b; i++) me.push(this.at('me', i + lag))const c = pearson(them, me)diff --git a/app/src/main/asr/index.ts b/app/src/main/asr/index.tsindex beb0ce0e..9fb133af 100644--- a/app/src/main/asr/index.ts+++ b/app/src/main/asr/index.ts@@ -458,7 +458,7 @@ function sweepEcho(id: string, s: Session) {const pipe = s.pipeline// A resumed session may overlap the previous final line; its audio cannot reclassify saved words.const lines = store.segments(id).filter(line => !s.priorLines.has(line.id)), them = lines.filter(line => line.track === 'them')- const matches = lines.filter(line => line.track === 'me').map(line => ({ id: line.id, confidence: echoConfidence(line, them, { echo: true, correlatedAt: ms => pipe.echoAt(ms), over: (a, b) => pipe.echoOver(a, b) }) }))+ const matches = lines.filter(line => line.track === 'me').map(line => ({ id: line.id, confidence: echoConfidence(line, them, { echo: true, correlatedAt: ms => pipe.echoAt(ms), over: (a, b) => pipe.echoOver(a, b), offsetMs: pipe.echoOffset() }) }))const gone = matches.filter(line => line.confidence).map(line => line.id)if (!gone.length) returnstore.hideSegments(gone, matches.filter(line => line.confidence === 'high').map(line => line.id))diff --git a/app/src/main/asr/pipeline.ts b/app/src/main/asr/pipeline.tsindex b53477bf..7c182386 100644--- a/app/src/main/asr/pipeline.ts+++ b/app/src/main/asr/pipeline.ts@@ -59,7 +59,7 @@ export function createPipeline(p: {const them: Line[] = []/** is their voice reaching the mic in this meeting (no headphones)? only then are echo lines hidden */const echo = new EchoDetector()- const echoCheck = (): EchoCheck => p.echoForTests ?? { echo: echo.present(), correlatedAt: (ms) => echo.correlatedAt(ms), over: (a, b) => echo.over(a, b) }+ const echoCheck = (): EchoCheck => p.echoForTests ?? { echo: echo.present(), correlatedAt: (ms) => echo.correlatedAt(ms), over: (a, b) => echo.over(a, b), offsetMs: echo.offsetMs() }let held: Array<{ line: Line; readyAt: number; chunkStartMs: number; chunkEndMs: number }> = []let timer: NodeJS.Timeout | undefinedlet echoDropped = 0@@ -212,7 +212,7 @@ export function createPipeline(p: {}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) => {+ const aec = createEchoCancel({ make: p.cancelEcho ?? aec3, offsetMs: () => echo.offsetMs(), out: (track, ms, samples) => {if (track === 'me' && p.cleanMic) { try { p.cleanMic(ms, samples) } catch (e) { console.error('keeping the mic without echo failed', e) } }cut.push(track, ms, samples)} })@@ -295,6 +295,8 @@ export function createPipeline(p: {echoPresent: () => echoCheck().echo ?? false,echoAt: (ms: number) => echoCheck().correlatedAt?.(ms) ?? true,echoOver: (startMs: number, endMs: number) => echoCheck().over?.(startMs, endMs),+ /** how far the mic track sat behind theirs (undefined: together) */+ echoOffset: () => echoCheck().offsetMs,}}export type Pipeline = ReturnType<typeof createPipeline>diff --git a/app/test/aec.test.ts b/app/test/aec.test.tsindex 8d8d743c..c6a2b96d 100644--- a/app/test/aec.test.ts+++ b/app/test/aec.test.ts@@ -23,13 +23,33 @@ function fakeCanceller() {/** 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) {+function rig(make: () => Canceller | null, maxWaitMs?: number, offsetMs?: () => number | undefined) {const out: Array<{ track: Track; ms: number; samples: Float32Array }> = []- const aec = createEchoCancel({ make, out: (track, ms, samples) => out.push({ track, ms, samples }), maxWaitMs })+ const aec = createEchoCancel({ make, out: (track, ms, samples) => out.push({ track, ms, samples }), maxWaitMs, offsetMs })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('#181: with the mic track a steady 830 ms behind theirs, the reference is held back to just ahead of it', () => {+ const f = fakeCanceller()+ let offset: number | undefined+ const r = rig(() => f.c, undefined, () => offset)+ for (let ms = 0; ms < 1000; ms += 100) { r.aec.push('them', ms, timed(ms, 1600)); r.aec.push('me', ms, timed(ms, 1600)) }+ expect(f.log.every((x) => x.ref === x.mic)).toBe(true)+ // the detector finds the offset: the canceller's own search covers the last 100 ms of it+ offset = 830+ const from = f.log.length+ for (let ms = 1000; ms < 3000; ms += 100) { r.aec.push('them', ms, timed(ms, 1600)); r.aec.push('me', ms, timed(ms, 1600)) }+ const after = f.log.slice(from)+ expect(after.length).toBe(200)+ expect(after.every((x) => x.mic - x.ref === 730)).toBe(true)+ })+ it('#181: a room lag the canceller finds itself (under 300 ms) leaves the reference where it is', () => {+ const f = fakeCanceller()+ const r = rig(() => f.c, undefined, () => undefined)+ for (let ms = 0; ms < 2000; ms += 100) { r.aec.push('them', ms, timed(ms, 1600)); r.aec.push('me', ms, timed(ms, 1600)) }+ expect(f.log.every((x) => x.ref === x.mic)).toBe(true)+ })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)diff --git a/app/test/echo.test.ts b/app/test/echo.test.tsindex 2bc9ac53..e9b58ff4 100644--- a/app/test/echo.test.ts+++ b/app/test/echo.test.ts@@ -232,3 +232,16 @@ describe('echo confidence for the inline disclosure', () => {expect(echoConfidence(seg('we should move the launch to friday morning', 10_100), theirs, { ...o, over: () => ({ pure: true, loud: false, correlated: true }) })).toBe(false)})})++describe('#181: the mic track sits behind theirs on meeting time', () => {+ const them = { id: 1, track: 'them' as const, text: 'can you send me the report by friday please', startMs: 10_000, endMs: 10_900 }+ it('a copy that starts past the speakers\' tail on their time is still found once the offset is known', () => {+ const copy = { id: 2, track: 'me' as const, text: 'can you send me the report by friday please', startMs: 11_500, endMs: 12_300 }+ expect(echoIds([them, copy], { echo: true })).toEqual([])+ expect(echoIds([them, copy], { echo: true, offsetMs: 830 })).toEqual([2])+ })+ it('a read-back well after their line, offset included, stays', () => {+ const readBack = { id: 2, track: 'me' as const, text: 'can you send me the report by friday please', startMs: 12_600, endMs: 13_400 }+ expect(echoIds([them, readBack], { echo: true, offsetMs: 830 })).toEqual([])+ })+})diff --git a/app/test/echoDetect.test.ts b/app/test/echoDetect.test.tsindex 26dc0ce4..34d49c6f 100644--- a/app/test/echoDetect.test.ts+++ b/app/test/echoDetect.test.ts@@ -7,7 +7,7 @@ const RATE = 16000function bursts(sec: number, amp = 0.3, seed = 1): Float32Array {const out = new Float32Array(Math.round(sec * RATE))let x = seed- const rnd = () => { x = (x * 1103515245 + 12345) & 0x7fffffff; return x / 0x7fffffff }+ const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }for (let i = 0; i < out.length; i++) {const t = i / RATEconst on = (t % 0.5) < 0.3 ? 1 : 0.02@@ -58,7 +58,7 @@ describe('echo evidence from the audio itself', () => {describe("round 2: the reviewer's detector probe", () => {/** speech-like bursts with random lengths and pauses, seeded */function speech(sec: number, seed: number, amp = 0.2) {- let x = seed; const rnd = () => { x = (x * 1103515245 + 12345) & 0x7fffffff; return x / 0x7fffffff }+ let x = seed; const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }const out = new Float32Array(sec * RATE); let i = 0while (i < out.length) {const on = Math.round((0.08 + rnd() * 0.25) * RATE), off = Math.round((0.03 + rnd() * (rnd() < 0.15 ? 0.6 : 0.12)) * RATE); const a = amp * (0.3 + rnd())@@ -199,7 +199,7 @@ describe('round 4: a mic line judged by its own audio', () => {describe("round 5: the reviewer's probes: a real line of the person's is never hidden on audio", () => {const R = RATEfunction speech(sec: number, seed: number, amp = 0.2) {- let x = seed; const rnd = () => { x = (x * 1103515245 + 12345) & 0x7fffffff; return x / 0x7fffffff }+ let x = seed; const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }const out = new Float32Array(Math.round(sec * R)); let i = 0while (i < out.length) {const on = Math.round((0.08 + rnd() * 0.25) * R), off = Math.round((0.03 + rnd() * (rnd() < 0.15 ? 0.6 : 0.12)) * R); const a = amp * (0.3 + rnd())@@ -209,7 +209,7 @@ describe("round 5: the reviewer's probes: a real line of the person's is never hreturn out}function music(sec: number, seed: number, amp = 0.15) {- let x = seed; const rnd = () => { x = (x * 1103515245 + 12345) & 0x7fffffff; return x / 0x7fffffff }+ let x = seed; const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }return Float32Array.from({ length: Math.round(sec * R) }, (_, i) => { const t = i / R; return amp * (0.6 + 0.4 * Math.abs(Math.sin(Math.PI * 2 * t))) * (Math.sin(2 * Math.PI * 220 * t) * 0.5 + (rnd() - 0.5)) })}const silence = (sec: number) => Float32Array.from({ length: Math.round(sec * R) }, (_, i) => 0.0005 * (((i * 7919) % 1000) / 1000 - 0.5))@@ -250,7 +250,7 @@ describe("round 5: the reviewer's probes: a real line of the person's is never hdescribe("round 3: the reviewer's turn-taking probe (shortened)", () => {const SEC = 120function speech(sec: number, seed: number, amp = 0.2) {- let x = seed; const rnd = () => { x = (x * 1103515245 + 12345) & 0x7fffffff; return x / 0x7fffffff }+ let x = seed; const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }const out = new Float32Array(sec * RATE); let i = 0while (i < out.length) {const on = Math.round((0.08 + rnd() * 0.25) * RATE), off = Math.round((0.03 + rnd() * (rnd() < 0.15 ? 0.6 : 0.12)) * RATE); const a = amp * (0.3 + rnd())@@ -261,7 +261,7 @@ describe("round 3: the reviewer's turn-taking probe (shortened)", () => {}/** who talks when: turns of 3 to 12 s, plus random stretches where both talk */function turns(seed: number, overlap: number) {- let x = seed; const rnd = () => { x = (x * 1103515245 + 12345) & 0x7fffffff; return x / 0x7fffffff }+ let x = seed; const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }const th = new Float32Array(SEC * RATE), me = new Float32Array(SEC * RATE); let i = 0, who = 0while (i < SEC * RATE) { const len = Math.round((3 + rnd() * 9) * RATE); for (let k = 0; k < len && i < SEC * RATE; k++, i++) { if (who === 0) th[i] = 1; else me[i] = 1 } who = 1 - who }for (let n = 0; n < overlap * 14; n++) { const at = Math.floor(rnd() * (SEC - 3) * RATE), len = Math.round((0.5 + rnd() * 2) * RATE); for (let k = 0; k < len; k++) { th[at + k] = 1; me[at + k] = 1 } }@@ -286,3 +286,76 @@ describe("round 3: the reviewer's turn-taking probe (shortened)", () => {// twelve simulated calls: plain number crunching that needs more than 5 s on a busy machine}, 30_000)})++describe('#181: the mic track sits a steady way behind theirs (up to 2 s), not just the room\'s 0 to 300 ms', () => {+ /** speech-like bursts with random lengths and pauses; Math.imul keeps the generator exact, so two seeds are two talkers */+ function talk(sec: number, seed: number, amp = 0.2) {+ let x = seed; const rnd = () => { x = (Math.imul(x, 1103515245) + 12345) & 0x7fffffff; return x / 0x7fffffff }+ const out = new Float32Array(Math.round(sec * RATE)); let i = 0+ while (i < out.length) {+ const on = Math.round((0.08 + rnd() * 0.25) * RATE), off = Math.round((0.03 + rnd() * (rnd() < 0.15 ? 0.6 : 0.12)) * RATE); const a = amp * (0.3 + rnd())+ for (let k = 0; k < on && i < out.length; k++, i++) out[i] = a * Math.sin(Math.PI * k / on) * (rnd() - 0.5) * 2+ for (let k = 0; k < off && i < out.length; k++, i++) out[i] = 0.001 * (rnd() - 0.5)+ }+ return out+ }+ const add = (a: Float32Array, b: Float32Array) => a.map((v, i) => v + (b[i] ?? 0))+ const run = (me: Float32Array, them: Float32Array) => { const d = new EchoDetector(); feed(d, me, them); return d }+ const MEET = 90++ it('an echo 830 ms behind is heard, at that lag, and judged there', () => {+ const them = talk(MEET, 7919)+ const d = run(leak(them, 0.3, 830), them)+ expect(d.present()).toBe(true)+ expect(d.offsetMs()).toBeGreaterThanOrEqual(820)+ expect(d.offsetMs()).toBeLessThanOrEqual(840)+ // a moment on the mic is the copy of their audio 830 ms earlier+ expect(d.correlatedAt(40_830)).toBe(true)+ expect(d.over(40_830, 43_830)).toMatchObject({ correlated: true, loud: true })+ })+ it('the sweep hides the mic copy of their line 830 ms later; the person\'s own line stays', () => {+ const them = talk(MEET, 7919)+ const d = run(leak(them, 0.3, 830), them)+ const segs = [+ { id: 1, track: 'them' as const, text: 'can you send me the report by friday please', startMs: 40_000, endMs: 40_900 },+ { id: 2, track: 'me' as const, text: 'can you send me the report by friday please', startMs: 41_500, endMs: 42_300 },+ { id: 3, track: 'me' as const, text: 'let me check the budget numbers first and get back', startMs: 60_000, endMs: 62_000 },+ ]+ expect(echoIds(segs, { echo: d.present(), correlatedAt: (ms) => d.correlatedAt(ms), over: (a, b) => d.over(a, b), offsetMs: d.offsetMs() })).toEqual([2])+ })+ it('the room\'s own lags (60 and 90 ms) still work, with no track offset', () => {+ for (const lag of [60, 90]) {+ const them = talk(MEET, 7919)+ const d = run(leak(them, 0.3, lag), them)+ expect(d.present(), `${lag} ms`).toBe(true)+ expect(d.offsetMs(), `${lag} ms`).toBeUndefined()+ expect(d.correlatedAt(40_000), `${lag} ms`).toBe(true)+ }+ })+ it('two people talking over each other, twenty times, never give an offset, loud or quiet', { timeout: 30_000 }, () => {+ for (const meAmp of [0.2, 0.002]) for (let seed = 1; seed <= 20; seed++) {+ const d = run(talk(MEET, seed * 104729 + 3, meAmp), talk(MEET, seed * 7919))+ expect(d.offsetMs(), `amp ${meAmp} seed ${seed}`).toBeUndefined()+ expect(d.present(), `amp ${meAmp} seed ${seed}`).toBe(false)+ }+ })+ it('their track carrying the person\'s own voice late (far-end echo) is not the mic copying them', () => {+ for (let seed = 1; seed <= 5; seed++) {+ const me = talk(MEET, seed * 104729 + 3)+ const them = add(talk(MEET, seed * 7919, 0.05), leak(me, 0.5, 600))+ expect(run(me, them).offsetMs(), `seed ${seed}`).toBeUndefined()+ }+ })+ it('a chance copy now and then, at random lags over the person\'s own voice, is no offset', () => {+ // the mic copies their track for a few seconds at a time, each at a different lag, inside the person's own talk+ const them = talk(MEET, 7919)+ let me = talk(MEET, 104729 + 3)+ for (let k = 0; k < 6; k++) {+ const at = (10 + k * 12) * RATE, lag = Math.round((400 + k * 230) * 16), len = 3 * RATE+ const part = new Float32Array(me.length)+ for (let i = at; i < at + len && i < me.length; i++) part[i] = 0.3 * them[i - lag]+ me = add(me, part)+ }+ expect(run(me, them).offsetMs()).toBeUndefined()+ })+})