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:
@@ -0,0 +1,8 @@
|
||||
.gradle/
|
||||
app/build/
|
||||
build/
|
||||
local.properties
|
||||
*.apk
|
||||
*.keystore
|
||||
logs/
|
||||
artifacts/
|
||||
@@ -0,0 +1,51 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
id 'org.jetbrains.kotlin.android'
|
||||
id 'org.jetbrains.kotlin.plugin.compose'
|
||||
}
|
||||
|
||||
// Android's <domain> text cannot reference @string. Generate it from the one address config
|
||||
// so changing voice_server_host and rebuilding also updates the certificate trust scope.
|
||||
def networkSecurityResources = layout.buildDirectory.dir('generated/networkSecurity/res')
|
||||
def generateNetworkSecurityConfig = tasks.register('generateNetworkSecurityConfig') {
|
||||
def serverConfig = file('src/main/res/values/config.xml')
|
||||
def template = file('src/main/network_security_config.xml')
|
||||
inputs.files(serverConfig, template)
|
||||
outputs.dir(networkSecurityResources)
|
||||
doLast {
|
||||
def host = new XmlSlurper().parse(serverConfig).string.find {
|
||||
it.@name.text() == 'voice_server_host'
|
||||
}.text()
|
||||
if (!(host ==~ /[A-Za-z0-9.:-]+/)) {
|
||||
throw new GradleException('voice_server_host must be an IP address or DNS host')
|
||||
}
|
||||
def output = new File(networkSecurityResources.get().asFile, 'xml/network_security_config.xml')
|
||||
output.parentFile.mkdirs()
|
||||
output.setText(template.getText('UTF-8').replace('@VOICE_SERVER_HOST@', host), 'UTF-8')
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.gorios.lanvoice'
|
||||
compileSdk 34
|
||||
defaultConfig {
|
||||
applicationId 'com.gorios.lanvoice'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 1
|
||||
versionName '0.1.0-m2'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
kotlinOptions { jvmTarget = '17' }
|
||||
buildFeatures { compose true }
|
||||
sourceSets.main.res.srcDir(networkSecurityResources)
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig) }
|
||||
dependencies {
|
||||
implementation platform('androidx.compose:compose-bom:2024.09.03')
|
||||
implementation 'androidx.compose.ui:ui'
|
||||
implementation 'androidx.compose.material3:material3'
|
||||
implementation 'androidx.activity:activity-compose:1.9.3'
|
||||
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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-----
|
||||
@@ -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>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources><string name="app_name">声伴</string></resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
plugins {
|
||||
id 'com.android.application' version '8.5.2' apply false
|
||||
id 'org.jetbrains.kotlin.android' version '2.0.20' apply false
|
||||
id 'org.jetbrains.kotlin.plugin.compose' version '2.0.20' apply false
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
# lan-voice Android 客户端规划(KISS 版,决策已定)
|
||||
|
||||
日期:2026-10-10 · 构建机:Ubuntu 4090 · 服务端:SPARK-2 lan-voice(当前 v0.7.1,服务停止中,联调前需启动)
|
||||
项目:`/home/ubuntu/lan-voice-android` · Herdr workspace:`lan-voice-android` (wE)
|
||||
|
||||
## 0. 已定决策(2026-10-10 用户确认)
|
||||
|
||||
1. **APK 零输入鉴权**:不手动输 token、不用访客 Cookie。配套服务端改动:gateway 增加 **LAN 直连授权模式**——WS 连接来自允许网段(192.168.31.0/24 + loopback)即视为已授权,无 token 无 Cookie。仅可信 LAN,文档明示边界。原 Bearer/Cookie 通道保留用于管理/调试。
|
||||
2. **服务器地址写打包配置**:`app/src/main/res/values/config.xml`(host/port),改地址改配置重新打包,KISS。
|
||||
3. **APK 不存任何 lorebook/音色**:永远以 `persona=default` 连接。服务端配套:**active profile 文件**(如 `.runtime/active_profile.json`,含 persona rules + voice_id),hello 时读取并应用——后台改文件即换角色人格与 TTS 音色参考,APK 零改动。这是测试期最灵活的形态。
|
||||
4. 不预置吕布等其他角色。
|
||||
5. **KISS**:最小骨架起步,逐步累加特性;不做摄像头/表情、不做 Opus、不做后台监听。
|
||||
|
||||
## 1. 服务端配套改动(v0.8,M1 联调前完成,本次不动)
|
||||
|
||||
- `LAN_OPEN_MODE`(默认关,显式开启):WS 握手时 client IP ∈ 允许网段 → 直接授权,跳过 auth/hello 前置 token;owner 隔离简化为每连接独立新会话(无跨会话恢复需求时可更简)。
|
||||
- `active_profile`:persona=default 时读取 `.runtime/active_profile.json`(rules + voice_id,白名单校验 voice_id 必须已注册 active),文件不存在则回退当前 default 行为。后台换角色/音色 = 改文件 + 新连接生效。
|
||||
- 35 项回归保持通过;服务当前停止,改完再启动。
|
||||
|
||||
## 2. APK 结构与目录
|
||||
|
||||
```
|
||||
/home/ubuntu/lan-voice-android/
|
||||
├── settings.gradle / build.gradle / gradle.properties
|
||||
├── gradlew + gradle/wrapper/ # 复用 android-build 基线的 wrapper(Gradle 8.7, sha256 固定)
|
||||
├── app/
|
||||
│ ├── build.gradle # AGP 8.5.2 / Kotlin 2.0.20 / Compose,仅 arm64-v8a,minSdk 26 targetSdk 34
|
||||
│ └── src/main/
|
||||
│ ├── AndroidManifest.xml # M0 无权限;M2 加 RECORD_AUDIO + INTERNET
|
||||
│ ├── java/com/gorios/lanvoice/
|
||||
│ │ ├── MainActivity.kt # M0 占位壳;后续 ui/ net/ audio/ 分包渐进
|
||||
│ │ └── ...
|
||||
│ └── res/
|
||||
│ ├── values/strings.xml / config.xml # config.xml:voice_server_host / voice_server_port
|
||||
│ └── xml/network_security_config.xml # M1 加:仅信任打包的 gateway 证书
|
||||
├── docs/PLAN.md
|
||||
└── scripts/build.sh # source android-build/env.sh && ./gradlew assembleDebug,日志入 logs/
|
||||
```
|
||||
|
||||
构建环境复用 `/home/ubuntu/android-build/env.sh`(JDK17 / SDK34 / NDK r26b / Gradle 8.7 / AGP 8.5.2)。
|
||||
Compose/Kotlin 依赖首次构建需联网下载并 `--write-verification-metadata sha256` 记录(TOFU),之后离线可复现。
|
||||
|
||||
## 3. 协议复刻要点(M1/M2 实现时照此)
|
||||
|
||||
- `wss://<config host>:<port>/ws/dialogue`,OkHttp 需显式带 `Origin: https://<host>:<port>` 头(服务端白名单校验)。
|
||||
- LAN 直连模式下 hello 即首条消息:`codec=pcm16, sample_rate=16000, frame_duration=20, persona=default, voice_mode=continuous_voice`。
|
||||
- 二进制帧 12 字节头 `LV|ver1|dir|turn_id|seq`:上行 640B/20ms PCM16@16k;下行 1920B/20ms PCM16@48k。
|
||||
- 控制:`listen(start,auto,barge_in) / abort / playback.drained / ping`;事件:`hello/stt/llm/tts/abort/error/metrics`。
|
||||
- **busy 单会话锁**:被 1013 关闭时 UI 提示"另一设备正在使用"。
|
||||
- 连接代次保护(参照 v0.7.1 修复):旧 socket 回调不得污染新连接。
|
||||
- 证书:network_security_config 仅对配置 host 信任打包的 gateway-cert.pem。
|
||||
|
||||
## 4. 音频管线(M2)
|
||||
|
||||
- `AudioRecord` VOICE_COMMUNICATION,16k mono PCM16,20ms 帧;探测并如实显示 AEC 可用性。
|
||||
- `AudioTrack` STREAM,48k mono,小缓冲;abort/turn 切换立即 pause+flush。
|
||||
- 权限仅 RECORD_AUDIO + INTERNET,运行时申请。
|
||||
|
||||
## 5. 界面(Compose,深色暖金,对齐网页 v0.7,KISS)
|
||||
|
||||
- 单一对话页(无角色页——角色由服务端 default 决定):
|
||||
- 顶部状态胶囊:已连接/听取中/识别中/思考中/回答中/被占用/已断开;
|
||||
- 聊天气泡流(STT / LLM 文本,打断轮灰标);
|
||||
- 底部大圆形语音按钮 + 打断按钮 + 音量条。
|
||||
- 无设置页(config 打包固定)、无角色页、无 debug UI。后续需要再逐项加。
|
||||
|
||||
## 6. 里程碑
|
||||
|
||||
| M | 内容 | 验收 |
|
||||
|---|---|---|
|
||||
| M0 ✅ | Gradle 骨架 + Compose 占位壳,assembleDebug 通过,产物+sha256 归档 | 构建成功 |
|
||||
| M1 | 服务端 v0.8(LAN 直连 + active_profile)+ APK WSS/hello/状态显示 | 服务端收到 hello,history 返回 |
|
||||
| M2 | 采集/播放全链路 | 真机一轮对话(手机到货后) |
|
||||
| M3 | 双工 barge-in / abort / drained / 连接代次 | 打断即时停播 |
|
||||
| M4 | 聊天流 UI 完整化 | 走查 |
|
||||
| M5+ | 按需累加:debug 导出、指标页、表情线索(另行评估)等 | 逐项定 |
|
||||
|
||||
真机验收清单(手机到货):连接、两轮对话、打断、另一设备占用提示、锁屏/退后台行为、AEC 实际表现。
|
||||
|
||||
## 7. 边界
|
||||
|
||||
- 4090 无模拟器,不能运行 ARM64 APK;真机验证在手机到货后。
|
||||
- LAN 直连模式只适合可信局域网,不可公网暴露;README 明示。
|
||||
- 对话流沿用现有满意实现,本阶段不改服务端 ASR/LLM/TTS 链路。
|
||||
|
||||
## 8. M1 APK 实施记录(2026-10-11,尚未验收)
|
||||
|
||||
- 新增 `net/DialogueClient.kt`:OkHttp 4.12.0,配置地址的 WSS + 显式 Origin,连接成功立即发送 hello;20 秒 RFC 6455 ping/pong,未收到 pong 时由 OkHttp 终止连接。
|
||||
- 新增 `net/DialogueProtocol.kt`:hello 固定采用本规划参数;JSON 按 type 分类 auth/hello/history/listen/vad/stt/llm/tts/error/abort/metrics/ping/pong,并保留完整字段和未知事件;下行帧校验 LV/ver/dir/PCM 长度,提取无符号 turn_id/seq 和 PCM16@48k。无音频采集/播放。
|
||||
- 所有 socket 回调先入主线程,再同时检查连接代次和 socket 身份;更换连接/退出前台先作废旧代次。1013 显示“被占用 · 另一设备正在使用”,终止后的回调不能覆盖状态。不自动重连;重新进入前台建立新连接。
|
||||
- UI 仅增加顶部连接状态胶囊。Manifest 增加 INTERNET(M1 连接所需),不申请麦克风权限。
|
||||
- TLS 模板位于 `app/src/main/network_security_config.xml`;Gradle 从 `values/config.xml` 生成 `app/build/generated/networkSecurity/res/xml/network_security_config.xml` 的 host 域配置,默认与该域的信任根都仅为 `@raw/gateway_cert`,拒绝明文,不包含系统/用户 CA 或 debug override。客户端只连接配置地址,并禁止重定向;地址仍只在 config.xml 修改。
|
||||
- **证书未取回**:沙箱禁止 socket,SSH 到 `gorios-spark-2@192.168.31.61` 返回 `Operation not permitted`。真实证书需放入 `app/src/main/res/raw/gateway_cert.pem`;未生成替代证书,未放宽验证。缺少证书资源时不可打包。
|
||||
- **完整构建未通过**:已调用 `./scripts/build.sh`,原缓存锁因基线路径只读失败;改用 `/tmp/lan-voice-m1-gradle-home` 的缓存副本后,Gradle daemon 因本地 socket 被禁而无法启动。`--write-verification-metadata sha256 assembleDebug` 同样未执行到依赖解析,尚无新 verification-metadata 或 M1 APK。日志在 `logs/`,未修改 android-build 基线。
|
||||
- 有限验证:使用已有 Kotlin 2.0.20 编译器和 SDK34 的 android.jar 单独编译协议文件;JVM 检查通过,覆盖网络字节序无符号 ID、完整/短末帧、PCM 原样保留,以及缺头/空载荷/奇数长度/超长/错误 magic/version/direction。此检查不代表 Android/OkHttp/Compose 完整编译或真机联调通过。
|
||||
- 待环境可用后:取回并核对真实证书;通过 `./scripts/build.sh` 构建,再 `./scripts/build.sh --write-verification-metadata sha256 assembleDebug` 固化依赖,归档 M1 APK + SHA256。
|
||||
- 待服务端 v0.8 就绪后:验证 LAN 零输入鉴权、hello/history、default 的 active_profile、1013、ping/pong、断网/前后台/连接替换。服务端源码暂无法读取,hello 的 JSON 布局和二进制 `dir=1` / uint32 大端 / 最大 1920B(允许短末帧)需核对实际实现;PCM 样本保持原字节,播放留到 M2。
|
||||
|
||||
### M1 构建补跑记录(2026-10-11)
|
||||
|
||||
- 用户已提供真实 `app/src/main/res/raw/gateway_cert.pem`;本地 SHA256 核对一致:`4058a2668bc609d7849edc6aa09a3faebb8de9f1d63faf6453180b951c848fe5`。此前“证书未取回”阻塞已解除。
|
||||
- 已补跑 `./scripts/build.sh`,并 source 基线环境后执行 `./gradlew --write-verification-metadata sha256 assembleDebug`;两个命令仍在 wrapper 锁文件处失败,当前 agent 会话中的基线 Gradle 缓存仍为只读。
|
||||
- 通过构建脚本使用可写 `/tmp/lan-voice-m1-gradle-home` 副本重试,仍因 `java.net.SocketException: Operation not permitted` 无法启动 Gradle daemon。当前会话权限尚未恢复,未进入编译/依赖解析,未生成 M1 APK 或 verification-metadata;仍需恢复缓存写权限和 socket 权限后补跑。未修改基线或构建代码。
|
||||
|
||||
## 9. M1 APK 侧完成记录(2026-10-11)
|
||||
|
||||
APK 侧实现、编译及依赖校验元数据固化已完成。用户在外部 shell 完成构建,agent 已核对归档 APK 的 SHA256、文件大小和校验元数据;服务端 v0.8 配套及真机联调仍待验收。前述失败记录保留为沙箱内执行历史,产物状态以本节为准。
|
||||
|
||||
### 改动文件清单
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `app/build.gradle` | 新增 OkHttp 4.12.0;版本更新为 `0.1.0-m1`;从 config.xml 生成网络安全域配置 |
|
||||
| `app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt` | WSS/Origin/hello;主线程连接代次和 socket 身份检查;1013 状态;20 秒 ping/pong;前台连接的创建和释放 |
|
||||
| `app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt` | hello 序列化、JSON 事件分类与原始字段保留、12 字节头及下行 PCM16@48k 帧解析 |
|
||||
| `app/src/main/java/com/gorios/lanvoice/MainActivity.kt` | 顶部已连接/已断开/被占用胶囊;前后台连接生命周期 |
|
||||
| `app/src/main/AndroidManifest.xml` | INTERNET 权限;禁用明文;引用网络安全配置 |
|
||||
| `app/src/main/network_security_config.xml` | 网络安全配置模板,仅信任打包的 gateway 证书,无系统/用户 CA 或 debug override |
|
||||
| `app/src/main/res/values/config.xml` | 服务器 host 禁止翻译;host/port 仍是唯一地址配置入口 |
|
||||
| `app/src/main/res/raw/gateway_cert.pem` | SPARK-2 真实 gateway 证书,SHA256 已核对,见第 8 节补跑记录 |
|
||||
| `gradle/verification-metadata.xml` | 固化 OkHttp、Okio、Compose 等依赖的 SHA256 |
|
||||
| `docs/PLAN.md` | 追加实施、构建补跑及完成记录;已定决策保持不变 |
|
||||
|
||||
构建日志保存在 `logs/`;M1 APK 归档在 `artifacts/lan-voice-m1-arm64-debug.apk`。本阶段未实现 audio/、设置页或角色页。
|
||||
|
||||
### 构建结果与沙箱限制
|
||||
|
||||
- 外部 shell 执行 `./scripts/build.sh`,`assembleDebug` 通过;加载 `/home/ubuntu/android-build/env.sh` 后执行 `./gradlew --write-verification-metadata sha256 assembleDebug`,依赖校验元数据生成成功。
|
||||
- APK:`artifacts/lan-voice-m1-arm64-debug.apk`,arm64 debug,大小 **9,225,842 字节(约 9.2 MB)**。
|
||||
- APK SHA256:`43b740d46bdac9819c3dedc107d9ea4e7121cfd7ab29a4bbdfc47d29c8010772`,agent 本地核对一致。
|
||||
- `gradle/verification-metadata.xml` 已存在,agent 确认包含 OkHttp 4.12.0、Okio 和 Compose 的校验记录。
|
||||
- 当前 agent 沙箱将 `/home/ubuntu/android-build/gradle-home` 设为只读,wrapper 无法创建缓存锁;使用可写临时缓存后,socket 禁止仍阻止 Gradle daemon 启动。**在当前沙箱限制下,完整构建和依赖下载/固化需由外部 shell 执行**,构建继续使用指定脚本和基线环境,不修改 android-build 基线。外部构建成功不代表 agent 沙箱权限已恢复。
|
||||
|
||||
### 待联调项
|
||||
|
||||
- 服务端 v0.8 的 LAN 直连授权及 active_profile 配套就绪、gateway 启动后,验证可信 LAN 的零输入鉴权、显式 Origin、hello 接收及 history 返回;核对 hello JSON 布局。
|
||||
- 验证 `persona=default` 应用 active_profile 的人格与音色,新连接读取更新后的配置。
|
||||
- 核对实际下行二进制协议:LV/ver1、dir、turn_id/seq 端序、48k PCM16 字节布局及帧/末帧长度;当前实现假设 dir=1、uint32 大端、最大 1920B 且允许短末帧。
|
||||
- 真机验证证书信任及主机名校验、连接/断开状态、另一设备占用时的 1013 提示、ping/pong 保活与断网检测。
|
||||
- 验证前后台切换、连接替换和断开后的迟到回调,确保旧 socket 的状态、JSON 事件及二进制帧均不能污染新连接。
|
||||
|
||||
本次停在 M1 APK 侧完成状态,等待下一步指令;音频管线继续留在 M2。
|
||||
|
||||
## 10. M2 APK 侧实施记录(2026-10-11,待外部构建与真机验收)
|
||||
|
||||
用户确认服务端 v0.8 已运行:LAN 直连授权开启,`persona=default` 由服务端映射到 active_profile(杨密及固定音色 `6f9683c3`);busy 在 WS 握手层返回 HTTP 403。APK 继续仅发送 default,不硬编码人格或音色。本节采用上行 direction=1、下行 direction=2,取代 M1 对下行方向的临时假设。
|
||||
|
||||
### 改动文件清单
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `app/src/main/java/com/gorios/lanvoice/audio/AudioCapture.kt` | VOICE_COMMUNICATION、16k mono PCM16、阻塞读取拼齐 640B/20ms;独立录音线程;停止及释放;AEC 三态探测,尝试创建并启用设备 AEC |
|
||||
| `app/src/main/java/com/gorios/lanvoice/audio/AudioPlayback.kt` | 48k mono PCM16 STREAM、约 2×minBuffer;非阻塞写入;abort/turn 切换 pause+flush 并清队列;依据实际播放头回报 drained |
|
||||
| `app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt` | 协调 listen、录音、播放和 UI 阶段;录音/播放代次检查;拒绝已退役/打断轮帧;停止及断线恢复按钮状态 |
|
||||
| `app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt` | 上行 direction=1 的 12B 头与 640B PCM 编码;下行改为 direction=2;listen、abort、playback.drained 控制 JSON |
|
||||
| `app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt` | 主线程控制和二进制发送接口;连接 ready 检查及上行积压限制;HTTP 403 映射为被占用,保留 1013 兼容 |
|
||||
| `app/src/main/java/com/gorios/lanvoice/MainActivity.kt` | RECORD_AUDIO 运行时申请与拒绝引导;底部大圆开始/停止按钮、打断按钮;听取/识别/思考/回答胶囊;AEC 可用/不可用/未知提示 |
|
||||
| `app/src/main/AndroidManifest.xml` | 增加 RECORD_AUDIO;权限仅 INTERNET 和 RECORD_AUDIO |
|
||||
| `app/build.gradle` | versionName 更新为 `0.1.0-m2`;无新增依赖 |
|
||||
| `docs/PLAN.md` | 追加 M2 实施记录,保留已定决策及历史记录 |
|
||||
| `logs/m2-source-check.log` / `logs/m2-protocol-check.log` | 缓存依赖源码编译与协议检查结果 |
|
||||
|
||||
### 实现决策
|
||||
|
||||
- “开始”先发 listen start,再启动采集;640B 帧在主线程使用最新 turn_id(服务端尚未提供时为 0),seq 在同轮内递增,切换轮时从 0 重新计数。listen stop 停止采集;用户停止时另发 abort 取消旧回答。运行中的语音会话在播放 drained 后恢复采集;收到服务端 listen stop 暂停采集,listen start 恢复采集。
|
||||
- 使用非阻塞 AudioTrack 写入,避免写线程因设备缓冲满而长时间占锁;打断/换轮立即 pause+flush,作废工作代次及待播数据。turn_id 只作为身份,不假设数值递增;当前连接保存已退役轮 ID,丢弃其迟到事件及音频,断开后清空。
|
||||
- 仅在明确收到 TTS 结束标记、软件队列写完且 AudioTrack 播放头达到已写样本数之后,发送一次对应 turn_id 的 playback.drained;临时断流/空队列不视为结束,已打断轮不发送 drained。短到未填满初始 STREAM 缓冲的完整回答补少量静音启动播放,静音尾计入 drain 样本数;drained 后暂停原生播放。
|
||||
- 录音回调再次检查录音代次,drained/播放错误回调再次检查播放代次;网络层仍检查连接代次和 socket 身份。停止、断线、退后台和释放均作废旧音频回调;退后台关闭连接,重新进入前台不自动恢复录音。
|
||||
- AEC UI 报告的是 `AcousticEchoCanceler.isAvailable()`,异常为未知;创建/启用 effect 是尽力尝试,不能据“可用”宣称消回声有效。播放使用媒体语音属性,遵循系统音量和输出路由,不强改扬声器模式。
|
||||
- 防止积压无限增长:上行 WS 排队超过约 64KiB 时断开并停止会话;软件播放队列上限为约 30 秒 PCM,溢出时停止当前语音会话并提示重新开始,不悄悄丢帧后虚报 drained。
|
||||
- `config.xml` host/port 未修改;无摄像头、表情、Opus、设置页、角色页或新依赖。
|
||||
|
||||
### 验证与待注意协议项
|
||||
|
||||
- 使用缓存的真实 OkHttp/Okio/AndroidX 依赖、SDK34、Kotlin 2.0.20 及 Compose 编译器插件,对全部主 Kotlin/Compose 源码执行独立编译检查。结果记录在 `logs/m2-source-check.log`;这不是 Gradle assembleDebug 或 APK 验收。
|
||||
- JVM 协议检查通过:方向 1/2、uint32 大端黄金头、640B 上行、1920B/短末帧下行、PCM 原样保留、非法头/长度/ID 拒绝。Manifest XML、权限和原 host/port 检查通过。
|
||||
- 当前沙箱仍不能 SSH 读取服务端源码,尚未收到请求的 JSON 示例。控制消息采用 `{type:"listen",state:"start",mode:"auto",barge_in:true}` / `{type:"listen",state:"stop"}`;abort 与 playback.drained 带 turn_id。事件动作读取 state 或 type 的点分后缀;TTS stop/done/end 视为整轮结束。**需与 v0.8 实际字段及整轮结束标记核对**,不能把逐句结束当作整轮结束。LV 的 uint32 大端沿用 M1,也需核对实际端序。
|
||||
- 完整构建由用户在外部执行 `./scripts/build.sh`,本次未生成或归档 M2 APK,现有 M1 产物保留。无新增依赖,不需因本次代码改动增加校验元数据条目。
|
||||
- 待真机联调:一轮及连续两轮对话、采集/播放格式、drained 时机、短回答启动、打断即时停播、换轮及旧回调隔离、HTTP 403 占用、断网/前后台恢复、权限拒绝及撤销、设备 AEC 实际效果与系统音频路由。
|
||||
|
||||
本次停在 M2 源码交付,等待外部构建结果和下一步指令。
|
||||
@@ -0,0 +1,3 @@
|
||||
org.gradle.jvmargs=-Xmx4g
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
File diff suppressed because it is too large
Load Diff
Vendored
BIN
Binary file not shown.
+8
@@ -0,0 +1,8 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionSha256Sum=544c35d6bd849ae8a5ed0bcea39ba677dc40f49df7d1835561582da2009b961d
|
||||
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.7-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,249 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
# 构建入口:scripts/build.sh [gradle 参数...],默认 assembleDebug;日志入 logs/
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
source /home/ubuntu/android-build/env.sh
|
||||
cd "$ROOT"
|
||||
if [ $# -eq 0 ]; then set -- assembleDebug; fi
|
||||
TS=$(date +%Y%m%d-%H%M%S)
|
||||
./gradlew --console=plain "$@" 2>&1 | tee "logs/build-$TS.log"
|
||||
@@ -0,0 +1,4 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement { repositories { google(); mavenCentral() } }
|
||||
rootProject.name = 'lan-voice-android'
|
||||
include ':app'
|
||||
Reference in New Issue
Block a user