Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

chore(android): send speech to Ming as AAC, a tenth of the mobile data

wqugurue901fed5e35e
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt
new file mode 100644
index 0000000..3a8b125
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt
@@ -0,0 +1,95 @@
+package com.wquguru.cicada
+
+import android.media.MediaCodec
+import android.media.MediaCodecInfo
+import android.media.MediaFormat
+import cicada.Clip
+import cicada.Segmenter
+import java.io.ByteArrayOutputStream
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/// A segment as AAC-LC in ADTS frames ("audio/aac"), which Ming hears as well as WAV at ~1/10 the
+/// size. ADTS needs no muxer or temp file: each encoded frame gets a 7-byte header. Null when the
+/// device has no usable encoder; the caller then sends WAV.
+object AacEncoder {
+ private const val BITRATE = 24_000
+ private const val TIMEOUT_US = 10_000L
+
+ fun encode(pcm: ShortArray, rate: Int = Segmenter.RATE): Clip? {
+ val freq = FREQ_INDEX[rate] ?: return null
+ val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, rate, 1).apply {
+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)
+ setInteger(MediaFormat.KEY_BIT_RATE, BITRATE)
+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16 * 1024)
+ }
+ val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC)
+ try {
+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
+ codec.start()
+ val bytes = ByteBuffer.allocate(pcm.size * 2).order(ByteOrder.LITTLE_ENDIAN)
+ for (s in pcm) bytes.putShort(s)
+ bytes.flip()
+ val out = ByteArrayOutputStream(pcm.size / 4)
+ val info = MediaCodec.BufferInfo()
+ var fed = 0L
+ var inputDone = false
+ // Bounded so a stuck codec can't hold a segment forever (~2 s without output).
+ var idle = 0
+ while (idle < 200) {
+ if (!inputDone) {
+ val i = codec.dequeueInputBuffer(1_000)
+ if (i >= 0) {
+ val buf = codec.getInputBuffer(i)!!
+ buf.clear()
+ val n = minOf(buf.remaining(), bytes.remaining())
+ val slice = bytes.slice(); slice.limit(n); buf.put(slice)
+ bytes.position(bytes.position() + n)
+ val timeUs = fed * 1_000_000L / rate
+ fed += n / 2
+ inputDone = !bytes.hasRemaining()
+ codec.queueInputBuffer(i, 0, n, timeUs, if (inputDone) MediaCodec.BUFFER_FLAG_END_OF_STREAM else 0)
+ }
+ }
+ // Drain everything ready without waiting while there is input left to feed:
+ // waiting on each frame here made a 7 s segment take a second to encode.
+ while (true) {
+ val o = codec.dequeueOutputBuffer(info, if (inputDone) TIMEOUT_US else 0)
+ if (o < 0) { if (inputDone) idle++; break }
+ idle = 0
+ val buf = codec.getOutputBuffer(o)!!
+ if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0 && info.size > 0) {
+ buf.position(info.offset); buf.limit(info.offset + info.size)
+ out.write(adts(info.size, freq))
+ val frame = ByteArray(info.size); buf.get(frame); out.write(frame)
+ }
+ codec.releaseOutputBuffer(o, false)
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
+ return if (out.size() > 0) Clip(out.toByteArray(), "audio/aac") else null
+ }
+ }
+ }
+ return null
+ } finally {
+ try { codec.stop() } catch (_: Exception) {}
+ codec.release()
+ }
+ }
+
+ private val FREQ_INDEX = mapOf(48000 to 3, 44100 to 4, 32000 to 5, 24000 to 6, 22050 to 7, 16000 to 8, 12000 to 9, 11025 to 10, 8000 to 11)
+
+ /// ADTS header for one AAC-LC mono frame of `size` bytes.
+ private fun adts(size: Int, freq: Int): ByteArray {
+ val len = size + 7
+ val profile = 1 // AAC LC (object type 2) minus one
+ val channels = 1
+ return byteArrayOf(
+ 0xFF.toByte(), 0xF1.toByte(),
+ ((profile shl 6) or (freq shl 2) or (channels shr 2)).toByte(),
+ (((channels and 3) shl 6) or (len shr 11)).toByte(),
+ ((len and 0x7FF) shr 3).toByte(),
+ (((len and 7) shl 5) or 0x1F).toByte(),
+ 0xFC.toByte(),
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index 11ea7cd..4f19360 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -69,6 +69,10 @@ class CicadaApp : Application() {
notes = NotesEngine(ling, store)
translator = Translator(ling)
listen = ListenEngine(ling, translator, store, notes, settings)
+ listen.encoder = { pcm ->
+ val t = System.currentTimeMillis()
+ AacEncoder.encode(pcm)?.also { Log.d("listen: ${pcm.size * 2 / 1024} KB PCM → ${it.bytes.size / 1024} KB ${it.type} in ${System.currentTimeMillis() - t} ms") }
+ }
overlay = Overlay(this)
listen.onChange(::changed)
notes.onChange(::changed)
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index ff9cb68..fcf947f 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -394,6 +394,8 @@ object Tests {
equal("audio_url", user[0].obj()!!["type"], "audio first")
equal("data:audio/wav;base64,AQID", user[0].obj()!!["audio_url"].obj()!!["url"], "WAV as a data URL")
equal("Translate.", user[1].obj()!!["text"], "fixed instruction last")
+ client(fake).chat("c", "i", Priority.Translate, model = LingClient.AUDIO_MODEL, audio = byteArrayOf(1, 2, 3), audioType = "audio/aac")
+ equal("data:audio/aac;base64,AQID", content(fake.calls[1].second, 1).arr()[0].obj()!!["audio_url"].obj()!!["url"], "AAC keeps its type")
}
fun lingDropsHijacked() {
diff --git a/android/core/src/main/kotlin/cicada/Audio.kt b/android/core/src/main/kotlin/cicada/Audio.kt
index 4d1f34d..336f9d4 100644
--- a/android/core/src/main/kotlin/cicada/Audio.kt
+++ b/android/core/src/main/kotlin/cicada/Audio.kt
@@ -53,6 +53,11 @@ class PcmAudioSource(private val load: () -> ShortArray, private val speed: Doub
override fun stop() { stopped = true }
}
+/// One stretch of speech as sent to Ming: the bytes and their media type.
+class Clip(val bytes: ByteArray, val type: String) {
+ companion object { fun wav(pcm: ShortArray) = Clip(Wav.bytes(pcm), "audio/wav") }
+}
+
object Wav {
fun bytes(pcm: ShortArray, rate: Int = Segmenter.RATE): ByteArray {
val b = ByteBuffer.allocate(44 + pcm.size * 2).order(ByteOrder.LITTLE_ENDIAN)
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index 4037499..68c7f8e 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -161,16 +161,17 @@ class LingClient(private val key: AIKey, private val transport: Transport = UrlT
}
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
- /// message, `audio` (a WAV) goes before it for Ming. Notes retry 429s with backoff; heard audio
+ /// message, `audio` (of `audioType`) goes before it for Ming. Notes retry 429s with backoff; heard audio
/// gets one retry (a lost reply loses the words); the rest fail fast so the caller can fall back.
fun chat(
content: String, instruction: String, priority: Priority, json: Boolean = false,
maxTokens: Int = 1024, timeout: Double = 30.0, model: String? = null, audio: ByteArray? = null,
+ audioType: String = "audio/wav",
): String {
val k = key.read() ?: throw LingException(LingException.Kind.NoKey)
if (keyState == KeyState.Invalid) throw LingException(LingException.Kind.InvalidKey)
val user: Any = if (audio == null) instruction else listOf(
- mapOf("type" to "audio_url", "audio_url" to mapOf("url" to "data:audio/wav;base64," + Base64.getEncoder().encodeToString(audio))),
+ mapOf("type" to "audio_url", "audio_url" to mapOf("url" to "data:$audioType;base64," + Base64.getEncoder().encodeToString(audio))),
mapOf("type" to "text", "text" to instruction),
)
val body = linkedMapOf<String, Any?>(
diff --git a/android/core/src/main/kotlin/cicada/ListenEngine.kt b/android/core/src/main/kotlin/cicada/ListenEngine.kt
index 4e94134..68d4a94 100644
--- a/android/core/src/main/kotlin/cicada/ListenEngine.kt
+++ b/android/core/src/main/kotlin/cicada/ListenEngine.kt
@@ -51,6 +51,10 @@ class ListenEngine(
/// The loudest recent level: 0 for a while means the source is silent (e.g. an app that blocks capture).
@Volatile var peak = 0.0; private set
+ /// Compresses a segment before upload (the app sets AAC: WAV is ~10x larger, ~146 MB an hour
+ /// of speech on mobile data). Null or a throw falls back to WAV, which Ming always takes.
+ @Volatile var encoder: (ShortArray) -> Clip? = { null }
+
init { translator.glossary = { notes.glossary() } }
fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
@@ -119,15 +123,21 @@ class ListenEngine(
pool.execute { notes.finish() }
}
+ private fun encode(pcm: ShortArray): Clip {
+ val clip = try { encoder(pcm) } catch (e: Exception) { Log.d("listen: encode failed ${e.message}"); null }
+ if (clip == null || clip.bytes.isEmpty()) return Clip.wav(pcm)
+ return clip
+ }
+
private fun send(seg: Segment) {
- val wav = Wav.bytes(seg.samples)
val lang = synchronized(gate) { segments[seg.index] = seg; hint }
changed()
val future = pool.submit {
var heard: Heard? = null
val started = System.currentTimeMillis()
try {
- heard = translator.hear(wav, target, lang)
+ val clip = encode(seg.samples)
+ heard = translator.hear(clip, target, lang)
problem = null
} catch (e: LingException) {
problem = when (e.kind) {
diff --git a/android/core/src/main/kotlin/cicada/Translator.kt b/android/core/src/main/kotlin/cicada/Translator.kt
index 5f84c8b..1f23f9c 100644
--- a/android/core/src/main/kotlin/cicada/Translator.kt
+++ b/android/core/src/main/kotlin/cicada/Translator.kt
@@ -16,12 +16,13 @@ class Translator(private val ling: LingClient, private val transport: Transport
// MARK: Hearing
- /// One stretch of speech (16 kHz mono WAV) heard and interpreted. `hint` is the language the
+ /// One stretch of speech (16 kHz mono, WAV or compressed) heard and interpreted. `hint` is the language the
/// meeting has been in, which keeps Ming from flipping on a short or accented stretch. Null
/// when there was no speech or the reply wasn't in the three-line form; never a guess.
- fun hear(wav: ByteArray, target: String, hint: String?): Heard? {
+ fun hear(clip: Clip, target: String, hint: String?): Heard? {
val reply = ling.chat(hearPrompt(target, hint, glossary()), hearInstruction(target), Priority.Translate,
- maxTokens = 800, timeout = 12.0, model = LingClient.AUDIO_MODEL, audio = wav)
+ maxTokens = 800, timeout = 12.0, model = LingClient.AUDIO_MODEL,
+ audio = clip.bytes, audioType = clip.type)
return parseHeard(reply, target, hint)
}