知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix(android): Face to face now hears people speaking normally across the table, not only someone right at the phone
wquguru415b092b62e9
diff --git a/android/cli/src/main/kotlin/cicada/cli/Main.kt b/android/cli/src/main/kotlin/cicada/cli/Main.ktindex f4b4047..e742877 100644--- a/android/cli/src/main/kotlin/cicada/cli/Main.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Main.kt@@ -1,13 +1,13 @@// cicada-cli: the Android engines without Android (scripts/cli.sh runs it).//// cicada-cli test the unit tests (no network)-// cicada-cli listen <file.wav> [--target zh-CN] [--speed 1|0] [--notes] [--log]+// cicada-cli listen <file.wav> [--target zh-CN] [--speed 1|0] [--notes] [--log] [--room]// Plays the file into ListenEngine as if the phone were playing it, prints each line as it// is recorded, then the record's folder. --notes waits for the final notes and prints them.// cicada-cli hear <file.wav> [--target zh-CN] one file to the hear model (Ming on Ling), raw reply printed// cicada-cli say <file.wav> [--to en] [--out said.wav]// 我说 · 面对面: what I say heard and translated, then read by the service's voice into a WAV-// cicada-cli segments <file.wav> where the segmenter cuts+// cicada-cli segments <file.wav> [--room] where the segmenter cuts (--room: 面对面's gate)// cicada-cli roundtrip <session.json>… reads and writes records, says if a byte changed//// --provider ling|openrouter|zenmux the AI service (default ling), with its recommended models;@@ -54,7 +54,7 @@ fun main(argv: Array<String>) {"segments" -> {val pcm = Wav.read(File(args[1]).inputStream())val list = mutableListOf<Segment>()- val seg = Segmenter().apply { onSegment = { list.add(it) } }+ val seg = Segmenter(if ("--room" in args) VoiceGate() else null).apply { onSegment = { list.add(it) } }var i = 0while (i < pcm.size) { seg.feed(pcm.copyOfRange(i, minOf(pcm.size, i + 1600))); i += 1600 }seg.flush()@@ -135,7 +135,7 @@ fun main(argv: Array<String>) {val ended = java.util.concurrent.CountDownLatch(1)val source = PcmAudioSource(File(args[1]), opt("--speed", "1").toDouble())source.onEnded = { ended.countDown() }- engine.start(source, "file")+ engine.start(source, if ("--room" in args) "mic" else "file")ended.await()Thread.sleep(1500)engine.stop()diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.ktindex e232244..e32b244 100644--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt@@ -61,6 +61,7 @@ object Tests {"keyClicksAreNotSpeech" to ::keyClicksAreNotSpeech,"cutsLongSpeechAtItsQuietestMoment" to ::cutsLongSpeech,"ignoresClicks" to ::ignoresClicks,+ "roomGateHearsAcrossTheTable" to ::roomGateHearsAcrossTheTable,"wavRoundTrip" to ::wavRoundTrip,"parsesNotes" to ::parsesNotes,"termsKeepOnlyFormsTheRecognizerWrote" to ::termsKeepOnlyFormsTheRecognizerWrote,@@ -459,9 +460,11 @@ object Tests {}fun concat(vararg parts: ShortArray): ShortArray = parts.fold(ShortArray(0)) { a, b -> a + b }- private fun cut(vararg parts: ShortArray): List<Segment> {+ private fun cut(vararg parts: ShortArray): List<Segment> = cut(null, *parts)++ private fun cut(gate: VoiceGate?, vararg parts: ShortArray): List<Segment> {val list = mutableListOf<Segment>()- val seg = Segmenter().apply { onSegment = { list.add(it) } }+ val seg = Segmenter(gate).apply { onSegment = { list.add(it) } }for (p in parts) { var i = 0; while (i < p.size) { seg.feed(p.copyOfRange(i, minOf(p.size, i + 1600))); i += 1600 } }seg.flush()return list@@ -492,6 +495,28 @@ object Tests {equal(0, cut(silence(0.5), keys(3.0), silence(1.0)).size, "typing alone makes no segment")}+ /// A room's hiss, about -60 dBFS.+ private fun room(seconds: Double, seed: Long = 7): ShortArray {+ val r = java.util.Random(seed)+ return ShortArray((seconds * 16000).toInt()) { (r.nextGaussian() * 0.001 * 32767).toInt().toShort() }+ }+ private fun mix(a: ShortArray, b: ShortArray) = ShortArray(a.size) { (a[it] + b[it]).coerceIn(-32768, 32767).toShort() }++ /// 面对面 (#30): a phone's mic hears a voice across the table around -50 dBFS, under the fixed+ /// -40 dBFS line, so the meeting showed 等有人说话… for 8 minutes. The room's gate hears it.+ fun roomGateHearsAcrossTheTable() {+ val gate = VoiceGate()+ equal(0.004, gate.threshold, "before the room is known")+ for (i in 0 until 30 * 33) gate.voiced(if (i % 10 == 0) 0.02 else 0.003, 0.03)+ check(abs(gate.threshold - 0.006) < 1e-9, "twice the room's noise, got ${gate.threshold}")+ check(gate.voiced(0.008, 0.03), "a quiet voice across the table")+ check(!gate.voiced(0.004, 0.03), "the fan")+ val voice = mix(concat(silence(4.0), tone(3.0, 0.006), silence(1.0)), room(8.0))+ equal(0, cut(voice).size, "the fixed line misses it")+ equal(1, cut(VoiceGate(), voice).size, "the room's line hears it")+ equal(0, cut(VoiceGate(), room(20.0)).size, "the room alone is not speech")+ }+fun ignoresClicks() {equal(0, cut(silence(1.0), tone(0.1), silence(1.0)).size, "under 0.25 s of sound is not speech")equal(0, cut(tone(3.0, 0.002)).size, "below the gate is silence")diff --git a/android/core/src/main/kotlin/cicada/ListenEngine.kt b/android/core/src/main/kotlin/cicada/ListenEngine.ktindex 46f3553..f37968c 100644--- a/android/core/src/main/kotlin/cicada/ListenEngine.kt+++ b/android/core/src/main/kotlin/cicada/ListenEngine.kt@@ -179,7 +179,8 @@ class ListenEngine(notes.begin(session.id)speakers?.reset()fixes?.meetingStarted()- val segmenter = Segmenter()+ // 面对面: the line follows the room, as the Mac's and Windows' room mic do.+ val segmenter = Segmenter(if (kind == "mic") VoiceGate() else null)segmenter.onSegment = ::sendval queue = LinkedBlockingQueue<ShortArray>()audio = queuediff --git a/android/core/src/main/kotlin/cicada/Segmenter.kt b/android/core/src/main/kotlin/cicada/Segmenter.ktindex 2062e85..9d04e65 100644--- a/android/core/src/main/kotlin/cicada/Segmenter.kt+++ b/android/core/src/main/kotlin/cicada/Segmenter.kt@@ -9,10 +9,11 @@ class Segment(val index: Int, val start: Double, val samples: ShortArray) {/// Cuts the audio into stretches of speech by loudness alone: a pause of 0.6 s ends one, and one/// that runs to 8 s is cut at its quietest moment in the last 2 s, so a word is split as rarely as/// possible (Ming has no word timings to put it back together). Not thread-safe: fed from the-/// listening worker only. Same numbers as the Windows Segmenter. (A meeting's first stretch was once+/// listening worker only. Same numbers as the Windows Segmenter. 面对面 gives it a VoiceGate: a+/// phone's mic hears a voice across the table well under -40 dBFS. (A meeting's first stretch was once/// cut at 4 s to show a line sooner: Ming then finished the cut sentence by itself, and the rest/// came back as a second, duplicate line.)-class Segmenter {+class Segmenter(private val gate: VoiceGate? = null) {companion object {const val RATE = 16000private const val FRAME = 480 // 30 ms@@ -54,6 +55,8 @@ class Segmenter {private var quietFrames = 0private var loudFrames = 0private var index = 0+ /// The level that counts as speech for this frame: the gate's when there is one.+ private var line = thresholdvar onSegment: ((Segment) -> Unit)? = null@@ -72,9 +75,16 @@ class Segmenter {/// Whether the frame holds speech: sound that has lasted 30 ms, judged in 10 ms steps against the/// line, so a lone key click (a few ms) neither opens a segment nor breaks the pause that ends one- /// (VoiceActivity.swift's onset); the pre-roll then reaches back to where that sound began.- private fun isSpeech(frame: ShortArray): Boolean {- val line = threshold+ /// (VoiceActivity.swift's onset); the pre-roll then reaches back to where that sound began. A+ /// room's gate learns its noise per frame and takes whole ones, as the Mac's does per block: a+ /// voiced 30 ms frame has lasted the onset already.+ private fun isSpeech(frame: ShortArray, level: Double): Boolean {+ gate?.let { g ->+ val on = g.voiced(level, FRAME / RATE.toDouble())+ sounding = if (on) sounding + FRAME / STEP else 0+ carried = false+ return on+ }var said = falsevar early = sounding > 0var i = 0@@ -93,7 +103,8 @@ class Segmenter {private fun step(frame: ShortArray) {val level = Wav.rms(frame)val high = high(frame)- val loud = isSpeech(frame)+ line = gate?.threshold ?: threshold+ val loud = isSpeech(frame, level)val now = consumed / RATE.toDouble()consumed += frame.size@@ -146,13 +157,13 @@ class Segmenter {/// through more often than before (about 1 in 3 segments, was 1 in 5); what Ming makes of it/// still meets the hear filter (Translator.isNoise).internal fun isSteady(frameLevels: List<Double>): Boolean {- val first = frameLevels.indexOfFirst { it >= threshold }- val last = frameLevels.indexOfLast { it >= threshold }+ val first = frameLevels.indexOfFirst { it >= line }+ val last = frameLevels.indexOfLast { it >= line }if (first < 0 || last <= first) return falseval body = frameLevels.subList(first, last + 1)- val top = body.map { maxOf(it, threshold) }.sorted()+ val top = body.map { maxOf(it, line) }.sorted()if (top[(0.9 * (top.size - 1)).toInt()] >= steady * top[(0.1 * (top.size - 1)).toInt()]) return false- val low = body.map { maxOf(it, threshold / 8) }.sorted()+ val low = body.map { maxOf(it, line / 8) }.sorted()return low[(0.5 * (low.size - 1)).toInt()] < dips * low[(0.1 * (low.size - 1)).toInt()]}@@ -173,10 +184,10 @@ class Segmenter {/// morning everyone." at 7.5 to 11.4 dB depending on where the frames fell, so it came and/// went with a few ms of lead-in; 10 ms steps and their 5th percentile give it 14.6 to 16.5.internal fun isWord(frameLevels: List<Double>): Boolean {- val first = frameLevels.indexOfFirst { it >= threshold }- val last = frameLevels.indexOfLast { it >= threshold }+ val first = frameLevels.indexOfFirst { it >= line }+ val last = frameLevels.indexOfLast { it >= line }if (first < 0 || (last - first + 1) * FRAME > short * RATE) return false- val quiet = threshold / 4+ val quiet = line / 4val q = lead ?: return falseif (q > quiet || last + 1 >= frameLevels.size || frameLevels.subList(last + 1, frameLevels.size).minOrNull()!! > quiet) return falseval samples = current.slice(0, current.size)@@ -191,7 +202,7 @@ class Segmenter {val rise = minOf(quiet, steps.max() / fade)val from = steps.indexOfFirst { it >= rise }val to = steps.indexOfLast { it >= rise }- val body = steps.subList(from, to + 1).map { maxOf(it, threshold / 8) }.sorted()+ val body = steps.subList(from, to + 1).map { maxOf(it, line / 8) }.sorted()val low = maxOf(2, (0.05 * (body.size - 1)).toInt())return low < body.size && body[(0.9 * (body.size - 1)).toInt()] >= swell * body[low] && isVoiced(frameLevels, samples)}@@ -238,7 +249,7 @@ class Segmenter {internal fun isRumble(frameLevels: List<Double>, frameHighs: List<Double>): Boolean {var full = 0.0; var above = 0.0for (i in 0 until minOf(frameLevels.size, frameHighs.size)) {- if (frameLevels[i] < threshold) continue+ if (frameLevels[i] < line) continuefull += frameLevels[i] * frameLevels[i]above += frameHighs[i] * frameHighs[i]}@@ -255,7 +266,7 @@ class Segmenter {val restSpeech = ArrayList(speech.subList(minOf(speech.size, end / FRAME), speech.size))val start = currentStartval sent = ArrayList(levels.subList(0, minOf(levels.size, end / FRAME)))- val said = if (isWord(levels)) sent.count { it >= threshold / 4 } * FRAME >= minWord * RATE+ val said = if (isWord(levels)) sent.count { it >= line / 4 } * FRAME >= minWord * RATEelse loudFrames * FRAME >= minSpeech * RATE && !isSteady(sent)val heard = said && !isRumble(sent, ArrayList(highs.subList(0, sent.size)))current.clear(); levels.clear(); highs.clear(); speech.clear()@@ -278,6 +289,41 @@ class Segmenter {}}+/// 面对面: where speech starts follows the room. The Mac's VoiceGate (RoomMic.swift) and Windows':+/// twice the room's noise, between -56 and -40 dBFS, the noise being the quietest moment of each+/// second (the gaps between words, even while people talk on and on), taken low over the last half+/// minute. A phone's VOICE_RECOGNITION input has no gain control, so a voice a metre away comes in+/// around -50 dBFS and a fixed -40 dBFS line never opened once (#30).+class VoiceGate {+ companion object {+ const val FIXED = 0.01+ const val LOWEST = 0.0015+ }+ private val quietest = ArrayDeque<Double>()+ private var second = Double.POSITIVE_INFINITY+ private var elapsed = 0.0++ val threshold: Double get() {+ if (quietest.size < 3) return 0.004+ val floor = quietest.sorted()[quietest.size / 5]+ return minOf(FIXED, maxOf(LOWEST, floor * 2))+ }++ /// Takes one frame's level and length; true when it is over the line.+ fun voiced(rms: Double, seconds: Double): Boolean {+ val on = rms >= threshold+ second = minOf(second, rms)+ elapsed += seconds+ if (elapsed >= 1 - 1e-9) {+ quietest.addLast(second)+ if (quietest.size > 30) quietest.removeFirst()+ second = Double.POSITIVE_INFINITY+ elapsed = 0.0+ }+ return on+ }+}+/// A growable ShortArray (no boxing on the audio path).internal class ShortList {private var a = ShortArray(RATE_HINT)