Document radio worker ownership and format failure boundaries
This commit is contained in:
1 parent
d7e2b323d2
commit
e6873198d9
1 file changed
+107
-101
@@ -34,6 +34,9 @@ import java.util.concurrent.Future
|
||||
* повторное нажатие снимает таймер, cancel завершает запрос без хвоста. Отказ постановки таймера
|
||||
* логируется как ERROR и немедленно завершает ручной запрос; автоматика/измеритель учитываются отдельно.
|
||||
* talkingFlow показывает запрос/наблюдаемый TX, transmittingGroup — фактический native TX своего канала.
|
||||
* Подписка/native capture и workers сохраняются до запуска API/Thread: частичный отказ получает rollback.
|
||||
* Ошибка capture останавливает его подписку/encoder, сохраняя приём; ошибка playback освобождает всю свою сессию.
|
||||
* Очистка идёт на io независимо от доставки main; identity/pоколение защищают заменившую сессию.
|
||||
*/
|
||||
class RadioAudioEngine {
|
||||
|
||||
@@ -457,6 +460,7 @@ class RadioAudioEngine {
|
||||
}
|
||||
}
|
||||
|
||||
/** Только io: сохранить подписку/native-владение до возможного эффекта API; при отказе выполнить rollback. */
|
||||
private fun startCapture(mode: Int): Boolean {
|
||||
if (!MicrophonePermission.granted()) {
|
||||
LogManager.addLog("WARN", "radio", "Auto/PTT capture blocked: RECORD_AUDIO not granted group=$audioGroup mode=$mode")
|
||||
@@ -522,6 +526,7 @@ class RadioAudioEngine {
|
||||
}
|
||||
}
|
||||
|
||||
/** Только io: закрыть подписку, дождаться worker и остановить encoder; незавершённый native stop повторяем. */
|
||||
private fun stopCapture() {
|
||||
captureRunning = false
|
||||
val subscription = captureSubscription
|
||||
@@ -714,6 +719,7 @@ class RadioAudioEngine {
|
||||
message
|
||||
}
|
||||
|
||||
/** Упорядочить PTT и PCM своей подписки; неверный кадр/отказ JNI завершает worker с этапом в логе. */
|
||||
private fun captureLoop(subscription: MicrophoneCapture.Subscription, group: Long, ch: Int) {
|
||||
var expected = -1L
|
||||
var captureEpoch = -1L
|
||||
@@ -731,83 +737,83 @@ class RadioAudioEngine {
|
||||
var previousFeedAllowed: Boolean? = null
|
||||
var operation = "poll"
|
||||
try {
|
||||
while (captureRunning && active && groupId == group) {
|
||||
operation = "poll"
|
||||
val readStartedNs = SystemClock.elapsedRealtimeNanos()
|
||||
val event = subscription.poll() ?: continue
|
||||
if (!captureRunning || !active || groupId != group) break
|
||||
if (event is MicrophoneCapture.Ptt) {
|
||||
operation = if (event.pressed) "control begin" else "control end"
|
||||
if (event.pressed) NativeLib.radioTalkBegin(group) else NativeLib.radioTalkEnd(group)
|
||||
talking = event.pressed
|
||||
continue
|
||||
}
|
||||
val captured = event as MicrophoneCapture.Frame
|
||||
val ageNs = System.nanoTime() - captured.createdNs
|
||||
if (ageNs > 100_000_000) {
|
||||
if (!discontinuity) LogManager.addLog("WARN", "radio", "stale capture group=$group ageMs=${ageNs / 1_000_000}")
|
||||
discontinuity = true
|
||||
continue
|
||||
}
|
||||
operation = "frame"
|
||||
check(captured.pcm.size == FRAME_SAMPLES * ch) {
|
||||
"invalid capture frame samples=${captured.pcm.size} expected=${FRAME_SAMPLES * ch} sequence=${captured.sequence}"
|
||||
}
|
||||
if (discontinuity || (expected >= 0 && (captured.sequence != expected || captured.generation != captureEpoch))) {
|
||||
operation = "discontinuity"
|
||||
LogManager.addLog("INFO", "radio", "shared capture boundary group=$group epoch=$captureEpoch->${captured.generation}")
|
||||
NativeLib.radioCaptureDiscontinuity(group)
|
||||
}
|
||||
captureEpoch = captured.generation
|
||||
discontinuity = false; expected = captured.sequence + FRAME_SAMPLES
|
||||
val buf = captured.pcm
|
||||
maxReadNs = maxOf(maxReadNs, SystemClock.elapsedRealtimeNanos() - readStartedNs)
|
||||
val inputDb = rmsDb(buf)
|
||||
minRmsDb = minOf(minRmsDb, inputDb)
|
||||
maxRmsDb = maxOf(maxRmsDb, inputDb)
|
||||
statsFrames++
|
||||
frameN++
|
||||
val autoAllowed = autoMode != RadioAutoSettings.OFF && screenInteractive && vadWindow.isAllowed(SystemClock.elapsedRealtime())
|
||||
val feedAllowed = active && groupId == group && captureRunning &&
|
||||
(talking || autoAllowed || (levelMonitoring && screenInteractive))
|
||||
if (previousFeedAllowed != feedAllowed) {
|
||||
LogManager.addLog("DEBUG", "radio", "Auto PCM gate group=$group frame=$frameN allowed=$feedAllowed " +
|
||||
"active=$active currentGroup=$groupId capture=$captureRunning manual=$requestedTalk talking=$talking " +
|
||||
"nativeMode=$autoMode screen=$screenInteractive backgroundDeadlineMs=${vadWindow.deadlineMs}")
|
||||
previousFeedAllowed = feedAllowed
|
||||
}
|
||||
if (feedAllowed) {
|
||||
operation = "feed"
|
||||
val requestNs = talkRequestNs
|
||||
val feedStartedNs = SystemClock.elapsedRealtimeNanos()
|
||||
check(NativeLib.radioAudioFeed(group, buf)) { "native PCM feed rejected" }
|
||||
maxFeedNs = maxOf(maxFeedNs, SystemClock.elapsedRealtimeNanos() - feedStartedNs)
|
||||
fedFrames++
|
||||
if (requestedTalk && requestNs != reportedRequestNs) {
|
||||
reportedRequestNs = requestNs
|
||||
LogManager.addLog("INFO", "RadioAudio", "PTT first frame queued elapsedMs=${(SystemClock.elapsedRealtimeNanos() - requestNs) / 1_000_000}")
|
||||
while (captureRunning && active && groupId == group) {
|
||||
operation = "poll"
|
||||
val readStartedNs = SystemClock.elapsedRealtimeNanos()
|
||||
val event = subscription.poll() ?: continue
|
||||
if (!captureRunning || !active || groupId != group) break
|
||||
if (event is MicrophoneCapture.Ptt) {
|
||||
operation = if (event.pressed) "control begin" else "control end"
|
||||
if (event.pressed) NativeLib.radioTalkBegin(group) else NativeLib.radioTalkEnd(group)
|
||||
talking = event.pressed
|
||||
continue
|
||||
}
|
||||
val captured = event as MicrophoneCapture.Frame
|
||||
val ageNs = System.nanoTime() - captured.createdNs
|
||||
if (ageNs > 100_000_000) {
|
||||
if (!discontinuity) LogManager.addLog("WARN", "radio", "stale capture group=$group ageMs=${ageNs / 1_000_000}")
|
||||
discontinuity = true
|
||||
continue
|
||||
}
|
||||
operation = "frame"
|
||||
check(captured.pcm.size == FRAME_SAMPLES * ch) {
|
||||
"invalid capture frame samples=${captured.pcm.size} expected=${FRAME_SAMPLES * ch} sequence=${captured.sequence}"
|
||||
}
|
||||
if (discontinuity || (expected >= 0 && (captured.sequence != expected || captured.generation != captureEpoch))) {
|
||||
operation = "discontinuity"
|
||||
LogManager.addLog("INFO", "radio", "shared capture boundary group=$group epoch=$captureEpoch->${captured.generation}")
|
||||
NativeLib.radioCaptureDiscontinuity(group)
|
||||
}
|
||||
captureEpoch = captured.generation
|
||||
discontinuity = false; expected = captured.sequence + FRAME_SAMPLES
|
||||
val buf = captured.pcm
|
||||
maxReadNs = maxOf(maxReadNs, SystemClock.elapsedRealtimeNanos() - readStartedNs)
|
||||
val inputDb = rmsDb(buf)
|
||||
minRmsDb = minOf(minRmsDb, inputDb)
|
||||
maxRmsDb = maxOf(maxRmsDb, inputDb)
|
||||
statsFrames++
|
||||
frameN++
|
||||
val autoAllowed = autoMode != RadioAutoSettings.OFF && screenInteractive && vadWindow.isAllowed(SystemClock.elapsedRealtime())
|
||||
val feedAllowed = active && groupId == group && captureRunning &&
|
||||
(talking || autoAllowed || (levelMonitoring && screenInteractive))
|
||||
if (previousFeedAllowed != feedAllowed) {
|
||||
LogManager.addLog("DEBUG", "radio", "Auto PCM gate group=$group frame=$frameN allowed=$feedAllowed " +
|
||||
"active=$active currentGroup=$groupId capture=$captureRunning manual=$requestedTalk talking=$talking " +
|
||||
"nativeMode=$autoMode screen=$screenInteractive backgroundDeadlineMs=${vadWindow.deadlineMs}")
|
||||
previousFeedAllowed = feedAllowed
|
||||
}
|
||||
if (feedAllowed) {
|
||||
operation = "feed"
|
||||
val requestNs = talkRequestNs
|
||||
val feedStartedNs = SystemClock.elapsedRealtimeNanos()
|
||||
check(NativeLib.radioAudioFeed(group, buf)) { "native PCM feed rejected" }
|
||||
maxFeedNs = maxOf(maxFeedNs, SystemClock.elapsedRealtimeNanos() - feedStartedNs)
|
||||
fedFrames++
|
||||
if (requestedTalk && requestNs != reportedRequestNs) {
|
||||
reportedRequestNs = requestNs
|
||||
LogManager.addLog("INFO", "RadioAudio", "PTT first frame queued elapsedMs=${(SystemClock.elapsedRealtimeNanos() - requestNs) / 1_000_000}")
|
||||
}
|
||||
operation = "TX status"
|
||||
if (captureRunning) _talkingFlow.value = requestedTalk || NativeLib.radioTransmitting()
|
||||
} else skippedFrames++
|
||||
operation = "TX status"
|
||||
if (captureRunning) _talkingFlow.value = requestedTalk || NativeLib.radioTransmitting()
|
||||
} else skippedFrames++
|
||||
operation = "TX status"
|
||||
val transmitting = if (captureRunning && active && groupId == group && NativeLib.radioTransmitting()) group else null
|
||||
if (_transmittingGroup.value != transmitting) {
|
||||
_transmittingGroup.value = transmitting
|
||||
LogManager.addLog("DEBUG", "radio", "TX state group=$group on=${transmitting != null} manual=$requestedTalk mode=$autoMode")
|
||||
val transmitting = if (captureRunning && active && groupId == group && NativeLib.radioTransmitting()) group else null
|
||||
if (_transmittingGroup.value != transmitting) {
|
||||
_transmittingGroup.value = transmitting
|
||||
LogManager.addLog("DEBUG", "radio", "TX state group=$group on=${transmitting != null} manual=$requestedTalk mode=$autoMode")
|
||||
}
|
||||
val nowMs = SystemClock.elapsedRealtime()
|
||||
if (nowMs - statsMs >= 10_000L) {
|
||||
LogManager.addLog("DEBUG", "radio", "Auto capture summary group=$group spanMs=${nowMs - statsMs} " +
|
||||
"frames=$statsFrames audioMs=${statsFrames * FRAME_MS} fed=$fedFrames skipped=$skippedFrames " +
|
||||
"rmsDb=$minRmsDb..$maxRmsDb readMaxMs=${maxReadNs / 1_000_000.0} feedMaxMs=${maxFeedNs / 1_000_000.0} " +
|
||||
"channels=$ch input=${MediaAudioController.state.value.inputName} " +
|
||||
"route=${route()} mode=$autoMode screen=$screenInteractive manual=$requestedTalk tx=${_talkingFlow.value}")
|
||||
statsMs = nowMs
|
||||
statsFrames = 0; fedFrames = 0; skippedFrames = 0
|
||||
minRmsDb = 0; maxRmsDb = -120; maxReadNs = 0L; maxFeedNs = 0L
|
||||
}
|
||||
}
|
||||
val nowMs = SystemClock.elapsedRealtime()
|
||||
if (nowMs - statsMs >= 10_000L) {
|
||||
LogManager.addLog("DEBUG", "radio", "Auto capture summary group=$group spanMs=${nowMs - statsMs} " +
|
||||
"frames=$statsFrames audioMs=${statsFrames * FRAME_MS} fed=$fedFrames skipped=$skippedFrames " +
|
||||
"rmsDb=$minRmsDb..$maxRmsDb readMaxMs=${maxReadNs / 1_000_000.0} feedMaxMs=${maxFeedNs / 1_000_000.0} " +
|
||||
"channels=$ch input=${MediaAudioController.state.value.inputName} " +
|
||||
"route=${route()} mode=$autoMode screen=$screenInteractive manual=$requestedTalk tx=${_talkingFlow.value}")
|
||||
statsMs = nowMs
|
||||
statsFrames = 0; fedFrames = 0; skippedFrames = 0
|
||||
minRmsDb = 0; maxRmsDb = -120; maxReadNs = 0L; maxFeedNs = 0L
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (e is InterruptedException && !captureRunning) {
|
||||
LogManager.addLog("DEBUG", "RadioAudio", "capture cancelled operation=$operation group=$group")
|
||||
@@ -840,36 +846,36 @@ class RadioAudioEngine {
|
||||
var written = 0
|
||||
LogManager.addLog("DEBUG", "radio", "playback progress tracking group=$group guard=200ms")
|
||||
try {
|
||||
while (playbackRunning) {
|
||||
operation = "head"
|
||||
/* AudioTrack возвращает unsigned 32-bit позицию; разворачиваем wrap (~25 часов @48k). */
|
||||
val head = track.playbackHeadPosition.toLong() and 0xffffffffL
|
||||
playedFrames += (head - previousHead) and 0xffffffffL
|
||||
previousHead = head
|
||||
operation = "pull"
|
||||
val n = NativeLib.radioAudioPull(group, buf, playedFrames)
|
||||
check(n in 0..frame && n % PLAY_CHANNELS == 0) { "invalid native playback count=$n capacity=$frame" }
|
||||
if (n < frame) buf.fill(0, n, frame)
|
||||
written = 0
|
||||
operation = "write"
|
||||
while (written < frame && playbackRunning) {
|
||||
val count = track.write(buf, written, frame - written)
|
||||
check(count > 0 && count <= frame - written && count % PLAY_CHANNELS == 0) {
|
||||
"invalid playback write rc=$count written=$written/$frame channels=$PLAY_CHANNELS"
|
||||
while (playbackRunning) {
|
||||
operation = "head"
|
||||
/* AudioTrack возвращает unsigned 32-bit позицию; разворачиваем wrap (~25 часов @48k). */
|
||||
val head = track.playbackHeadPosition.toLong() and 0xffffffffL
|
||||
playedFrames += (head - previousHead) and 0xffffffffL
|
||||
previousHead = head
|
||||
operation = "pull"
|
||||
val n = NativeLib.radioAudioPull(group, buf, playedFrames)
|
||||
check(n in 0..frame && n % PLAY_CHANNELS == 0) { "invalid native playback count=$n capacity=$frame" }
|
||||
if (n < frame) buf.fill(0, n, frame)
|
||||
written = 0
|
||||
operation = "write"
|
||||
while (written < frame && playbackRunning) {
|
||||
val count = track.write(buf, written, frame - written)
|
||||
check(count > 0 && count <= frame - written && count % PLAY_CHANNELS == 0) {
|
||||
"invalid playback write rc=$count written=$written/$frame channels=$PLAY_CHANNELS"
|
||||
}
|
||||
written += count
|
||||
}
|
||||
written += count
|
||||
}
|
||||
|
||||
/* абсолютный deadline: не даём Thread.sleep накопить систематический дрейф */
|
||||
nextNs += frameNs
|
||||
val waitNs = nextNs - System.nanoTime()
|
||||
if (waitNs > 0) {
|
||||
operation = "sleep"
|
||||
Thread.sleep(waitNs / 1_000_000L, (waitNs % 1_000_000L).toInt())
|
||||
} else {
|
||||
nextNs = System.nanoTime() /* отстали — сбрасываем, не копим долг */
|
||||
/* абсолютный deadline: не даём Thread.sleep накопить систематический дрейф */
|
||||
nextNs += frameNs
|
||||
val waitNs = nextNs - System.nanoTime()
|
||||
if (waitNs > 0) {
|
||||
operation = "sleep"
|
||||
Thread.sleep(waitNs / 1_000_000L, (waitNs % 1_000_000L).toInt())
|
||||
} else {
|
||||
nextNs = System.nanoTime() /* отстали — сбрасываем, не копим долг */
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (e is InterruptedException && !playbackRunning) {
|
||||
LogManager.addLog("DEBUG", "RadioAudio", "playback cancelled operation=$operation group=$group generation=$version")
|
||||
|
||||
Reference in new issue
Block a user