M0-M2: LAN voice Android client skeleton + WSS protocol + audio pipeline

- M0: Gradle scaffold (AGP 8.5.2 / Kotlin 2.0.20 / Compose BOM 2024.09.03), arm64-v8a, minSdk 26
- M1: OkHttp WebSocket client, LV binary frame codec, connection generation guard, cert pinning
- M2: AudioRecord capture (16k PCM16 20ms), AudioTrack playback (48k), barge-in, RECORD_AUDIO
- Server address in res/values/config.xml; persona/lore resolved server-side
- PLAN.md with milestones and decisions
This commit is contained in:
zenord
2026-10-11 08:19:31 +08:00
commit 07d5f77808
22 changed files with 4116 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:label="@string/app_name"
android:theme="@android:style/Theme.Material.NoActionBar"
android:supportsRtl="true"
android:usesCleartextTraffic="false"
android:networkSecurityConfig="@xml/network_security_config">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,147 @@
package com.gorios.lanvoice
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.gorios.lanvoice.audio.AecAvailability
import com.gorios.lanvoice.audio.VoicePhase
import com.gorios.lanvoice.audio.VoiceSession
import com.gorios.lanvoice.audio.VoiceUiState
import com.gorios.lanvoice.net.ConnectionStatus
class MainActivity : ComponentActivity() {
private var state by mutableStateOf(VoiceUiState())
private lateinit var session: VoiceSession
private var pendingStart = false
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val shouldStart = pendingStart
pendingStart = false
if (granted && shouldStart) session.startVoice()
else if (!granted) session.permissionDenied()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
session = VoiceSession(
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
onState = { state = it },
)
setContent { Home(state, ::toggleVoice, session::interrupt) }
}
private fun toggleVoice() {
if (state.voiceActive) {
pendingStart = false
session.stopVoice()
} else if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
session.startVoice()
} else if (!pendingStart) {
pendingStart = true
microphonePermission.launch(Manifest.permission.RECORD_AUDIO)
}
}
override fun onStart() {
super.onStart()
session.foreground()
}
override fun onStop() {
pendingStart = false
session.background()
super.onStop()
}
override fun onDestroy() {
session.release()
super.onDestroy()
}
}
@Composable
fun Home(state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit) {
val gold = Color(0xFFE8C884)
val muted = Color(0xFF9CA3AF)
val connected = state.connection == ConnectionStatus.CONNECTED
Box(Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp)) {
Text(
text = when (state.connection) {
ConnectionStatus.DISCONNECTED -> "已断开"
ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用"
ConnectionStatus.CONNECTED -> when (state.phase) {
VoicePhase.IDLE -> "已连接"
VoicePhase.LISTENING -> "听取中"
VoicePhase.RECOGNIZING -> "识别中"
VoicePhase.THINKING -> "思考中"
VoicePhase.ANSWERING -> "回答中"
}
},
color = if (connected) gold else muted,
fontSize = 14.sp,
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp)
.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 20.dp, vertical = 10.dp)
)
Column(
modifier = Modifier.align(Alignment.Center).padding(bottom = 180.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("声伴", color = gold, fontSize = 44.sp)
Text("角色与音色由服务端决定", color = muted, modifier = Modifier.padding(top = 16.dp))
}
Column(
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
state.guidance?.let {
Text(it, color = gold, fontSize = 14.sp, textAlign = TextAlign.Center)
}
Button(
onClick = onToggleVoice,
enabled = connected,
shape = CircleShape,
colors = ButtonDefaults.buttonColors(containerColor = gold, contentColor = Color(0xFF121220)),
modifier = Modifier.size(140.dp),
) {
Text(if (state.voiceActive) "停止" else "开始\n语音对话", fontSize = 20.sp, textAlign = TextAlign.Center)
}
Button(onClick = onInterrupt, enabled = connected && state.voiceActive) {
Text("打断")
}
Text(
"AEC:" + when (state.aec) {
AecAvailability.AVAILABLE -> "可用"
AecAvailability.UNAVAILABLE -> "不可用"
AecAvailability.UNKNOWN -> "未知"
} + " · 实际消回声效果需真机验证",
color = muted, fontSize = 12.sp, textAlign = TextAlign.Center,
)
}
}
}
@@ -0,0 +1,110 @@
package com.gorios.lanvoice.audio
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.media.audiofx.AcousticEchoCanceler
import android.os.Process
enum class AecAvailability { AVAILABLE, UNAVAILABLE, UNKNOWN }
/** A recorder and effect belong to one run; a stopped worker cannot reuse a new run's device. */
class AudioCapture {
private class Run {
@Volatile var active = true
var recorder: AudioRecord? = null
}
private val lock = Any()
private var current: Run? = null
fun aecAvailability(): AecAvailability = try {
if (AcousticEchoCanceler.isAvailable()) AecAvailability.AVAILABLE else AecAvailability.UNAVAILABLE
} catch (_: Exception) {
AecAvailability.UNKNOWN
}
/** The caller must obtain RECORD_AUDIO permission before starting. Callbacks run off main. */
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit) {
stop()
val run = Run()
synchronized(lock) { current = run }
Thread({ record(run, onFrame, onError) }, "lan-voice-capture").apply {
isDaemon = true
start()
}
}
fun stop() {
synchronized(lock) {
val run = current ?: return
current = null
run.active = false
// Unblock a READ_BLOCKING call; release is exclusively the worker's responsibility.
try { run.recorder?.stop() } catch (_: IllegalStateException) { }
}
}
private fun record(run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit) {
var recorder: AudioRecord? = null
var aec: AcousticEchoCanceler? = null
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO)
val minimum = AudioRecord.getMinBufferSize(
16_000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
)
check(minimum > 0) { "16k mono PCM16 recording is unavailable" }
val device = AudioRecord(
MediaRecorder.AudioSource.VOICE_COMMUNICATION, 16_000,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
maxOf(minimum * 2, FRAME_BYTES * 2)
)
recorder = device
check(device.state == AudioRecord.STATE_INITIALIZED) { "AudioRecord initialization failed" }
// Availability is reported separately; creating/enabling an effect is best effort.
if (aecAvailability() == AecAvailability.AVAILABLE) {
try {
aec = AcousticEchoCanceler.create(device.audioSessionId)
aec?.setEnabled(true)
} catch (_: Exception) { /* The UI never promises effective echo cancellation. */ }
}
synchronized(lock) {
if (!run.active || current !== run) return
run.recorder = device
device.startRecording()
check(device.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "Recording did not start" }
}
val frame = ByteArray(FRAME_BYTES)
var filled = 0
while (run.active) {
val read = device.read(frame, filled, frame.size - filled, AudioRecord.READ_BLOCKING)
if (!run.active) break
check(read >= 0) { "AudioRecord read failed: $read" }
if (read == 0) {
Thread.sleep(2)
continue
}
filled += read
if (filled == frame.size) {
onFrame(frame.copyOf())
filled = 0
}
}
} catch (error: Exception) {
if (run.active) onError(error)
} finally {
synchronized(lock) {
run.active = false
run.recorder = null
if (current === run) current = null
}
aec?.release()
recorder?.let {
try { it.stop() } catch (_: IllegalStateException) { }
it.release()
}
}
}
companion object { const val FRAME_BYTES = 640 }
}
@@ -0,0 +1,195 @@
package com.gorios.lanvoice.audio
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import android.os.Process
import com.gorios.lanvoice.net.DownlinkFrame
import java.util.ArrayDeque
/** Nonblocking native writes keep pause+flush independent of a potentially full audio buffer. */
class AudioPlayback(
private val onDrained: (turnId: Long, generation: Long) -> Unit,
private val onError: (generation: Long, error: Exception) -> Unit,
) {
private val lock = Object()
private val queue = ArrayDeque<ByteArray>()
private var queuedBytes = 0
private var generation = 0L
private var turnId: Long? = null
private var ended = false
private var drained = false
private var writtenSamples = 0L
private var track: AudioTrack? = null
private var released = false
init {
Thread(::play, "lan-voice-playback").apply { isDaemon = true; start() }
}
fun beginTurn(id: Long) = synchronized(lock) {
if (!released && turnId != id) resetLocked(id)
}
fun enqueue(frame: DownlinkFrame): Boolean = synchronized(lock) {
if (released) return false
if (turnId != frame.turnId) resetLocked(frame.turnId)
if (ended || drained || queuedBytes + frame.pcm16.size > MAX_QUEUED_BYTES) return false
queue.addLast(frame.pcm16)
queuedBytes += frame.pcm16.size
lock.notifyAll()
true
}
/** Only an explicit TTS end event may arm playback.drained, never a temporary empty queue. */
fun endTurn(id: Long) = synchronized(lock) {
if (!released && turnId == id && !drained) {
ended = true
lock.notifyAll()
}
}
fun isCurrent(id: Long, epoch: Long): Boolean = synchronized(lock) {
!released && turnId == id && generation == epoch
}
fun isCurrent(epoch: Long): Boolean = synchronized(lock) { !released && generation == epoch }
fun interrupt() = synchronized(lock) { resetLocked(null) }
fun release() = synchronized(lock) {
if (!released) {
released = true
resetLocked(null)
}
}
private fun resetLocked(id: Long?) {
generation++
turnId = id
ended = false
drained = false
queue.clear()
queuedBytes = 0
writtenSamples = 0
track?.let {
try { it.pause(); it.flush() } catch (_: IllegalStateException) { }
}
lock.notifyAll()
}
private fun acquireTrack(epoch: Long): AudioTrack? {
synchronized(lock) {
if (released || generation != epoch) return null
track?.let {
if (it.playState != AudioTrack.PLAYSTATE_PLAYING) it.play()
return it
}
}
val minimum = AudioTrack.getMinBufferSize(
48_000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT
)
check(minimum > 0) { "48k mono PCM16 playback is unavailable" }
val device = AudioTrack.Builder()
.setAudioAttributes(AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
.setAudioFormat(AudioFormat.Builder().setSampleRate(48_000)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT).build())
.setTransferMode(AudioTrack.MODE_STREAM)
.setBufferSizeInBytes(minimum * 2)
.build()
if (device.state != AudioTrack.STATE_INITIALIZED) {
device.release()
error("AudioTrack initialization failed")
}
synchronized(lock) {
if (released || generation != epoch) {
device.release()
return null
}
track = device
device.play()
return device
}
}
private fun play() {
try {
try { Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO) } catch (_: SecurityException) { }
while (true) {
val epoch: Long
val id: Long
val chunk: ByteArray?
synchronized(lock) {
while (!released && (turnId == null || (queue.isEmpty() && (!ended || drained)))) {
lock.wait()
}
if (released) return
epoch = generation
id = checkNotNull(turnId)
chunk = queue.pollFirst()
if (chunk != null) queuedBytes -= chunk.size
}
try {
if (chunk != null) {
val device = acquireTrack(epoch) ?: continue
var offset = 0
while (offset < chunk.size) {
val written = synchronized(lock) {
if (released || generation != epoch) null else
device.write(chunk, offset, chunk.size - offset, AudioTrack.WRITE_NON_BLOCKING)
.also { if (it > 0) writtenSamples += it / 2 }
} ?: break
check(written >= 0) { "AudioTrack write failed: $written" }
offset += written
if (written == 0) Thread.sleep(4)
}
} else {
val finished = synchronized(lock) {
if (released || generation != epoch || !ended || drained) false
else {
val device = track
// Some devices wait for the initial stream buffer to fill. For a
// very short completed utterance, append only enough silence to
// start it; include that tail in the native drain count.
if (device != null && writtenSamples > 0 &&
writtenSamples < device.bufferSizeInFrames) {
val padding = ByteArray((device.bufferSizeInFrames - writtenSamples.toInt()) * 2)
val written = device.write(padding, 0, padding.size, AudioTrack.WRITE_NON_BLOCKING)
check(written >= 0) { "AudioTrack tail write failed: $written" }
writtenSamples += written / 2
}
val played = device?.playbackHeadPosition?.toLong()?.and(0xffff_ffffL) ?: 0L
val primed = device == null || writtenSamples == 0L || writtenSamples >= device.bufferSizeInFrames
if (primed && played >= writtenSamples) {
device?.pause()
drained = true
true
} else false
}
}
if (finished) onDrained(id, epoch) else Thread.sleep(5)
}
} catch (error: Exception) {
val failedTrack = synchronized(lock) {
if (released || generation != epoch) null else {
queue.clear()
queuedBytes = 0
ended = false
track.also { track = null }
}
}
failedTrack?.release()
if (isCurrent(epoch)) onError(epoch, error)
}
}
} finally {
val device = synchronized(lock) { track.also { track = null } }
device?.release()
}
}
companion object { private const val MAX_QUEUED_BYTES = 48_000 * 2 * 30 }
}
@@ -0,0 +1,254 @@
package com.gorios.lanvoice.audio
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.gorios.lanvoice.net.ConnectionStatus
import com.gorios.lanvoice.net.DialogueClient
import com.gorios.lanvoice.net.DownlinkFrame
import com.gorios.lanvoice.net.EventKind
import com.gorios.lanvoice.net.ServerEvent
enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING }
data class VoiceUiState(
val connection: ConnectionStatus = ConnectionStatus.DISCONNECTED,
val phase: VoicePhase = VoicePhase.IDLE,
val voiceActive: Boolean = false,
val aec: AecAvailability = AecAvailability.UNKNOWN,
val guidance: String? = null,
)
/** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */
class VoiceSession(host: String, port: Int, private val onState: (VoiceUiState) -> Unit) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
private var foreground = false
private var released = false
private var captureEpoch = 0L
private var capturing = false
private var currentTurn = 0L
private var hasTurn = false
private val retiredTurns = mutableSetOf<Long>()
private var blockedTurn: Long? = null
private var sequence = 0L
private val capture = AudioCapture()
private val playback: AudioPlayback = AudioPlayback(
onDrained = { turn, epoch ->
main.post {
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
if (dialogue.playbackDrained(turn)) {
update(state.copy(phase = VoicePhase.LISTENING))
startCapture()
}
}
}
},
onError = { epoch, error ->
main.post {
if (isActive() && playbackIsCurrent(epoch)) failAudio("无法播放音频,请重新开始语音对话", error)
}
},
)
private val dialogue: DialogueClient = DialogueClient(
host, port,
onStatus = ::onConnection,
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
)
fun foreground() {
checkMainThread()
if (released) return
foreground = true
update(state.copy(aec = capture.aecAvailability()))
dialogue.connect()
}
fun background() {
checkMainThread()
foreground = false
stopVoice(sendControls = false)
dialogue.disconnect()
}
fun release() {
checkMainThread()
if (released) return
background()
released = true
playback.release()
dialogue.release()
}
/** Activity verifies runtime permission first; capture still handles permission revocation. */
fun startVoice() {
checkMainThread()
if (released || !foreground || state.connection != ConnectionStatus.CONNECTED || state.voiceActive) return
if (!dialogue.listen(true)) return
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null))
startCapture()
}
fun stopVoice(sendControls: Boolean = true) {
checkMainThread()
val wasActive = state.voiceActive
stopCapture()
playback.interrupt()
blockedTurn = currentTurn
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE))
if (sendControls && wasActive && state.connection == ConnectionStatus.CONNECTED) {
dialogue.listen(false)
dialogue.abort(currentTurn)
}
}
fun interrupt() {
checkMainThread()
if (!isActive()) return
blockedTurn = currentTurn
playback.interrupt() // Silence locally before waiting for the server's abort event.
if (dialogue.abort(currentTurn)) {
update(state.copy(phase = VoicePhase.LISTENING))
startCapture()
}
}
fun permissionDenied() {
checkMainThread()
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
}
private fun onConnection(connection: ConnectionStatus) {
if (connection != ConnectionStatus.CONNECTED) {
stopCapture()
playback.interrupt()
currentTurn = 0
hasTurn = false
retiredTurns.clear()
blockedTurn = null
sequence = 0
update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE))
} else update(state.copy(connection = connection, guidance = null))
}
private fun startCapture() {
if (!isActive() || capturing) return
capturing = true
val epoch = ++captureEpoch
capture.start(
onFrame = { pcm ->
main.post {
if (epoch == captureEpoch && capturing && isActive()) {
if (dialogue.sendAudio(pcm, currentTurn, sequence)) {
sequence = (sequence + 1) and UINT32_MASK
}
}
}
},
onError = { error ->
main.post {
if (epoch == captureEpoch && isActive()) failAudio("无法录音,请检查麦克风权限后重新开始", error)
}
},
)
}
private fun stopCapture() {
captureEpoch++
capturing = false
capture.stop()
}
private fun onEvent(event: ServerEvent) {
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
if (turn != null && !acceptTurn(turn)) return
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
when (event.kind) {
EventKind.LISTEN -> if (isActive()) {
when (action) {
"start" -> {
update(state.copy(phase = VoicePhase.LISTENING))
startCapture()
}
"stop" -> {
stopCapture()
update(state.copy(phase = VoicePhase.RECOGNIZING))
}
}
}
EventKind.VAD -> if (isActive()) {
update(state.copy(phase = if (action in setOf("end", "stop", "speech_end"))
VoicePhase.RECOGNIZING else VoicePhase.LISTENING))
}
EventKind.STT -> if (isActive()) {
update(state.copy(phase = if (action in setOf("partial", "start"))
VoicePhase.RECOGNIZING else VoicePhase.THINKING))
}
EventKind.LLM -> if (isActive() && state.phase != VoicePhase.ANSWERING) {
update(state.copy(phase = VoicePhase.THINKING))
}
EventKind.TTS -> if (isActive() && blockedTurn != currentTurn) {
playback.beginTurn(currentTurn)
update(state.copy(phase = VoicePhase.ANSWERING))
if (action in setOf("stop", "done", "end")) playback.endTurn(currentTurn)
}
EventKind.ABORT -> {
blockedTurn = currentTurn
playback.interrupt()
if (isActive()) {
update(state.copy(phase = VoicePhase.LISTENING))
startCapture()
}
}
EventKind.ERROR -> if (state.voiceActive) {
stopVoice()
update(state.copy(guidance = "服务端处理失败,请重新开始语音对话"))
}
else -> Unit
}
}
private fun onFrame(frame: DownlinkFrame) {
if (!isActive() || !acceptTurn(frame.turnId) || blockedTurn == frame.turnId) return
update(state.copy(phase = VoicePhase.ANSWERING))
if (!playback.enqueue(frame)) {
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
}
}
private fun acceptTurn(id: Long): Boolean {
if (id !in 0..UINT32_MASK) return false
// IDs identify turns; do not assume the server allocates them in numeric order.
if (id in retiredTurns) return false
if (!hasTurn || id != currentTurn) {
if (hasTurn) retiredTurns.add(currentTurn)
playback.interrupt()
currentTurn = id
hasTurn = true
sequence = 0
if (blockedTurn != id) blockedTurn = null
}
return true
}
private fun failAudio(message: String, error: Exception) {
Log.w(TAG, message, error)
stopVoice()
update(state.copy(guidance = message))
}
private fun playbackIsCurrent(turn: Long, epoch: Long): Boolean = playback.isCurrent(turn, epoch)
private fun playbackIsCurrent(epoch: Long): Boolean = playback.isCurrent(epoch)
private fun isActive() = !released && foreground && state.voiceActive && state.connection == ConnectionStatus.CONNECTED
private fun update(next: VoiceUiState) { state = next; onState(next) }
private fun checkMainThread() {
check(Looper.myLooper() === main.looper) { "VoiceSession must be used on main" }
}
companion object {
private const val TAG = "LanVoice"
private const val UINT32_MASK = 0xffff_ffffL
}
}
@@ -0,0 +1,171 @@
package com.gorios.lanvoice.net
import android.os.Handler
import android.os.Looper
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.util.concurrent.TimeUnit
enum class ConnectionStatus { CONNECTED, DISCONNECTED, BUSY }
/**
* Owned by the main thread. All socket callbacks cross the same main-thread generation gate,
* including callbacks already queued when connect/disconnect replaces the current socket.
* No automatic reconnect: foreground entry starts a fresh session; 1013 stays visible.
*/
class DialogueClient(
host: String,
port: Int,
private val onStatus: (ConnectionStatus) -> Unit,
private val onEvent: (ServerEvent) -> Unit = {},
private val onFrame: (DownlinkFrame) -> Unit = {},
private val onProtocolError: (String) -> Unit = {},
) {
private val main = Handler(Looper.getMainLooper())
private val endpoint = HttpUrl.Builder()
.scheme("https").host(host).port(port).addPathSegments("ws/dialogue").build()
private val request = Request.Builder()
.url(endpoint.toString().replaceFirst("https://", "wss://"))
.header("Origin", "https://${endpoint.host.let { if (':' in it) "[$it]" else it }}:${endpoint.port}")
.build()
// OkHttp sends RFC 6455 ping frames, replies to ping with pong automatically, and fails a
// connection whose pong is absent at the next interval. No timer survives disconnect.
private val client = OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false)
.pingInterval(20, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.build()
private var generation = 0L
private var socket: WebSocket? = null
private var released = false
private var ready = false
fun connect() {
checkMainThread()
check(!released) { "DialogueClient has been released" }
generation++
ready = false
socket?.cancel()
socket = null
onStatus(ConnectionStatus.DISCONNECTED)
socket = client.newWebSocket(request, listener(generation))
}
fun disconnect() {
checkMainThread()
generation++ // Invalidate before cancellation can trigger onFailure.
ready = false
val previous = socket
socket = null
previous?.cancel()
onStatus(ConnectionStatus.DISCONNECTED)
}
fun release() {
checkMainThread()
if (released) return
disconnect()
released = true
client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()
}
fun listen(start: Boolean): Boolean = send(DialogueProtocol.listen(start))
fun abort(turnId: Long): Boolean = send(DialogueProtocol.abort(turnId))
fun playbackDrained(turnId: Long): Boolean = send(DialogueProtocol.playbackDrained(turnId))
fun sendAudio(pcm16: ByteArray, turnId: Long, sequence: Long): Boolean {
checkMainThread()
val current = socket ?: return false
if (!ready || released) return false
// Bound microphone latency rather than silently buffering many seconds of stale speech.
if (current.queueSize() > 64 * 1024 ||
!current.send(ByteString.of(*DialogueProtocol.uplink(pcm16, turnId, sequence)))) {
finish(current, ConnectionStatus.DISCONNECTED)
return false
}
return true
}
private fun send(text: String): Boolean {
checkMainThread()
val current = socket ?: return false
if (!ready || released) return false
if (current.send(text)) return true
finish(current, ConnectionStatus.DISCONNECTED)
return false
}
private fun listener(attempt: Long) = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
if (webSocket.send(DialogueProtocol.hello())) {
ready = true
onStatus(ConnectionStatus.CONNECTED)
} else {
finish(webSocket, ConnectionStatus.DISCONNECTED)
}
}
override fun onMessage(webSocket: WebSocket, text: String) = dispatch(attempt, webSocket) {
val event = try {
DialogueProtocol.parseEvent(text)
} catch (error: Exception) {
onProtocolError(error.message ?: "Invalid JSON event")
return@dispatch
}
onEvent(event)
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) = dispatch(attempt, webSocket) {
val frame = try {
DialogueProtocol.parseDownlink(bytes.toByteArray())
} catch (error: IllegalArgumentException) {
onProtocolError(error.message ?: "Invalid binary frame")
return@dispatch
}
onFrame(frame)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
finish(webSocket, statusFor(code))
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
finish(webSocket, statusFor(code))
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
}
}
private fun dispatch(attempt: Long, webSocket: WebSocket, action: () -> Unit) {
main.post {
if (generation == attempt && socket === webSocket && !released) action()
}
}
private fun finish(webSocket: WebSocket, status: ConnectionStatus) {
// Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status.
socket = null
ready = false
webSocket.cancel()
onStatus(status)
}
private fun statusFor(code: Int) =
if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED
private fun checkMainThread() {
check(Looper.myLooper() === main.looper) { "DialogueClient must be used on the main thread" }
}
}
@@ -0,0 +1,103 @@
package com.gorios.lanvoice.net
import org.json.JSONObject
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Wire payloads stay intact: event-specific fields are consumed by later milestones. */
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
enum class EventKind {
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
}
/** Header integers are unsigned, network byte order; PCM samples are signed little endian. */
data class DownlinkFrame(val turnId: Long, val sequence: Long, val pcm16: ByteArray) {
val sampleRate: Int get() = 48_000
}
object DialogueProtocol {
const val HEADER_BYTES = 12
const val VERSION = 1
const val UPLINK = 1
const val DOWNLINK = 2
const val UPLINK_PCM_BYTES = 640
const val DOWNLINK_PCM_BYTES = 1_920
fun hello(): String = JSONObject()
.put("type", "hello")
.put("codec", "pcm16")
.put("sample_rate", 16_000)
.put("frame_duration", 20)
.put("persona", "default")
.put("voice_mode", "continuous_voice")
.toString()
fun listen(start: Boolean): String = JSONObject()
.put("type", "listen")
.put("state", if (start) "start" else "stop")
.apply {
if (start) {
put("mode", "auto")
put("barge_in", true)
}
}.toString()
fun abort(turnId: Long): String = JSONObject()
.put("type", "abort").put("turn_id", turnId).toString()
fun playbackDrained(turnId: Long): String = JSONObject()
.put("type", "playback.drained").put("turn_id", turnId).toString()
fun uplink(pcm16: ByteArray, turnId: Long, sequence: Long): ByteArray {
require(pcm16.size == UPLINK_PCM_BYTES) { "Expected 20 ms of PCM16@16k" }
require(turnId in 0..0xffff_ffffL && sequence in 0..0xffff_ffffL) {
"Frame IDs must be uint32"
}
return ByteBuffer.allocate(HEADER_BYTES + pcm16.size).order(ByteOrder.BIG_ENDIAN)
.put('L'.code.toByte()).put('V'.code.toByte()).put(VERSION.toByte())
.put(UPLINK.toByte()).putInt(turnId.toInt()).putInt(sequence.toInt())
.put(pcm16).array()
}
fun parseEvent(text: String): ServerEvent {
val payload = JSONObject(text)
val type = payload.opt("type") as? String
require(!type.isNullOrBlank()) { "Event is missing a string type" }
val kind = when (type.substringBefore('.')) {
"auth" -> EventKind.AUTH
"hello" -> EventKind.HELLO
"history" -> EventKind.HISTORY
"listen" -> EventKind.LISTEN
"vad" -> EventKind.VAD
"stt" -> EventKind.STT
"llm" -> EventKind.LLM
"tts" -> EventKind.TTS
"error" -> EventKind.ERROR
"abort" -> EventKind.ABORT
"metrics" -> EventKind.METRICS
"ping" -> EventKind.PING
"pong" -> EventKind.PONG
else -> EventKind.UNKNOWN
}
return ServerEvent(type, kind, payload)
}
fun parseDownlink(bytes: ByteArray): DownlinkFrame {
require(bytes.size > HEADER_BYTES) { "Missing PCM payload" }
require(bytes[0] == 'L'.code.toByte() && bytes[1] == 'V'.code.toByte()) {
"Invalid LV magic"
}
require(bytes[2].toInt() == VERSION) { "Unsupported frame version" }
require(bytes[3].toInt() == DOWNLINK) { "Expected a downlink frame" }
val pcmBytes = bytes.size - HEADER_BYTES
// A final TTS chunk may be shorter than 20 ms, but must contain whole samples.
require(pcmBytes <= DOWNLINK_PCM_BYTES && pcmBytes % 2 == 0) {
"Invalid PCM16 payload length"
}
val header = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN)
val turnId = header.getInt(4).toLong() and 0xffff_ffffL
val sequence = header.getInt(8).toLong() and 0xffff_ffffL
return DownlinkFrame(turnId, sequence, bytes.copyOfRange(HEADER_BYTES, bytes.size))
}
}
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Build template: generated into res/xml using values/config.xml. -->
<network-security-config>
<!-- No system/user roots and no debug override. The gateway certificate is required. -->
<base-config cleartextTrafficPermitted="false">
<trust-anchors>
<certificates src="@raw/gateway_cert" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="false">@VOICE_SERVER_HOST@</domain>
<trust-anchors>
<certificates src="@raw/gateway_cert" />
</trust-anchors>
</domain-config>
</network-security-config>
+20
View File
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDNzCCAh+gAwIBAgIUNb+LPM2IuTsKiIgQofZlOzFxMQ8wDQYJKoZIhvcNAQEL
BQAwGjEYMBYGA1UEAwwPbGFuLXZvaWNlLmxvY2FsMB4XDTI2MTAwOTEwNDcyNVoX
DTI3MTAwOTEwNDcyNVowGjEYMBYGA1UEAwwPbGFuLXZvaWNlLmxvY2FsMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3txyC4cNInEky/aPagMaLnyOzSM9
BeyQ9k4tAE5XtF0db7ICQw4ce5IrlqnXNlW3p7hV/7kMmejktST9W/0ThBIsim4e
F0MYjQVOhYqvzRr9Rw1mnHlwyLl2B3P6hRDAAWStm7IXoRxVoc+xZrfRm8vw9LVQ
V7OKDOMLA7zAER5dE84bx91lG+G5C+XkDV4gZ3DqNMUGxOLKcBnkAxGjzA1ylFEL
h4kS6uAueuHJOTOhqtFAZKnXv5RFjuqp6BH1VASBoiMRxP/nR2/0hJwwKXF7oqpv
pAeL0BVTWuz+jH4il2miYMj6VlrR4RPKOdyknWYv2Tlefcq+5fyUw7xOiwIDAQAB
o3UwczAdBgNVHQ4EFgQU1jb5gTOEiaRiQT7asBU8vc9Ug8YwHwYDVR0jBBgwFoAU
1jb5gTOEiaRiQT7asBU8vc9Ug8YwDwYDVR0TAQH/BAUwAwEB/zAgBgNVHREEGTAX
hwTAqB89hwR/AAABgglsb2NhbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAAI2yCpq
mVdIu9iJnORJ8BJa/swJlmDFmBK07Wxe5PM9BSmhaVKpIgfVPx7oRvCUnrF+E1wy
eia5Sm3wMqUsu6eaz32IHkuH4pE9euZMQQ/jZh4mSNmx33kUZXlf/xVHJU/tfkLC
q9f9raTLxWyM1JMTf2hLc3pOm6RoFJ6yFWP1uuAQC991/nL1oUjOje2CUt3YtUU+
sdLKSM8LGnn2csUUIkr8MQeekgOJwKVM9P1fKGbjivr119/VBiGPW0ZdKnaqvUeN
4dsedHiLtdOg6cCUQpT+YurRg/ElCNRJTLfD8/8BTFdlBigMGs+yRskUMDOGZiVh
b6Siq7zlkEch4WE=
-----END CERTIFICATE-----
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="voice_server_host" translatable="false">192.168.31.61</string>
<integer name="voice_server_port">5011</integer>
</resources>
+2
View File
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<resources><string name="app_name">声伴</string></resources>