Skip to content

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.

Playback: the mic is played without the other side's echo where the meeting had one; the recording stays as it was (#166)

christianmat5fbb7b0fbbd2
diff --git a/app/src/main/asr/aec.ts b/app/src/main/asr/aec.ts
index 53a8b4e6..cc3c79e9 100644
--- a/app/src/main/asr/aec.ts
+++ b/app/src/main/asr/aec.ts
@@ -8,8 +8,8 @@ import type { Track } from '../capture'
*
* 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.
+ * (the canceller finds the room's own delay itself). The saved files stay as recorded; the cancelled mic is also kept
+ * beside them for listening back where the meeting had echo (cleanMic.ts).
*/
export const FRAME = 160
const FRAME_MS = 10
diff --git a/app/src/main/asr/cleanMic.ts b/app/src/main/asr/cleanMic.ts
new file mode 100644
index 00000000..36481aab
--- /dev/null
+++ b/app/src/main/asr/cleanMic.ts
@@ -0,0 +1,96 @@
+import { closeSync, existsSync, openSync, renameSync, rmSync, writeSync } from 'node:fs'
+import { join } from 'node:path'
+
+/**
+ * The mic without the other side's echo, for listening back (#166). Without headphones the mic hears them from the
+ * speakers, and the player plays both tracks at once, so their voice came out twice, a little apart. The echo canceller
+ * already cleans the mic's 16 kHz copy for whisper (aec.ts); that copy is written here too, on meeting time, and kept
+ * only for a meeting where echo was heard. The recording itself stays as it was: transcribing again, AI apps and backups
+ * read it, and deleting this file brings the player back to it.
+ *
+ * 16-bit WAV, because every player plays it (Chromium, the iPhone, any app): 1.9 MB a minute, only for meetings with echo.
+ */
+export const CLEAN_MIC = 'me-clean.wav'
+const RATE = 16000
+/** a recording that starts later than this continues an earlier one: its copy would be silent where the mic was not */
+const WHOLE_FROM_MS = 1000
+/** a jump forward past this is not a pause: nothing is written rather than hours of silence */
+const MAX_GAP_MS = 4 * 3600_000
+const FLUSH = RATE
+
+export function wavHeader(samples: number, rate = RATE): Buffer {
+ const h = Buffer.alloc(44)
+ h.write('RIFF', 0, 'ascii'); h.writeUInt32LE(36 + samples * 2, 4); h.write('WAVEfmt ', 8, 'ascii')
+ h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22); h.writeUInt32LE(rate, 24)
+ h.writeUInt32LE(rate * 2, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34)
+ h.write('data', 36, 'ascii'); h.writeUInt32LE(samples * 2, 40)
+ return h
+}
+
+export type CleanMicEnd = {
+ /** echo was heard in this meeting */
+ echo: boolean
+ /** where the meeting's audio, either track, started and ended */
+ firstMs: number
+ endMs: number
+ /** the reading stopped partway (a saved recording): what was there stays */
+ failed?: boolean
+}
+
+/** One meeting's copy, written as it comes to `<file>.part` and put in place (or thrown away) at the end */
+export function createCleanMic(dir: string) {
+ const file = join(dir, CLEAN_MIC), part = `${file}.part`
+ let fd: number | null = null
+ let written = 0
+ let broken = false
+ let buf = Buffer.alloc(FLUSH * 2), used = 0
+
+ const flush = () => {
+ if (fd === null || !used) return
+ writeSync(fd, buf, 0, used)
+ used = 0
+ }
+ const put = (x: number) => {
+ const v = Math.max(-1, Math.min(1, x))
+ buf.writeInt16LE(Math.round(v * 32767), used)
+ used += 2
+ written++
+ if (used === buf.length) flush()
+ }
+ const padTo = (ms: number) => {
+ const to = Math.round(ms * 16)
+ while (written < to) put(0)
+ }
+ const guard = (f: () => void) => {
+ if (broken) return
+ try { f() } catch (e) { broken = true; console.error('writing the mic without echo failed: the player keeps the recording as it is', e) }
+ }
+
+ return {
+ push(ms: number, samples: Float32Array) {
+ guard(() => {
+ if (fd === null) { fd = openSync(part, 'w'); writeSync(fd, wavHeader(0)) }
+ if (ms - written / 16 > MAX_GAP_MS) throw new Error(`a jump of ${Math.round(ms - written / 16)} ms`)
+ padTo(ms)
+ const skip = Math.max(0, written - Math.round(ms * 16))
+ for (let i = skip; i < samples.length; i++) put(samples[i])
+ })
+ },
+ finish(end: CleanMicEnd) {
+ const keep = !end.failed && end.echo && end.firstMs < WHOLE_FROM_MS && !broken && fd !== null
+ guard(() => {
+ if (keep) { padTo(end.endMs); flush(); writeSync(fd!, wavHeader(written), 0, 44, 0) }
+ })
+ try { if (fd !== null) closeSync(fd) } catch { /* closed */ }
+ fd = null
+ buf = Buffer.alloc(0)
+ try {
+ if (keep && !broken) { renameSync(part, file); return }
+ rmSync(part, { force: true })
+ // the recording changed (continued) or had no echo after all: an older copy would not match it
+ if (!end.failed && existsSync(file)) rmSync(file, { force: true })
+ } catch (e) { console.error('putting the mic without echo in place failed', e) }
+ },
+ }
+}
+export type CleanMic = ReturnType<typeof createCleanMic>
diff --git a/app/src/main/asr/index.ts b/app/src/main/asr/index.ts
index dad941ed..6137cf6e 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 { createCleanMic, type CleanMic } from './cleanMic'
import { loadAec3 } from './aec3'
import { echoConfidence } from './echo'
import { appleSpeechAvailable, installSpeechLocale, readSpeechLocales, speechDisagrees, speechFits, wantedSpeechLocale, type SpeechHost, type SpeechLocales } from './appleSpeech'
@@ -30,6 +31,9 @@ type Session = { complete?: () => boolean; pipeline: Pipeline | null; priorLines
/** a live meeting whose speech engine was there: a transcript left incomplete is queued for its saved recording */
liveEngine?: boolean
replacement?: boolean
+ /** the mic without echo, for listening back (cleanMic.ts) */
+ cleanMic?: CleanMic
+ aborted?: () => boolean
/** Apple's speech listens in this locale for the meeting (null: whisper only); off once whisper hears another language */
speech?: string | null
micQuickAfterFinal?: boolean
@@ -207,6 +211,8 @@ export function hookTranscription(p: {
spoken?: () => Spoken
/** a live transcript came out incomplete (whisper-server died, #127): its saved recording waits to be transcribed */
queued?: (meetingId: string) => void
+ /** the meeting's folder, where the mic without echo is kept for listening back (#166); none: not kept */
+ meetingDir?: (meetingId: string) => string
}): () => 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
@@ -317,7 +323,11 @@ export function hookTranscription(p: {
} catch (error) { if (options.signal?.aborted) return []; throw error }
}
}
+ // a reading of part of a saved recording (from a gap) would make a copy with holes: the one there stays
+ const whole = !later || !Object.values(options?.fromMs ?? {}).some((ms) => (ms ?? 0) > 0)
+ const cleanMic = transcribe && whole && p.meetingDir ? createCleanMic(p.meetingDir(id)) : undefined
const s: Session = {
+ cleanMic, aborted: () => !!options?.signal?.aborted,
complete: () => !!transcribe && !pendingBefore && !saveFailed && !warned.has('transcribe-failed') && !s.failed && !options?.signal?.aborted && !s.pipeline?.paused() && !Object.keys(s.pipeline?.gaps() ?? {}).length,
replacement: !!options?.save, liveEngine: !later && !!transcribe, store: p.store, refresh: p.refresh, speech: speechLocaleFor(id), priorLines: new Set(p.store.segments?.(id).map((s) => s.id) ?? []),
pipeline: transcribe ? createPipeline({ meetingId: id, transcribe, save: (segs) => {
@@ -332,7 +342,8 @@ export function hookTranscription(p: {
if (part.track === 'me' && s.micQuickAfterFinal !== undefined && !part.words?.length) micQuickReads(s, s.micQuickAfterFinal)
}, holdMs: p.holdMs, extraWaitMs: p.extraWaitMs, onWarn: warnOnce,
nameOf: (a, b) => p.store.meeting?.(id)?.source === 'audio-file' ? AUDIO_SPEAKER : p.nameOf?.(id, a, b) ?? previousSpeaker(priorSegments,'them',a,b),
- respell: (t) => { const m = p.store.meeting?.(id); return m ? respell(t, meetingWords(m)) : t } }) : null,
+ respell: (t) => { const m = p.store.meeting?.(id); return m ? respell(t, meetingWords(m)) : t },
+ cleanMic: cleanMic && ((ms, x) => cleanMic.push(ms, x)) }) : null,
}
if (s.speech) s.pipeline?.setQuickReads(false)
sessions.set(id, s)
@@ -466,6 +477,7 @@ function finishSession(id: string, s: Session, audioDone: () => Promise<void> =
s.store ??= store
let queued = false
s.done ??= audioDone().then(() => s.pipeline?.finish()).then(() => {
+ if (s.cleanMic && s.pipeline) s.cleanMic.finish({ echo: s.pipeline.echoPresent(), ...s.pipeline.span(), failed: !!s.failed || !!s.aborted?.() })
if (!s.replacement) clearAfterGaps(id, s)
if (!s.replacement) sweepEcho(id, s)
if (!s.replacement && s.complete?.()) s.store?.updateMeeting(id, { transcriptionPending: false })
diff --git a/app/src/main/asr/pipeline.ts b/app/src/main/asr/pipeline.ts
index a03a4cc8..b53477bf 100644
--- a/app/src/main/asr/pipeline.ts
+++ b/app/src/main/asr/pipeline.ts
@@ -43,6 +43,8 @@ export function createPipeline(p: {
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
+ /** the mic after the echo canceller, on meeting time: kept for listening back where the meeting had echo (cleanMic.ts) */
+ cleanMic?: (ms: number, samples: Float32Array) => void
}) {
const hold = p.holdMs ?? 2000
const extraWait = p.extraWaitMs ?? EXTRA_WAIT_MS
@@ -210,7 +212,12 @@ 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) => cut.push(track, ms, samples) })
+ const aec = createEchoCancel({ make: p.cancelEcho ?? aec3, 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)
+ } })
+ /** where the audio given to it started and ended, on meeting time */
+ let firstMs = Infinity, endMs = 0
let finishing: Promise<void> | undefined
return {
@@ -238,6 +245,7 @@ export function createPipeline(p: {
push(track: Track, ms: number, samples: Float32Array) {
if (closed) return
wallOffset = Date.now() - (ms + samples.length / 16)
+ firstMs = Math.min(firstMs, ms); endMs = Math.max(endMs, ms + samples.length / 16)
echo.push(track, ms, samples)
aec.push(track, ms, samples)
},
@@ -281,6 +289,7 @@ export function createPipeline(p: {
/** audio waiting for whisper on the busiest track (not counting the chunk being worked on), in ms */
backlogMs: () => Math.max(...(['me', 'them'] as const).map((t) => waiting[t].reduce((n, c) => n + c.samples.length, 0) / 16)),
busy: () => !finishing || queued('me') + queued('them') + held.length > 0,
+ span: () => ({ firstMs: Number.isFinite(firstMs) ? firstMs : 0, endMs }),
stats: () => ({ echoDropped, dropped: [...dropped], delays: [...delays] }),
/** echo was heard in this meeting (their voice on the mic): the sweep after it may hide lines; whether the mic echoed at a moment; what a line's own audio says */
echoPresent: () => echoCheck().echo ?? false,
diff --git a/app/src/main/audio.ts b/app/src/main/audio.ts
index e4afd862..eefa17ac 100644
--- a/app/src/main/audio.ts
+++ b/app/src/main/audio.ts
@@ -1,6 +1,7 @@
import { createReadStream, existsSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { Readable } from 'node:stream'
+import { CLEAN_MIC } from './asr/cleanMic'
/** yogurt-audio://<meetingId>/<track>: a meeting's recording, for the transcript's player */
export const AUDIO_SCHEME = 'yogurt-audio'
@@ -38,6 +39,15 @@ export function trackFile(dir: string, track: string, exts: readonly AudioExt[])
return null
}
+/**
+ * The file to listen to: the mic without the other side's echo where the meeting had one (asr/cleanMic.ts), else the
+ * recording. Transcribing again, AI apps and backups read the recording itself (trackFile).
+ */
+export function playbackFile(dir: string, track: string, exts: readonly AudioExt[]): string | null {
+ const clean = join(dir, CLEAN_MIC)
+ return track === 'me' && existsSync(clean) ? clean : trackFile(dir, track, exts)
+}
+
/**
* Serves only me and them of a meeting the store knows, from its own folder, once its files are final
* (the m4a is only playable after the recorder closes it). Range requests let the player seek.
@@ -49,7 +59,7 @@ export function createAudioHandler(p: { dirOf: (id: string) => string; known: (i
const id = url.hostname, track = url.pathname.slice(1)
if (url.protocol !== `${AUDIO_SCHEME}:` || !UUID.test(id) || !(TRACKS as readonly string[]).includes(track) || !p.known(id)) return notFound()
await p.ready(id)
- const file = trackFile(p.dirOf(id), track, p.exts)
+ const file = playbackFile(p.dirOf(id), track, p.exts)
if (!file) return notFound()
let size: number
try { size = statSync(file).size } catch { return notFound() }
diff --git a/app/src/main/backup.ts b/app/src/main/backup.ts
index c12ab2e4..09d86770 100644
--- a/app/src/main/backup.ts
+++ b/app/src/main/backup.ts
@@ -141,8 +141,8 @@ export function mergeBackup(into: DatabaseSync, from: DatabaseSync): { added: st
return { added: add, skipped }
}
-/** the live copy older versions kept for telling voices apart: scratch, not a recording */
-const scratch = (name: string) => name.endsWith('.f32')
+/** the live copy older versions kept for telling voices apart, and a file still being written: scratch, not a recording */
+const scratch = (name: string) => name.endsWith('.f32') || name.endsWith('.part')
// Cleanup cannot undo a committed export/import or replace the original failure.
const cleanup = (dir: string) => rm(dir, { recursive: true, force: true }).catch((e) => console.warn('backup cleanup failed', dir, e))
diff --git a/app/src/main/deleteRecording.ts b/app/src/main/deleteRecording.ts
index 71ea7bd8..a80f8cb8 100644
--- a/app/src/main/deleteRecording.ts
+++ b/app/src/main/deleteRecording.ts
@@ -44,7 +44,7 @@ export async function deleteRecording(id: string, p: {
// Native joins retain exact audio inputs here, sometimes as hard links.
rmSync(join(dir, 'original'), { recursive: true, force: true })
// Unlink synchronously so a resumed recording cannot start between the guard and deletion.
- for (const f of files) if (/^(me|them)(\.joined)?\.(m4a|ogg|wav|f32)(\.joined|\.tmp)?$/.test(f)) unlinkSync(join(dir, f))
+ for (const f of files) if (/^(me|them)(\.joined|-clean)?\.(m4a|ogg|wav|f32)(\.joined|\.tmp|\.part)?$/.test(f)) unlinkSync(join(dir, f))
try { p.removed(id) } catch (e) { console.warn('recording deleted; window refresh failed', id, e) }
return 'deleted'
} catch (e) {
diff --git a/app/src/main/index.ts b/app/src/main/index.ts
index eefb7269..48794ce5 100644
--- a/app/src/main/index.ts
+++ b/app/src/main/index.ts
@@ -89,7 +89,7 @@ import { createQuietStart } from './quietStart'
import { startArgs, startReason, type StartReason } from './startReason'
import { quitCalledOff, quitting, started as startedAfterQuit } from './quitByUser'
import { deleteRecording } from './deleteRecording'
-import { AUDIO_SCHEME, audioExts, createAudioHandler, trackFile, type AudioExt } from './audio'
+import { AUDIO_SCHEME, audioExts, createAudioHandler, playbackFile, trackFile, type AudioExt } from './audio'
import { helperDecode, wavDecode } from './asr/backfill'
import { finishQuit, hookUpdates, isPreviewBuild, updatesOn } from './updates'
import { createCompanion, type Companion } from './companion'
@@ -676,6 +676,8 @@ app.whenReady().then(() => {
warn: (code) => tell({ t: 'warn', code }), pidFile: join(userDataDir(), 'whisper-server.pid'),
// whisper-server went down mid-meeting (#127): the rest is read from the saved recording once the transcript is settled
queued: () => { void savedTranscriptions.pump() },
+ // the mic without the other side's echo is kept beside the recording, for listening back (#166)
+ meetingDir: (id) => join(userDataDir(), 'meetings', id),
// English only (the default) or Multi-language, read on each chunk so the footer's picker counts at once
spoken: () => spokenSetting(loadSettings(settingsFile)),
// Apple's on-device speech for the live words (macOS 26, Apple Silicon); fake mode has a stand-in when a test asks
@@ -1209,7 +1211,8 @@ app.whenReady().then(() => {
start: (id, again) => savedTranscriptions.start(id, again) }, m, audioPath, draft),
audioFiles: async (id) => {
await rejoined; await recordingSettled(id)
- return (['me', 'them'] as const).flatMap((track) => { const path = trackFile(meetingDir(id), track, audioKinds); return path ? [{ track, path }] : [] })
+ // the iPhone plays what the note's player plays: the mic without echo where there is one (#166)
+ return (['me', 'them'] as const).flatMap((track) => { const path = playbackFile(meetingDir(id), track, audioKinds); return path ? [{ track, path }] : [] })
},
ops: {
// a new revision; an open note takes it unless it was typed in since (then both texts are kept)
diff --git a/app/test/audio.test.ts b/app/test/audio.test.ts
index 577e05e5..126d0eb9 100644
--- a/app/test/audio.test.ts
+++ b/app/test/audio.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
-import { audioExts, createAudioHandler, parseRange, trackFile } from '../src/main/audio'
+import { audioExts, createAudioHandler, parseRange, playbackFile, trackFile } from '../src/main/audio'
const ID = '3f2b8c1e-7d4a-4c9b-9e1f-0a1b2c3d4e5f'
function setup(o: { known?: (id: string) => boolean; ready?: () => Promise<void> } = {}) {
@@ -121,3 +121,23 @@ describe('a meeting restored from another computer', () => {
expect([them.headers.get('content-type'), await them.text()]).toEqual(['audio/mp4', 'mac-them'])
})
})
+
+describe('the mic without the echo (#166)', () => {
+ it('plays the cleaned mic copy where there is one, and keeps the recording as it was', async () => {
+ const { root, handle } = setup()
+ const dir = join(root, 'meetings', ID)
+ writeFileSync(join(dir, 'me-clean.wav'), 'RIFF-clean')
+ const me = await get(handle, `yogurt-audio://${ID}/me`)
+ expect([me.status, me.headers.get('content-type'), await me.text()]).toEqual([200, 'audio/wav', 'RIFF-clean'])
+ expect(await (await get(handle, `yogurt-audio://${ID}/them`)).text()).toBe('abcdefghij')
+ expect(playbackFile(dir, 'me', ['m4a'])).toBe(join(dir, 'me-clean.wav'))
+ expect(playbackFile(dir, 'them', ['m4a'])).toBe(join(dir, 'them.m4a'))
+ // transcribing again, AI apps and backups read the recording itself
+ expect(trackFile(dir, 'me', ['m4a'])).toBe(join(dir, 'me.m4a'))
+ })
+ it('falls back to the recording without a cleaned copy', () => {
+ const { root } = setup()
+ const dir = join(root, 'meetings', ID)
+ expect(playbackFile(dir, 'me', ['m4a'])).toBe(join(dir, 'me.m4a'))
+ })
+})
diff --git a/app/test/cleanMic.test.ts b/app/test/cleanMic.test.ts
new file mode 100644
index 00000000..5a3c1076
--- /dev/null
+++ b/app/test/cleanMic.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { CLEAN_MIC, createCleanMic, wavHeader } from '../src/main/asr/cleanMic'
+import { createPipeline } from '../src/main/asr/pipeline'
+import { FRAME, type Canceller } from '../src/main/asr/aec'
+
+const RATE = 16000
+const dirs: string[] = []
+afterEach(() => { dirs.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true })) })
+const temp = () => { const d = mkdtempSync(join(tmpdir(), 'yogurt-clean-')); dirs.push(d); return d }
+const tone = (n: number, level = 0.5) => Float32Array.from({ length: n }, (_, i) => level * Math.sin(i / 7))
+/** the samples of a 16-bit mono WAV, as -1..1 */
+function samplesOf(file: string): number[] {
+ const b = readFileSync(file)
+ const n = b.readUInt32LE(40) / 2
+ return Array.from({ length: n }, (_, i) => b.readInt16LE(44 + i * 2) / 32767)
+}
+
+describe('wavHeader', () => {
+ it('describes 16 kHz mono 16-bit audio of the given length', () => {
+ const h = wavHeader(1000)
+ expect(h.length).toBe(44)
+ expect(h.toString('ascii', 0, 4)).toBe('RIFF')
+ expect(h.readUInt32LE(4)).toBe(36 + 2000)
+ expect(h.toString('ascii', 8, 16)).toBe('WAVEfmt ')
+ expect(h.readUInt16LE(20)).toBe(1)
+ expect(h.readUInt16LE(22)).toBe(1)
+ expect(h.readUInt32LE(24)).toBe(RATE)
+ expect(h.readUInt32LE(28)).toBe(RATE * 2)
+ expect(h.readUInt16LE(34)).toBe(16)
+ expect(h.toString('ascii', 36, 40)).toBe('data')
+ expect(h.readUInt32LE(40)).toBe(2000)
+ })
+})
+
+describe('the cleaned mic copy', () => {
+ it('is kept for a meeting with echo, on meeting time: gaps are silence, overlaps are not written twice, the end reaches their track', () => {
+ const dir = temp(), c = createCleanMic(dir)
+ c.push(0, tone(1600))
+ // a pause: 100 ms of nothing, then a piece that starts 5 ms before the last one ended
+ c.push(200, tone(1600, 0.25))
+ c.push(295, tone(1600, 0.1))
+ c.finish({ echo: true, firstMs: 0, endMs: 500 })
+ expect(readdirSync(dir)).toEqual([CLEAN_MIC])
+ const s = samplesOf(join(dir, CLEAN_MIC))
+ expect(s.length).toBe(500 * 16)
+ expect(s[100]).toBeCloseTo(0.5 * Math.sin(100 / 7), 3)
+ expect(s.slice(1600, 3200).every((x) => x === 0)).toBe(true)
+ expect(s[3200 + 100]).toBeCloseTo(0.25 * Math.sin(100 / 7), 3)
+ // the overlapping 5 ms (80 samples) of the third piece are dropped
+ expect(s[4800]).toBeCloseTo(0.1 * Math.sin(80 / 7), 3)
+ expect(s.slice(6320).every((x) => x === 0)).toBe(true)
+ })
+
+ it('clips instead of wrapping around', () => {
+ const dir = temp(), c = createCleanMic(dir)
+ c.push(0, Float32Array.from([2, -2, 0.5]))
+ c.finish({ echo: true, firstMs: 0, endMs: 0 })
+ const s = samplesOf(join(dir, CLEAN_MIC))
+ expect(s[0]).toBeCloseTo(1, 3)
+ expect(s[1]).toBeCloseTo(-1, 3)
+ })
+
+ it('is not kept when there was no echo (headphones), and an older copy goes', () => {
+ const dir = temp()
+ writeFileSync(join(dir, CLEAN_MIC), 'old')
+ const c = createCleanMic(dir)
+ c.push(0, tone(1600))
+ c.finish({ echo: false, firstMs: 0, endMs: 100 })
+ expect(readdirSync(dir)).toEqual([])
+ })
+
+ it('is not kept for a recording that continues an earlier one: the old copy no longer matches the mic', () => {
+ const dir = temp()
+ writeFileSync(join(dir, CLEAN_MIC), 'old')
+ const c = createCleanMic(dir)
+ c.push(60_000, tone(1600))
+ c.finish({ echo: true, firstMs: 60_000, endMs: 60_100 })
+ expect(readdirSync(dir)).toEqual([])
+ })
+
+ it('leaves the copy it had when a reading of the saved recording stops partway', () => {
+ const dir = temp()
+ writeFileSync(join(dir, CLEAN_MIC), 'old')
+ const c = createCleanMic(dir)
+ c.push(0, tone(1600))
+ c.finish({ echo: true, firstMs: 0, endMs: 100, failed: true })
+ expect(readdirSync(dir)).toEqual([CLEAN_MIC])
+ expect(readFileSync(join(dir, CLEAN_MIC), 'utf8')).toBe('old')
+ })
+
+ it('writes nothing for a meeting without a mic', () => {
+ const dir = temp(), c = createCleanMic(dir)
+ c.finish({ echo: true, firstMs: 0, endMs: 100 })
+ expect(existsSync(join(dir, CLEAN_MIC))).toBe(false)
+ expect(readdirSync(dir)).toEqual([])
+ })
+})
+
+describe('the pipeline gives out the cleaned mic', () => {
+ it('passes the mic after the echo canceller, and says the span of audio it got', async () => {
+ const halve: Canceller = { analyze: () => {}, process: (mic, out) => { for (let i = 0; i < FRAME; i++) out[i] = mic[i] / 2 }, free: () => {} }
+ const got: Array<{ ms: number; samples: Float32Array }> = []
+ const p = createPipeline({ meetingId: 'm1', holdMs: 10, transcribe: async () => [], save: () => {}, emit: () => {}, cancelEcho: () => halve,
+ cleanMic: (ms, samples) => got.push({ ms, samples: samples.slice() }) })
+ const x = tone(RATE)
+ for (let i = 0; i < x.length; i += 1600) { p.push('them', 40 + i / 16, x.subarray(i, i + 1600)); p.push('me', 40 + i / 16, x.subarray(i, i + 1600)) }
+ await p.finish()
+ expect(got[0].ms).toBe(40)
+ const all = got.flatMap((g) => [...g.samples])
+ expect(all.length).toBe(RATE)
+ expect(Math.max(...all)).toBeCloseTo(0.25, 2)
+ expect(p.span()).toEqual({ firstMs: 40, endMs: 1040 })
+ })
+})
diff --git a/app/test/deleteRecording.test.ts b/app/test/deleteRecording.test.ts
index a3b10210..f0bd8f0d 100644
--- a/app/test/deleteRecording.test.ts
+++ b/app/test/deleteRecording.test.ts
@@ -20,7 +20,7 @@ function setup({ transcript = true, summary = true } = {}) {
const folder = store.createFolder('Launch'); store.addToFolder(folder.id, m.id)
store.addChatTurn(m.id, 'When is launch?')
const dir = join(root, m.id); mkdirSync(dir)
- for (const name of ['me.m4a', 'them.ogg', 'me.wav', 'them.f32', 'me.m4a.joined', 'me.joined.m4a', 'them.joined.ogg', 'metadata.json']) writeFileSync(join(dir, name), 'fixture')
+ for (const name of ['me.m4a', 'them.ogg', 'me.wav', 'them.f32', 'me.m4a.joined', 'me.joined.m4a', 'them.joined.ogg', 'me-clean.wav', 'me-clean.wav.part', 'metadata.json']) writeFileSync(join(dir, name), 'fixture')
mkdirSync(join(dir, 'original'))
linkSync(join(dir, 'me.m4a'), join(dir, 'original', 'previous-me.m4a'))
writeFileSync(join(dir, 'original', 'previous-them.1.ogg'), 'original recording')