maauto: audio sinks ch4/5 plus mic ch6, focus matrix, tests
- Commit
d3680b40f0c7a80cef9ed9af2628a64d661b0ab9- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 22:42 UTC (2 months ago)
- Parents
3798785
Diff
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/AudioCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/AudioCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/AudioCodec.ktnew file mode 100644index 0000000000..8f32ec0f69--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/AudioCodec.kt@@ -0,0 +1,419 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AudioConfiguration+import com.vayunmathur.auto.protocol.gal.MediaAck+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSetupRequest+import com.vayunmathur.auto.protocol.gal.MediaSetupResponse+import com.vayunmathur.auto.protocol.gal.MediaStartRequest+import com.vayunmathur.auto.protocol.gal.MediaStopRequest+import com.vayunmathur.auto.protocol.gal.Service+import java.nio.ByteBuffer+import java.nio.ByteOrder++/**+ * Which car speaker set a sink feeds.+ *+ * Service 4 (SYSTEM) carries transient sounds -- TTS prompts, notification+ * pings -- and asks for transient focus; service 5 (MEDIA) carries music and+ * asks for full gain. Guidance (service 3) is deliberately unowned: it rides+ * the same `jdk` sink shape, but nothing feeds it yet and opening a channel+ * we never start would only earn head-unit attention we cannot answer.+ */+enum class AudioSinkRole(val serviceId: Int) {+ SYSTEM(GalService.AUDIO_SINK_SYSTEM.id),+ MEDIA(GalService.AUDIO_SINK_MEDIA.id),+ ;++ companion object {+ fun forServiceId(id: Int): AudioSinkRole? = entries.firstOrNull { it.serviceId == id }+ }+}++/**+ * How loud a sink may emit right now.+ *+ * FULL streams as captured; DUCKED scales PCM down before sending (the+ * music-behind-TTS case); MUTED drops frames. Ducking is a sink-side sample+ * decision, not a play gate -- [FocusArbitration.mayPlayMedia] stays the+ * coarse "may the phone make noise" answer, and this refines it per sink.+ */+enum class AudioGain {+ FULL,+ DUCKED,+ MUTED,+}++/** A sink-side inbound message, already classified. Anything else is [Observed]. */+sealed interface InboundAudio {+ /** The head unit answered setup (0x8003): which discovery configs it accepts. */+ data class Config(val response: MediaSetupResponse) : InboundAudio++ /** The head unit consumed frames (0x8004). [ackSeq] is the mod-256 counter, unsigned. */+ data class Ack(val sessionId: Int, val ackSeq: Long?) : InboundAudio++ /** The no-payload 0x800B from the media-sink table; presumed stream sync. */+ data object Sync : InboundAudio++ /**+ * Anything else on the channel -- 0x8013 (`xkq`), malformed setup/ack bytes,+ * a future extension. Observed and ignored, never fatal.+ */+ data class Observed(val type: Int) : InboundAudio+}++/** One microphone bulk chunk with its capture timestamp, if it carried one. */+data class MicChunk(+ /** Microseconds from the 8-byte 0x0000 prefix, or -1 for prefix-less 0x0001. */+ val timestampUs: Long,+ val pcm: ByteArray,+) {+ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is MicChunk) return false+ return timestampUs == other.timestampUs && pcm.contentEquals(other.pcm)+ }++ override fun hashCode(): Int = 31 * timestampUs.hashCode() + pcm.contentHashCode()+}++/** 16-bit mono PCM unwrapped from a TTS WAV file, at its native rate. */+data class WavPcm(val sampleRateHz: Int, val pcm: ByteArray) {+ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is WavPcm) return false+ return sampleRateHz == other.sampleRateHz && pcm.contentEquals(other.pcm)+ }++ override fun hashCode(): Int = 31 * sampleRateHz + pcm.contentHashCode()+}++/**+ * Pure audio-channel (services 4/5 sinks, service 6 source) codecs and policy.+ *+ * Android-free like everything else in this module, so config negotiation,+ * the focus preemption matrix and the PCM helpers are all host-testable. The+ * sink bring-up mirrors video (`requestSetup` -> CONFIG -> focus -> START),+ * except the focus ask goes over control 0x18 first: gearhead's `jdk` sends+ * media setup from `onChannelOpened` and the audio sinks request focus before+ * starting the stream.+ *+ * Codec ground truth (FINDINGS.md media-sink table): sinks SEND 0x8000 setup,+ * 0x8001 start, 0x8002 stop and bulk 0x0000/0x0001, and RECEIVE 0x8003 config,+ * 0x8004 ack and no-payload 0x800B. The car owns the microphone, so the phone+ * RECEIVES 0x8006 requests and bulk audio and SENDS 0x8004 acks.+ *+ * Opus note: the teardown's codec enum (`xkj`) is PCM / AAC_LC / H264_BP /+ * AAC_LC_ADTS / VP9 / AV1 / H265 -- no Opus. Negotiation therefore requires+ * PCM (`MEDIA_CODEC_AUDIO_PCM`) and declines anything else rather than+ * starting a stream the head unit cannot decode; an Opus entry point goes in+ * [selectConfig] if a future teardown recovers one.+ */+object AudioCodec {++ /** `MediaSetupRequest.media_type`: 1 audio, 3 video. */+ const val MEDIA_TYPE_AUDIO = 1++ /** Mic acks name the session the sinks use: no mic start handshake carries one. */+ const val MIC_SESSION_ID = 0++ /** 0x0000 bulk carries this many timestamp bytes ahead of the audio. */+ const val TIMESTAMP_BYTES = Long.SIZE_BYTES++ /** Ducked music plays this much quieter behind transient audio (-12 dB). */+ const val DUCK_NUMERATOR = 1+ const val DUCK_DENOMINATOR = 4++ /** Phone -> HU: claim the channel for audio. Sent on the channel grant. */+ fun encodeSetup(): Pair<Int, ByteArray> =+ GalMessage.Media.SETUP_REQUEST to MediaSetupRequest.newBuilder()+ .setMediaType(MEDIA_TYPE_AUDIO)+ .build()+ .toByteArray()++ /** Phone -> HU: start streaming the confirmed configuration. */+ fun encodeStart(sessionId: Int, configurationIndex: Int): Pair<Int, ByteArray> =+ GalMessage.Media.START_REQUEST to MediaStartRequest.newBuilder()+ .setSessionId(sessionId)+ .setConfigurationIndex(configurationIndex)+ .build()+ .toByteArray()++ /** Phone -> HU: stop streaming. Genuinely empty, like video's. */+ fun encodeStop(): Pair<Int, ByteArray> =+ GalMessage.Media.STOP_REQUEST to MediaStopRequest.newBuilder().build().toByteArray()++ /**+ * Phone -> HU: the mic ack (`jaz` sends 0x8004). Session only -- the ack+ * counter is the head unit's own frame tracker on sink channels, and the+ * mic direction has no phone-side counter to report.+ */+ fun encodeMicAck(sessionId: Int = MIC_SESSION_ID): Pair<Int, ByteArray> =+ GalMessage.Media.ACK to MediaAck.newBuilder()+ .setSessionId(sessionId)+ .build()+ .toByteArray()++ /**+ * Picks the discovery configuration to offer, or null when the service+ * cannot carry PCM.+ *+ * Null means "do not start this sink": a non-PCM codec, no audio configs,+ * or no sane config (bits outside 8/16/24/32, channels outside mono/+ * stereo, absurd rate). The bring-up carries on with the remaining+ * services -- an unstarted sink is a missing feature, not a dead session.+ * The returned index addresses the discovery `audio_configs` list, which+ * is what the head unit's `configuration_indices` confirm against.+ */+ fun selectConfig(service: Service): SelectedConfig? {+ if (!service.hasMediaSink()) return null+ val sink = service.mediaSink+ if (sink.availableType != MediaCodecType.MEDIA_CODEC_AUDIO_PCM) return null+ var best: SelectedConfig? = null+ sink.audioConfigsList.forEachIndexed { index, config ->+ if (score(config) > (best?.let { score(it.config) } ?: -1)) {+ best = SelectedConfig(index, config)+ }+ }+ return best?.takeIf { score(it.config) >= 0 }+ }++ /**+ * Confirms our selection against the head unit's 0x8003 answer.+ *+ * An empty index list accepts our pick (same leniency as the video+ * channel's `firstOrNull() ?: 0`); otherwise the best-scoring confirmed+ * config wins, and null -- do not start -- when nothing confirmed is sane.+ */+ fun confirmConfig(+ response: MediaSetupResponse,+ selected: SelectedConfig,+ service: Service,+ ): SelectedConfig? {+ val indices = response.configurationIndicesList+ if (indices.isEmpty()) return selected+ val configs = service.mediaSink.audioConfigsList+ var best: SelectedConfig? = null+ for (index in indices) {+ val config = configs.getOrNull(index) ?: continue+ if (score(config) >= 0 && score(config) > (best?.let { score(it.config) } ?: -1)) {+ best = SelectedConfig(index, config)+ }+ }+ return best+ }++ /**+ * Classifies one inbound sink message. Never throws: malformed+ * setup/ack bytes and unknown types decode to [InboundAudio.Observed],+ * so the pump survives whatever a head unit sends.+ */+ fun decodeSinkInbound(type: Int, payload: ByteArray): InboundAudio = when (type) {+ GalMessage.Media.CONFIG -> runCatching { MediaSetupResponse.parseFrom(payload) }+ .getOrNull()+ ?.let { InboundAudio.Config(it) }+ ?: InboundAudio.Observed(type)+ GalMessage.Media.ACK -> runCatching { MediaAck.parseFrom(payload) }+ .getOrNull()+ ?.let { InboundAudio.Ack(it.sessionId, if (it.hasAck()) Integer.toUnsignedLong(it.ack) else null) }+ ?: InboundAudio.Observed(type)+ GalMessage.Audio.SYNC -> InboundAudio.Sync+ else -> InboundAudio.Observed(type)+ }++ /**+ * Strips one inbound mic bulk chunk, or null when it carries no audio.+ *+ * 0x0000 prefixes an 8-byte big-endian microsecond timestamp; 0x0001 has+ * no prefix. Anything else, a truncated prefix, or a timestamp-only+ * payload is observed-but-empty, never an error.+ */+ fun decodeMicData(type: Int, payload: ByteArray): MicChunk? = when (type) {+ GalMessage.Media.DATA_WITH_TIMESTAMP -> {+ if (payload.size <= TIMESTAMP_BYTES) null+ else {+ val timestamp = ByteBuffer.wrap(payload, 0, TIMESTAMP_BYTES)+ .order(ByteOrder.BIG_ENDIAN).long+ MicChunk(timestamp, payload.copyOfRange(TIMESTAMP_BYTES, payload.size))+ }+ }+ GalMessage.Media.DATA -> if (payload.isEmpty()) null else MicChunk(-1, payload.copyOf())+ else -> null+ }++ /**+ * The focus preemption matrix: which sink may emit under each head-unit+ * audio state.+ *+ * - Full GAIN streams everything; transient gain lets SYS through and+ * ducks MEDIA (TTS over music); MEDIA_ONLY mutes SYS; transient+ * guidance-only mutes MEDIA; every loss mutes both except+ * LOSS_TRANSIENT_CAN_DUCK, which keeps MEDIA flowing quietly.+ * - Projected video is the implicit grant: it lifts MUTED to FULL, but a+ * transient gain still preempts MEDIA down to DUCKED -- the TTS case+ * does not care which screen is up.+ */+ fun gainFor(+ role: AudioSinkRole,+ audioFocus: com.vayunmathur.auto.protocol.gal.AudioFocusState,+ videoFocus: VideoFocus,+ ): AudioGain {+ val base = when (audioFocus) {+ com.vayunmathur.auto.protocol.gal.AudioFocusState.AUDIO_FOCUS_STATE_GAIN ->+ AudioGain.FULL to AudioGain.FULL+ com.vayunmathur.auto.protocol.gal.AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT ->+ AudioGain.FULL to AudioGain.DUCKED+ com.vayunmathur.auto.protocol.gal.AudioFocusState.AUDIO_FOCUS_STATE_GAIN_MEDIA_ONLY ->+ AudioGain.MUTED to AudioGain.FULL+ com.vayunmathur.auto.protocol.gal.AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT_GUIDANCE_ONLY ->+ AudioGain.FULL to AudioGain.MUTED+ com.vayunmathur.auto.protocol.gal.AudioFocusState.AUDIO_FOCUS_STATE_LOSS_TRANSIENT_CAN_DUCK ->+ AudioGain.MUTED to AudioGain.DUCKED+ else -> AudioGain.MUTED to AudioGain.MUTED+ }+ val granted = if (role == AudioSinkRole.SYSTEM) base.first else base.second+ if (granted != AudioGain.MUTED || videoFocus != VideoFocus.PROJECTED) return granted+ // Implicit grant, except the transient preemption above still holds.+ return if (role == AudioSinkRole.MEDIA && audioFocus ==+ com.vayunmathur.auto.protocol.gal.AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT+ ) {+ AudioGain.DUCKED+ } else {+ AudioGain.FULL+ }+ }++ /** Whether [role] may emit at all: anything but MUTED. */+ fun mayPlay(+ role: AudioSinkRole,+ audioFocus: com.vayunmathur.auto.protocol.gal.AudioFocusState,+ videoFocus: VideoFocus,+ ): Boolean = gainFor(role, audioFocus, videoFocus) != AudioGain.MUTED++ /**+ * Scales 16-bit little-endian PCM by [numerator]/[denominator], clamping+ * to short range. Odd trailing bytes are carried over untouched -- a+ * truncated frame is the sender's bug, not a reason to drop the buffer.+ */+ fun scalePcm16(pcm: ByteArray, numerator: Int, denominator: Int): ByteArray {+ if (numerator == denominator) return pcm.copyOf()+ val out = pcm.copyOf()+ val buffer = ByteBuffer.wrap(out).order(ByteOrder.LITTLE_ENDIAN)+ var i = 0+ while (i + 1 < pcm.size) {+ val scaled = (buffer.getShort(i).toLong() * numerator / denominator)+ .coerceIn(Short.MIN_VALUE.toLong(), Short.MAX_VALUE.toLong())+ buffer.putShort(i, scaled.toShort())+ i += 2+ }+ return out+ }++ /**+ * Linear-resamples mono 16-bit PCM between rates. Identity copies;+ * anything else interpolates. Empty in, empty out.+ */+ fun resampleLinearMono16(pcm: ByteArray, fromRateHz: Int, toRateHz: Int): ByteArray {+ require(fromRateHz > 0 && toRateHz > 0) { "rates must be positive" }+ if (pcm.isEmpty()) return ByteArray(0)+ if (fromRateHz == toRateHz) return pcm.copyOf()+ val input = ShortArray(pcm.size / 2) { i ->+ ByteBuffer.wrap(pcm, i * 2, 2).order(ByteOrder.LITTLE_ENDIAN).short+ }+ val outSamples = ((input.size.toLong() * toRateHz) / fromRateHz).toInt().coerceAtLeast(1)+ val out = ByteBuffer.allocate(outSamples * 2).order(ByteOrder.LITTLE_ENDIAN)+ for (o in 0 until outSamples) {+ val position = o.toLong() * fromRateHz / toRateHz+ val index = position.toInt().coerceIn(0, input.size - 1)+ val next = (index + 1).coerceIn(0, input.size - 1)+ val fraction = ((o.toLong() * fromRateHz % toRateHz).toDouble() / toRateHz)+ out.putShort((input[index] + (next - index) * fraction).toInt().toShort())+ }+ return out.array()+ }++ /**+ * Unwraps the WAV a TTS `synthesizeToFile` produces into raw mono PCM.+ *+ * Requires PCM format (1), 16-bit samples, mono or stereo (stereo is+ * downmixed by averaging pairs); anything else is null rather than+ * misdecoded audio. Chunks are scanned, not assumed in order -- the only+ * contract is RIFF/WAVE framing.+ */+ fun stripWavToPcm16Mono(wav: ByteArray): WavPcm? {+ if (wav.size < 44) return null+ val header = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN)+ if (header.getInt(0) != RIFF_MAGIC || header.getInt(8) != WAVE_MAGIC) return null+ var channels = 0+ var sampleRate = 0+ var offset = 12+ while (offset + 8 <= wav.size) {+ val chunkId = header.getInt(offset)+ val chunkSize = header.getInt(offset + 4)+ if (chunkSize < 0) return null+ val body = offset + 8+ if (body + chunkSize > wav.size) return null+ when (chunkId) {+ FMT_MAGIC -> {+ if (chunkSize < 16) return null+ if (header.getShort(body) != 1.toShort()) return null+ channels = header.getShort(body + 2).toInt()+ if (channels != 1 && channels != 2) return null+ sampleRate = header.getInt(body + 4)+ if (sampleRate <= 0) return null+ if (header.getShort(body + 14) != 16.toShort()) return null+ }+ DATA_MAGIC -> {+ if (channels == 0 || sampleRate == 0) return null+ val raw = wav.copyOfRange(body, body + chunkSize - (chunkSize % 2))+ val mono = if (channels == 1) raw else downmixStereo16(raw)+ return WavPcm(sampleRate, mono)+ }+ }+ offset = body + chunkSize + (chunkSize % 2)+ }+ return null+ }++ /**+ * Scores a discovery config for PCM streaming. Negative is unusable;+ * otherwise higher wins: 16-bit, then stereo, then 48 kHz > 44.1 kHz >+ * 16 kHz voice.+ */+ private fun score(config: AudioConfiguration): Int {+ if (!config.hasSamplingRate() || !config.hasNumberOfBits() || !config.hasNumberOfChannels()) {+ return -1+ }+ if (config.numberOfBits !in setOf(8, 16, 24, 32)) return -1+ if (config.numberOfChannels != 1 && config.numberOfChannels != 2) return -1+ if (config.samplingRate !in 8_000..192_000) return -1+ var score = 0+ if (config.numberOfBits == 16) score += 4+ if (config.numberOfChannels == 2) score += 2+ score += when (config.samplingRate) {+ 48_000 -> 3+ 44_100 -> 2+ 16_000 -> 1+ else -> 0+ }+ return score+ }++ private fun downmixStereo16(stereo: ByteArray): ByteArray {+ val frames = stereo.size / 4+ val out = ByteBuffer.allocate(frames * 2).order(ByteOrder.LITTLE_ENDIAN)+ val input = ByteBuffer.wrap(stereo).order(ByteOrder.LITTLE_ENDIAN)+ repeat(frames) {+ out.putShort(((input.short.toInt() + input.short.toInt()) / 2).toShort())+ }+ return out.array()+ }++ private const val RIFF_MAGIC = 0x46464952 // "RIFF", little-endian+ private const val WAVE_MAGIC = 0x45564157 // "WAVE", little-endian+ private const val FMT_MAGIC = 0x20746D66 // "fmt ", little-endian+ private const val DATA_MAGIC = 0x61746164 // "data", little-endian+}++/** One usable discovery configuration and its index in `audio_configs`. */+data class SelectedConfig(val index: Int, val config: AudioConfiguration)
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/AudioCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/AudioCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/AudioCodecTest.ktnew file mode 100644index 0000000000..ca48725578--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/AudioCodecTest.kt@@ -0,0 +1,422 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AudioConfiguration+import com.vayunmathur.auto.protocol.gal.AudioFocusState+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSetupResponse+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.Service+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins audio config negotiation (PCM required, PCM picked, head-unit answer+ * confirmed), the focus preemption matrix, mic bulk framing and the PCM+ * helpers -- all host-runnable, all pure [AudioCodec].+ */+class AudioCodecTest {++ private fun audioService(vararg configs: AudioConfiguration, type: MediaCodecType = MediaCodecType.MEDIA_CODEC_AUDIO_PCM): Service =+ Service.newBuilder()+ .setId(GalService.AUDIO_SINK_MEDIA.id)+ .setMediaSink(+ MediaSinkService.newBuilder()+ .setAvailableType(type)+ .addAllAudioConfigs(configs.asList())+ .build(),+ )+ .build()++ private fun config(rate: Int = 48_000, bits: Int = 16, channels: Int = 2): AudioConfiguration =+ AudioConfiguration.newBuilder()+ .setSamplingRate(rate)+ .setNumberOfBits(bits)+ .setNumberOfChannels(channels)+ .build()++ // ---- negotiation ----++ @Test+ fun `setup claims the channel for audio`() {+ val (type, payload) = AudioCodec.encodeSetup()+ assertEquals(GalMessage.Media.SETUP_REQUEST, type)+ val parsed = com.vayunmathur.auto.protocol.gal.MediaSetupRequest.parseFrom(payload)+ assertEquals(AudioCodec.MEDIA_TYPE_AUDIO, parsed.mediaType)+ }++ @Test+ fun `start names the session and the confirmed config`() {+ val (type, payload) = AudioCodec.encodeStart(sessionId = 0, configurationIndex = 2)+ assertEquals(GalMessage.Media.START_REQUEST, type)+ val parsed = com.vayunmathur.auto.protocol.gal.MediaStartRequest.parseFrom(payload)+ assertEquals(0, parsed.sessionId)+ assertEquals(2, parsed.configurationIndex)+ }++ @Test+ fun `pcm service picks the best config`() {+ val selected = AudioCodec.selectConfig(+ audioService(config(16_000, 16, 1), config(48_000, 16, 2), config(44_100, 16, 2)),+ )+ assertNotNull(selected)+ assertEquals(1, selected.index)+ assertEquals(48_000, selected.config.samplingRate)+ }++ @Test+ fun `an aac-only service is not started`() {+ assertNull(+ AudioCodec.selectConfig(+ audioService(config(), type = MediaCodecType.MEDIA_CODEC_AUDIO_AAC_LC),+ ),+ )+ }++ @Test+ fun `a service with no audio configs is not started`() {+ assertNull(AudioCodec.selectConfig(audioService()))+ }++ @Test+ fun `an insane config is not started`() {+ assertNull(AudioCodec.selectConfig(audioService(config(48_000, 7, 2))))+ assertNull(AudioCodec.selectConfig(audioService(config(48_000, 16, 5))))+ assertNull(AudioCodec.selectConfig(audioService(config(3_000_000, 16, 2))))+ }++ @Test+ fun `a non-sink service is not started`() {+ val service = Service.newBuilder().setId(GalService.AUDIO_SINK_MEDIA.id).build()+ assertNull(AudioCodec.selectConfig(service))+ }++ @Test+ fun `an empty head-unit answer accepts our pick`() {+ val service = audioService(config(48_000, 16, 2))+ val selected = AudioCodec.selectConfig(service)!!+ val confirmed = AudioCodec.confirmConfig(+ MediaSetupResponse.newBuilder().setMediaStatus(0).build(),+ selected,+ service,+ )+ assertEquals(selected, confirmed)+ }++ @Test+ fun `a confirming head-unit answer picks the best confirmed config`() {+ val service = audioService(config(48_000, 16, 2), config(16_000, 16, 1))+ val selected = AudioCodec.selectConfig(service)!!+ val confirmed = AudioCodec.confirmConfig(+ MediaSetupResponse.newBuilder().setMediaStatus(0).addConfigurationIndices(1).build(),+ selected,+ service,+ )+ assertNotNull(confirmed)+ assertEquals(1, confirmed.index)+ assertEquals(16_000, confirmed.config.samplingRate)+ }++ @Test+ fun `an out-of-range head-unit answer means do not start`() {+ val service = audioService(config(48_000, 16, 2))+ val selected = AudioCodec.selectConfig(service)!!+ assertNull(+ AudioCodec.confirmConfig(+ MediaSetupResponse.newBuilder().setMediaStatus(0).addConfigurationIndices(9).build(),+ selected,+ service,+ ),+ )+ }++ // ---- sink inbound ----++ @Test+ fun `a setup answer classifies as config`() {+ val payload = MediaSetupResponse.newBuilder()+ .setMediaStatus(0)+ .addConfigurationIndices(0)+ .build()+ .toByteArray()+ val inbound = AudioCodec.decodeSinkInbound(GalMessage.Media.CONFIG, payload)+ assertTrue(inbound is InboundAudio.Config)+ assertEquals(listOf(0), inbound.response.configurationIndicesList.toList())+ }++ @Test+ fun `an ack classifies with its unsigned counter`() {+ val payload = com.vayunmathur.auto.protocol.gal.MediaAck.newBuilder()+ .setSessionId(0)+ .setAck(-1)+ .build()+ .toByteArray()+ val inbound = AudioCodec.decodeSinkInbound(GalMessage.Media.ACK, payload)+ assertEquals(InboundAudio.Ack(0, 4_294_967_295L), inbound)+ }++ @Test+ fun `a sync pulse classifies as sync`() {+ assertEquals(InboundAudio.Sync, AudioCodec.decodeSinkInbound(GalMessage.Audio.SYNC, ByteArray(0)))+ }++ @Test+ fun `garbage on a sink channel is observed, never fatal`() {+ assertEquals(+ InboundAudio.Observed(0x8013),+ AudioCodec.decodeSinkInbound(0x8013, ByteArray(0)),+ )+ assertEquals(+ InboundAudio.Observed(GalMessage.Media.CONFIG),+ AudioCodec.decodeSinkInbound(GalMessage.Media.CONFIG, byteArrayOf(1, 2, 3)),+ )+ assertEquals(+ InboundAudio.Observed(GalMessage.Media.ACK),+ AudioCodec.decodeSinkInbound(GalMessage.Media.ACK, byteArrayOf(1, 2, 3)),+ )+ }++ @Test+ fun `sink and mic ids are distinct across services`() {+ val ids = setOf(+ GalMessage.Media.SETUP_REQUEST,+ GalMessage.Media.START_REQUEST,+ GalMessage.Media.STOP_REQUEST,+ GalMessage.Media.CONFIG,+ GalMessage.Media.ACK,+ GalMessage.Audio.SYNC,+ GalMessage.Microphone.REQUEST,+ GalMessage.Media.DATA,+ GalMessage.Media.DATA_WITH_TIMESTAMP,+ )+ assertEquals(9, ids.size)+ }++ // ---- mic ----++ @Test+ fun `a timestamped mic chunk strips its prefix`() {+ val payload = ByteBuffer.allocate(8 + 3).order(ByteOrder.BIG_ENDIAN)+ .putLong(42L)+ .put(byteArrayOf(1, 2, 3))+ .array()+ assertEquals(+ MicChunk(42L, byteArrayOf(1, 2, 3)),+ AudioCodec.decodeMicData(GalMessage.Media.DATA_WITH_TIMESTAMP, payload),+ )+ }++ @Test+ fun `a prefix-less mic chunk keeps no timestamp`() {+ assertEquals(+ MicChunk(-1, byteArrayOf(4, 5)),+ AudioCodec.decodeMicData(GalMessage.Media.DATA, byteArrayOf(4, 5)),+ )+ }++ @Test+ fun `a truncated mic payload is observed-but-empty`() {+ assertNull(AudioCodec.decodeMicData(GalMessage.Media.DATA_WITH_TIMESTAMP, ByteArray(8)))+ assertNull(AudioCodec.decodeMicData(GalMessage.Media.DATA, ByteArray(0)))+ assertNull(AudioCodec.decodeMicData(GalMessage.Microphone.REQUEST, byteArrayOf(1)))+ }++ @Test+ fun `a mic ack names the mic session`() {+ val (type, payload) = AudioCodec.encodeMicAck()+ assertEquals(GalMessage.Media.ACK, type)+ assertEquals(+ AudioCodec.MIC_SESSION_ID,+ com.vayunmathur.auto.protocol.gal.MediaAck.parseFrom(payload).sessionId,+ )+ }++ // ---- focus preemption matrix ----++ private fun gain(role: AudioSinkRole, audio: AudioFocusState, video: VideoFocus): AudioGain =+ AudioCodec.gainFor(role, audio, video)++ @Test+ fun `full gain streams everything`() {+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_GAIN, VideoFocus.NATIVE))+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN, VideoFocus.NATIVE))+ }++ @Test+ fun `transient gain lets sys through and ducks media`() {+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT, VideoFocus.NATIVE))+ assertEquals(AudioGain.DUCKED, gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT, VideoFocus.NATIVE))+ }++ @Test+ fun `media-only mutes sys while music streams`() {+ assertEquals(AudioGain.MUTED, gain(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_MEDIA_ONLY, VideoFocus.NATIVE))+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_MEDIA_ONLY, VideoFocus.NATIVE))+ }++ @Test+ fun `transient guidance mutes media`() {+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT_GUIDANCE_ONLY, VideoFocus.NATIVE))+ assertEquals(AudioGain.MUTED, gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT_GUIDANCE_ONLY, VideoFocus.NATIVE))+ }++ @Test+ fun `loss mutes both, duckable loss keeps music quiet`() {+ for (loss in listOf(+ AudioFocusState.AUDIO_FOCUS_STATE_LOSS,+ AudioFocusState.AUDIO_FOCUS_STATE_LOSS_TRANSIENT,+ )) {+ assertEquals(AudioGain.MUTED, gain(AudioSinkRole.SYSTEM, loss, VideoFocus.NATIVE))+ assertEquals(AudioGain.MUTED, gain(AudioSinkRole.MEDIA, loss, VideoFocus.NATIVE))+ }+ assertEquals(+ AudioGain.DUCKED,+ gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_LOSS_TRANSIENT_CAN_DUCK, VideoFocus.NATIVE),+ )+ assertEquals(+ AudioGain.MUTED,+ gain(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_LOSS_TRANSIENT_CAN_DUCK, VideoFocus.NATIVE),+ )+ }++ @Test+ fun `invalid focus stays muted on a native screen`() {+ assertFalse(+ AudioCodec.mayPlay(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_INVALID, VideoFocus.NATIVE),+ )+ assertFalse(+ AudioCodec.mayPlay(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_INVALID, VideoFocus.NATIVE),+ )+ }++ @Test+ fun `projected video is the implicit grant, except the tts duck`() {+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.SYSTEM, AudioFocusState.AUDIO_FOCUS_STATE_LOSS, VideoFocus.PROJECTED))+ assertEquals(AudioGain.FULL, gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_INVALID, VideoFocus.PROJECTED))+ // The transient preemption survives the grant: TTS still ducks music.+ assertEquals(AudioGain.DUCKED, gain(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT, VideoFocus.PROJECTED))+ }++ @Test+ fun `mayPlay is anything but muted`() {+ assertTrue(AudioCodec.mayPlay(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN, VideoFocus.NATIVE))+ assertTrue(AudioCodec.mayPlay(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT, VideoFocus.NATIVE))+ assertFalse(AudioCodec.mayPlay(AudioSinkRole.MEDIA, AudioFocusState.AUDIO_FOCUS_STATE_LOSS, VideoFocus.NATIVE))+ }++ // ---- PCM helpers ----++ @Test+ fun `scaling pcm attenuates and clamps`() {+ val pcm = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN)+ .putShort(1000).putShort(Short.MAX_VALUE).array()+ val scaled = AudioCodec.scalePcm16(pcm, AudioCodec.DUCK_NUMERATOR, AudioCodec.DUCK_DENOMINATOR)+ val view = ByteBuffer.wrap(scaled).order(ByteOrder.LITTLE_ENDIAN)+ assertEquals(250, view.short)+ assertEquals((Short.MAX_VALUE / 4).toShort(), view.short)+ }++ @Test+ fun `scaling to silence and identity leave no garbage`() {+ val pcm = byteArrayOf(1, 2, 3)+ val identity = AudioCodec.scalePcm16(byteArrayOf(0, 1), 1, 1)+ assertContentEquals(byteArrayOf(0, 1), identity)+ assertContentEquals(byteArrayOf(0, 0, 3), AudioCodec.scalePcm16(pcm, 0, 4))+ }++ @Test+ fun `upsampling doubles zero-crossings and downsampling halves them`() {+ // One 16-sample sine period at 16 kHz; up to 48 kHz triples the samples.+ val period = ShortArray(16) { i -> (10_000 * kotlin.math.sin(i * 2 * kotlin.math.PI / 16)).toInt().toShort() }+ val pcm = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN).apply {+ period.forEach { putShort(it) }+ }.array()+ val up = AudioCodec.resampleLinearMono16(pcm, 16_000, 48_000)+ assertEquals(48, up.size / 2)+ val back = AudioCodec.resampleLinearMono16(up, 48_000, 16_000)+ assertEquals(16, back.size / 2)+ // Interpolation stays within the original envelope.+ val view = ByteBuffer.wrap(back).order(ByteOrder.LITTLE_ENDIAN)+ repeat(16) { assertTrue(kotlin.math.abs(view.short.toInt()) <= 10_000) }+ }++ @Test+ fun `a mono wav unwraps at its native rate`() {+ val samples = shortArrayOf(0, 1000, -1000, 3000)+ val wav = wavBytes(samples, channels = 1, rate = 16_000)+ assertEquals(WavPcm(16_000, pcmBytes(samples)), AudioCodec.stripWavToPcm16Mono(wav))+ }++ @Test+ fun `a stereo wav downmixes to mono`() {+ val left = shortArrayOf(1000, 2000)+ val right = shortArrayOf(3000, -2000)+ val wav = wavBytesStereo(left, right, rate = 16_000)+ val stripped = AudioCodec.stripWavToPcm16Mono(wav)+ assertNotNull(stripped)+ assertEquals(16_000, stripped.sampleRateHz)+ assertContentEquals(pcmBytes(shortArrayOf(2000, 0)), stripped.pcm)+ }++ @Test+ fun `a non-pcm wav is declined, not misdecoded`() {+ assertNull(AudioCodec.stripWavToPcm16Mono(ByteArray(10)))+ assertNull(AudioCodec.stripWavToPcm16Mono("RIFF....WAVEjunk".toByteArray()))+ val samples = shortArrayOf(1, 2)+ val float = wavBytes(samples, channels = 1, rate = 16_000, format = 3)+ assertNull(AudioCodec.stripWavToPcm16Mono(float))+ val fiveChannel = wavBytes(shortArrayOf(1, 2, 3, 4, 5), channels = 5, rate = 16_000)+ assertNull(AudioCodec.stripWavToPcm16Mono(fiveChannel))+ }++ private fun pcmBytes(samples: ShortArray): ByteArray =+ ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN).apply {+ samples.forEach { putShort(it) }+ }.array()++ private fun wavBytes(samples: ShortArray, channels: Int, rate: Int, format: Int = 1): ByteArray {+ val data = pcmBytes(samples)+ val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)+ header.put("RIFF".toByteArray())+ header.putInt(36 + data.size)+ header.put("WAVE".toByteArray())+ header.put("fmt ".toByteArray())+ header.putInt(16)+ header.putShort(format.toShort())+ header.putShort(channels.toShort())+ header.putInt(rate)+ header.putInt(rate * channels * 2)+ header.putShort((channels * 2).toShort())+ header.putShort(16)+ header.put("data".toByteArray())+ header.putInt(data.size)+ return header.array() + data+ }++ private fun wavBytesStereo(left: ShortArray, right: ShortArray, rate: Int): ByteArray {+ val interleaved = ByteBuffer.allocate((left.size + right.size) * 2).order(ByteOrder.LITTLE_ENDIAN)+ left.indices.forEach { interleaved.putShort(left[it]); interleaved.putShort(right[it]) }+ val data = interleaved.array()+ val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)+ header.put("RIFF".toByteArray())+ header.putInt(36 + data.size)+ header.put("WAVE".toByteArray())+ header.put("fmt ".toByteArray())+ header.putInt(16)+ header.putShort(1)+ header.putShort(2)+ header.putInt(rate)+ header.putInt(rate * 4)+ header.putShort(4)+ header.putShort(16)+ header.put("data".toByteArray())+ header.putInt(data.size)+ return header.array() + data+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/AudioEvent.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AudioEvent.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AudioEvent.ktnew file mode 100644index 0000000000..76259bc8db--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AudioEvent.kt@@ -0,0 +1,48 @@+package com.vayunmathur.auto.platform++/**+ * Something an audio sink or the mic source observed, forwarded to+ * [AutoSessionState] for the phone UI.+ *+ * Streaming never waits on these: they are fire-and-forget observations,+ * mirroring [VideoEvent] and [InputEvent]. The phone status screen counts+ * bytes, syncs, turns and TTS so the operator can tell "channel alive" from+ * "silent" without a live run.+ */+sealed interface AudioEvent {+ /** A sink claimed its channel; [detail] names the role and config. */+ data class SinkSetup(val role: String, val detail: String) : AudioEvent++ /** A sink changed bring-up state or arbitrated gain; the session card reads these. */+ data class SinkStatus(val status: AudioSinkStatus) : AudioEvent++ /** A sink started streaming; [configIndex] is the confirmed discovery index. */+ data class SinkStarted(val role: String, val configIndex: Int) : AudioEvent++ /** A sink stopped; the session is tearing down or focus was lost for good. */+ data class SinkStopped(val role: String) : AudioEvent++ /** PCM went out on [role]; [bytes] is the framed payload size. */+ data class FramesSent(val role: String, val bytes: Long) : AudioEvent++ /** The head unit answered a sink with the no-payload 0x800B sync pulse. */+ data class SyncReceived(val role: String) : AudioEvent++ /** The head unit acked sink frames; [ackSeq] is the mod-256 counter, unsigned. */+ data class AckReceived(val role: String, val ackSeq: Long?) : AudioEvent++ /** One TTS utterance reached the car; [chars] is its PCM sample count. */+ data class TtsSpoken(val chars: Int) : AudioEvent++ /** A TTS utterance was dropped; [reason] is short and human-readable. */+ data class TtsDropped(val reason: String) : AudioEvent++ /** One mic turn completed; [bytes] is buffered PCM, zero when unretained. */+ data class MicTurn(val bytes: Long) : AudioEvent++ /** One mic chunk was acked upstream. */+ data object MicAcked : AudioEvent++ /** Mic audio arrived but retention is off, so only the ack went out. */+ data object MicIdle : AudioEvent+}
auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.ktnew file mode 100644index 0000000000..fcb50ad9c9--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt@@ -0,0 +1,275 @@+package com.vayunmathur.auto.platform++import android.os.Handler+import android.os.HandlerThread+import android.os.SystemClock+import android.util.Log+import com.vayunmathur.auto.protocol.AudioCodec+import com.vayunmathur.auto.protocol.AudioGain+import com.vayunmathur.auto.protocol.AudioSinkRole+import com.vayunmathur.auto.protocol.FocusArbitration+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.InboundAudio+import com.vayunmathur.auto.protocol.SelectedConfig+import com.vayunmathur.auto.protocol.gal.AudioFocusRequestType+import com.vayunmathur.auto.protocol.gal.Service+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.util.concurrent.atomic.AtomicInteger++/**+ * One audio sink channel: [AudioSinkRole.SYSTEM] (service 4, transient TTS+ * and pings) or [AudioSinkRole.MEDIA] (service 5, music).+ *+ * Bring-up mirrors video's (`requestSetup` on the grant -> CONFIG answered+ * with a focus ask on control 0x18 -> START with the confirmed config), and+ * each sink's samples are written by its own audio thread -- never the pump+ * thread, never the video vsync drain. The only thing shared with the pump+ * is [GalConnection.send], which enqueues and flushes under the connection's+ * engine lock (see `GalConnection`'s one-lock-many-threads discipline). The+ * sink's state is written on the audio thread and read off it only through+ * the atomic frame counter and the [AudioSinkStatus] snapshots, which hop to+ * the pump/main threads via the thread-safe `StateFlow` set in+ * [AutoSessionState.onAudioEvent].+ *+ * Feeding is file-shaped on purpose: the only phone-side audio sources in+ * scope are TTS WAV bytes (system sink) and decoded PCM (media sink). The+ * sink resamples to the negotiated rate, ducks or mutes per the arbitrated+ * focus ([AudioCodec.gainFor]), and frames at the head unit's MTU --+ * [FRAMES_PER_PACKET] of 16-bit mono samples per 0x0000 bulk frame.+ *+ * An unsupported discovery (non-PCM codec, no sane config) parks the sink in+ * [AudioSinkState.UNSUPPORTED]: observed, counted, never started. Guidance+ * (service 3) is deliberately unowned -- sensors-dev's [GuidanceChannel] stub+ * holds that shape, and this owner only answers for 4/5.+ */+class AudioSinkChannel(+ private val role: AudioSinkRole,+ private val service: Service,+ private val connection: GalConnection,+ /** Arbitrated focus; the service reads it off the session. */+ private val focus: () -> FocusArbitration = { FocusArbitration() },+ /** Fire-and-forget observations for the phone status screen; never gates. */+ private val onEvent: (AudioEvent) -> Unit = {},+) {+ val channelId: Int get() = service.id++ @Volatile+ private var state: AudioSinkState = AudioSinkState.IDLE++ @Volatile+ private var selected: SelectedConfig? = null++ @Volatile+ private var sessionId = -1++ @Volatile+ private var lastGain: AudioGain = AudioGain.MUTED++ /** Frames consumed by the head unit, mod-256 unwrapped for the UI. */+ private val ackSeq = AtomicInteger(-1)++ private var thread: HandlerThread? = null+ private var handler: Handler? = null++ /**+ * The grant arrived: claim the channel and request audio focus. Called+ * once per channel open -- sending on a channel the head unit has not+ * opened earns a bare MessageError (0xff).+ */+ fun requestSetup() {+ val pick = AudioCodec.selectConfig(service)+ if (pick == null) {+ state = AudioSinkState.UNSUPPORTED+ onEvent(AudioEvent.SinkSetup(role.name, "unsupported"))+ Log.w(TAG, "$role sink unsupported (non-PCM or no config); parked")+ publish()+ return+ }+ selected = pick+ state = AudioSinkState.SETUP+ startAudioThread()+ val (type, payload) = AudioCodec.encodeSetup()+ connection.send(channelId, type, payload)+ connection.send(connection.session.requestAudioFocus(focusRequestType()))+ onEvent(+ AudioEvent.SinkSetup(+ role.name,+ "${pick.config.samplingRate}Hz ${pick.config.numberOfBits}b " ++ "${pick.config.numberOfChannels}ch config ${pick.index}",+ ),+ )+ Log.i(TAG, "$role sink setup requested (config ${pick.index})")+ publish()+ }++ /** One message for this channel; anything else is ignored, never misparsed. */+ fun onMessage(channelId: Int, type: Int, payload: ByteArray) {+ if (channelId != this.channelId) {+ Log.w(TAG, "ignoring 0x${type.toString(16)} for channel $channelId")+ return+ }+ when (val inbound = AudioCodec.decodeSinkInbound(type, payload)) {+ is InboundAudio.Config -> onConfig(inbound)+ is InboundAudio.Ack -> {+ ackSeq.set(inbound.ackSeq?.toInt() ?: ackSeq.get())+ onEvent(AudioEvent.AckReceived(role.name, inbound.ackSeq))+ }+ is InboundAudio.Sync -> onEvent(AudioEvent.SyncReceived(role.name))+ is InboundAudio.Observed -> Log.d(TAG, "$role unhandled audio message 0x${type.toString(16)}")+ }+ }++ /**+ * Queue PCM for the car. Safe from any thread: the copy hops to the audio+ * thread, which resamples, gains and frames it. [sampleRateHz] is the+ * buffer's native rate; 16-bit mono little-endian.+ */+ fun feedPcm(pcm: ByteArray, sampleRateHz: Int) {+ val target = handler ?: return+ val snapshot = pcm.copyOf()+ target.post { writeFramed(snapshot, sampleRateHz) }+ }++ /**+ * Queue a TTS WAV file for the car. The WAV unwraps to its native rate+ * ([AudioCodec.stripWavToPcm16Mono]) and rides the same path as [feedPcm].+ * Non-PCM or malformed bytes are dropped with a count, never a crash.+ */+ fun feedWav(wav: ByteArray) {+ val target = handler ?: return+ val snapshot = wav.copyOf()+ target.post {+ val pcm = AudioCodec.stripWavToPcm16Mono(snapshot)+ if (pcm == null) {+ Log.w(TAG, "$role dropping malformed TTS wav (${snapshot.size}B)")+ onEvent(AudioEvent.TtsDropped("malformed"))+ return@post+ }+ writeFramed(pcm.pcm, pcm.sampleRateHz)+ onEvent(AudioEvent.TtsSpoken(pcm.pcm.size / 2))+ }+ }++ /** Recompute the gain against fresh arbitration; called on every focus change. */+ fun onFocusChanged() {+ lastGain = currentGain()+ publish()+ if (lastGain == AudioGain.MUTED) {+ Log.d(TAG, "$role muted by focus")+ }+ }++ fun release() {+ if (state == AudioSinkState.STARTED && sessionId >= 0) {+ val (type, payload) = AudioCodec.encodeStop()+ runCatching { connection.send(channelId, type, payload) }+ }+ state = AudioSinkState.STOPPED+ onEvent(AudioEvent.SinkStopped(role.name))+ publish()+ handler?.removeCallbacksAndMessages(null)+ handler = null+ thread?.quitSafely()+ thread = null+ }++ private fun onConfig(inbound: InboundAudio.Config) {+ val pick = selected ?: AudioCodec.selectConfig(service) ?: run {+ state = AudioSinkState.UNSUPPORTED+ publish()+ return+ }+ val confirmed = AudioCodec.confirmConfig(inbound.response, pick, service) ?: run {+ state = AudioSinkState.UNSUPPORTED+ Log.w(TAG, "$role head unit confirmed nothing usable; parked")+ publish()+ return+ }+ selected = confirmed+ sessionId = nextSessionId()+ val (type, payload) = AudioCodec.encodeStart(sessionId, confirmed.index)+ connection.send(channelId, type, payload)+ state = AudioSinkState.STARTED+ lastGain = currentGain()+ onEvent(AudioEvent.SinkStarted(role.name, confirmed.index))+ Log.i(TAG, "$role sink started (session $sessionId, config ${confirmed.index})")+ publish()+ }++ private fun writeFramed(pcm: ByteArray, sampleRateHz: Int) {+ val config = selected ?: run {+ Log.d(TAG, "$role dropping ${pcm.size}B with no confirmed config")+ return+ }+ if (state != AudioSinkState.STARTED) {+ Log.d(TAG, "$role dropping ${pcm.size}B while $state")+ return+ }+ val gain = currentGain()+ lastGain = gain+ if (gain == AudioGain.MUTED) {+ Log.d(TAG, "$role muted; dropping ${pcm.size}B")+ return+ }+ val resampled = AudioCodec.resampleLinearMono16(pcm, sampleRateHz, config.config.samplingRate)+ val scaled = if (gain == AudioGain.DUCKED) {+ AudioCodec.scalePcm16(resampled, AudioCodec.DUCK_NUMERATOR, AudioCodec.DUCK_DENOMINATOR)+ } else {+ resampled+ }+ var offset = 0+ while (offset < scaled.size) {+ val end = minOf(offset + FRAME_BYTES, scaled.size)+ val frame = timestampedFrame(scaled.copyOfRange(offset, end))+ connection.send(channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, frame)+ onEvent(AudioEvent.FramesSent(role.name, frame.size.toLong()))+ offset = end+ }+ publish()+ }++ private fun timestampedFrame(audio: ByteArray): ByteArray =+ ByteBuffer.allocate(AudioCodec.TIMESTAMP_BYTES + audio.size)+ .order(ByteOrder.BIG_ENDIAN)+ .putLong(SystemClock.elapsedRealtimeNanos() / 1_000)+ .put(audio)+ .array()++ private fun currentGain(): AudioGain {+ val arbitration = focus()+ return AudioCodec.gainFor(role, arbitration.audioFocus, arbitration.videoFocus)+ }++ private fun focusRequestType(): AudioFocusRequestType =+ if (role == AudioSinkRole.SYSTEM) {+ AudioFocusRequestType.AUDIO_FOCUS_GAIN_TRANSIENT+ } else {+ AudioFocusRequestType.AUDIO_FOCUS_GAIN+ }++ private fun startAudioThread() {+ if (thread != null) return+ val name = "ma-auto-audio-${role.name.lowercase()}"+ thread = HandlerThread(name).also {+ it.start()+ handler = Handler(it.looper)+ }+ }++ private fun publish() {+ onEvent(AudioEvent.SinkStatus(AudioSinkStatus(role, state, lastGain)))+ }++ private companion object {+ const val TAG = "MaAuto.Audio"++ /** Samples per 0x0000 bulk frame: 1024 mono samples at the negotiated rate. */+ const val FRAMES_PER_PACKET = 1024+ const val FRAME_BYTES = FRAMES_PER_PACKET * 2++ private val sessions = AtomicInteger(0)+ private fun nextSessionId(): Int = sessions.getAndIncrement()+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/AudioState.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AudioState.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AudioState.ktnew file mode 100644index 0000000000..c3409730a3--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AudioState.kt@@ -0,0 +1,34 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.AudioGain+import com.vayunmathur.auto.protocol.AudioSinkRole++/** Where a sink is in its bring-up. */+enum class AudioSinkState {+ /** Channel granted but setup not yet answered, or never attempted. */+ IDLE,++ /** Setup sent; waiting on the head unit's 0x8003 config answer. */+ SETUP,++ /** Streaming: start sent with a confirmed config. */+ STARTED,++ /** Torn down with the session. */+ STOPPED,++ /** Discovery cannot carry PCM (non-PCM codec, no sane config): never started. */+ UNSUPPORTED,+}++/**+ * Phone-visible snapshot of one audio sink: which role, its bring-up state,+ * and the current arbitrated gain. Published through [AudioEvent.SinkStatus]+ * on every transition and every focus change, so the session card reads one+ * source of truth instead of polling the channel.+ */+data class AudioSinkStatus(+ val role: AudioSinkRole,+ val state: AudioSinkState,+ val gain: AudioGain,+)
auto/src/main/java/com/vayunmathur/auto/platform/CarTts.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarTts.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarTts.ktnew file mode 100644index 0000000000..0aabc4321f--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarTts.kt@@ -0,0 +1,138 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.os.Handler+import android.os.HandlerThread+import android.speech.tts.TextToSpeech+import android.speech.tts.UtteranceProgressListener+import android.util.Log+import java.io.File+import java.util.Locale+import java.util.UUID++/**+ * Speaks notification text on the car speakers through the system sink (ch4).+ *+ * The platform [TextToSpeech] engine synthesizes to a WAV file on a+ * background thread; the sink unwraps it ([AudioCodec.stripWavToPcm16Mono])+ * and frames it as 0x0000 bulk. Synthesis is fire-and-forget: a missing+ * engine, a failed file or an overlong utterance drops with a count, never a+ * crash and never a block of the caller.+ *+ * Owns its own thread -- never the pump thread, never the sink's audio+ * thread. The only thing shared is the sink's thread-safe [AudioSinkChannel.feedWav].+ */+class CarTts(+ context: Context,+ private val systemSink: () -> AudioSinkChannel?,+ private val onEvent: (AudioEvent) -> Unit = {},+) {+ private val appContext = context.applicationContext++ private var thread: HandlerThread? = null+ private var handler: Handler? = null++ @Volatile+ private var engine: TextToSpeech? = null++ @Volatile+ private var engineReady = false++ fun start() {+ val worker = HandlerThread("ma-auto-tts").also { it.start() }+ thread = worker+ handler = Handler(worker.looper)+ handler?.post {+ engine = TextToSpeech(appContext) { status ->+ engineReady = status == TextToSpeech.SUCCESS+ if (engineReady) {+ engine?.language = Locale.getDefault()+ engine?.setOnUtteranceProgressListener(progressListener)+ } else {+ Log.w(TAG, "tts engine unavailable (status $status)")+ }+ }+ }+ }++ /** Reads [text] aloud on the car speakers. Fire-and-forget. */+ fun speak(text: String) {+ val target = handler ?: return+ val snapshot = text.take(MAX_CHARS)+ target.post { synthesize(snapshot) }+ }++ fun stop() {+ handler?.removeCallbacksAndMessages(null)+ handler?.post {+ runCatching { engine?.stop(); engine?.shutdown() }+ engine = null+ engineReady = false+ }+ thread?.quitSafely()+ thread = null+ handler = null+ }++ private fun synthesize(text: String) {+ val tts = engine+ if (!engineReady || tts == null) {+ Log.d(TAG, "dropping ${text.length} chars; tts not ready")+ onEvent(AudioEvent.TtsDropped("engine-unready"))+ return+ }+ val sink = systemSink() ?: run {+ Log.d(TAG, "dropping ${text.length} chars; no system sink")+ onEvent(AudioEvent.TtsDropped("no-sink"))+ return+ }+ val file = File(appContext.cacheDir, "maauto-tts-${UUID.randomUUID()}.wav")+ val utteranceId = file.name+ val queued = tts.synthesizeToFile(text, null, file, utteranceId)+ if (queued != TextToSpeech.SUCCESS) {+ Log.w(TAG, "tts synthesize failed ($queued)")+ runCatching { file.delete() }+ onEvent(AudioEvent.TtsDropped("synthesize-failed"))+ return+ }+ // synthesizeToFile returns before the file lands; the progress+ // listener feeds the sink on onDone. A stuck utterance stays a stuck+ // file in the cache dir, which the OS reclaims -- never a stuck call.+ pending[utteranceId] = PendingUtterance(sink, file)+ }++ private data class PendingUtterance(val sink: AudioSinkChannel, val file: File)++ private val pending = mutableMapOf<String, PendingUtterance>()++ private val progressListener = object : UtteranceProgressListener() {+ override fun onStart(utteranceId: String?) = Unit++ override fun onDone(utteranceId: String?) {+ val pendingUtterance = synchronized(pending) { pending.remove(utteranceId) }+ ?: return+ val wav = runCatching { pendingUtterance.file.readBytes() }.getOrNull()+ runCatching { pendingUtterance.file.delete() }+ if (wav == null) {+ onEvent(AudioEvent.TtsDropped("read-failed"))+ return+ }+ pendingUtterance.sink.feedWav(wav)+ }++ override fun onError(utteranceId: String?) {+ synchronized(pending) { pending.remove(utteranceId) }?.let {+ runCatching { it.file.delete() }+ }+ Log.w(TAG, "tts utterance $utteranceId failed")+ onEvent(AudioEvent.TtsDropped("utterance-error"))+ }+ }++ private companion object {+ const val TAG = "MaAuto.Tts"++ /** A utterance longer than this is trimmed: car TTS is prompts, not chapters. */+ const val MAX_CHARS = 400+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/MicPermission.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MicPermission.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MicPermission.ktnew file mode 100644index 0000000000..eadd5edc1f--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MicPermission.kt@@ -0,0 +1,21 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.content.pm.PackageManager+import androidx.core.content.ContextCompat++/**+ * The microphone permission gate.+ *+ * Receiving the car's mic audio and acking it needs no permission, but+ * retaining a turn for transcription does: without an explicit grant no voice+ * data is buffered ([MicSourceChannel] acks and counts only). The grant also+ * covers the phone-side fallback a future transcriber may need.+ */+object MicPermission {+ fun isGranted(context: Context): Boolean =+ ContextCompat.checkSelfPermission(+ context,+ android.Manifest.permission.RECORD_AUDIO,+ ) == PackageManager.PERMISSION_GRANTED+}
auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.ktnew file mode 100644index 0000000000..cd55fb906b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt@@ -0,0 +1,152 @@+package com.vayunmathur.auto.platform++import android.os.Handler+import android.os.HandlerThread+import android.util.Log+import com.vayunmathur.auto.protocol.AudioCodec+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage++/**+ * The microphone source channel: the car's microphone, service 6.+ *+ * Direction is the reverse of the sinks: the CAR sends bulk PCM (0x0000 with+ * an 8-byte timestamp prefix, or prefix-less 0x0001) plus 0x8006 mic+ * requests, and the PHONE answers each chunk with a 0x8004 ack. There is no+ * setup/start handshake on this channel -- the head unit opens it and starts+ * talking, and we ack from the first chunk.+ *+ * Retention is permission-gated ([MicPermission]): without RECORD_AUDIO no+ * voice data is buffered -- chunks are acked and counted only, so the head+ * unit sees a live endpoint while the phone keeps nothing. With the grant, a+ * voice-reply turn buffers chunks until [endTurn] and hands the PCM to its+ * callback; a TTS/speak turn needs no buffer and only counts.+ *+ * All turn work lands on the mic's own thread -- never the pump thread --+ * and the only thing shared with the pump is [GalConnection.send], which is+ * thread-safe under the connection's engine lock.+ */+class MicSourceChannel(+ private val connection: GalConnection,+ /** Whether buffered retention is allowed; read per turn, so a mid-session grant applies. */+ private val retentionAllowed: () -> Boolean = { false },+ /** Fire-and-forget observations for the phone status screen; never gates. */+ private val onEvent: (AudioEvent) -> Unit = {},+) {+ val channelId: Int get() = com.vayunmathur.auto.protocol.GalService.AUDIO_SOURCE.id++ private var open = false++ @Volatile+ private var retained: ByteArray? = null++ @Volatile+ private var turnCallback: ((ByteArray) -> Unit)? = null++ private var thread: HandlerThread? = null+ private var handler: Handler? = null++ /** The grant arrived: mark the channel open. Called once per channel open. */+ fun onChannelOpen() {+ open = true+ startMicThread()+ Log.i(TAG, "mic channel open; acking upstream chunks")+ }++ /** One message for this channel; anything else is ignored, never misparsed. */+ fun onMessage(channelId: Int, type: Int, payload: ByteArray) {+ if (channelId != this.channelId) {+ Log.w(TAG, "ignoring 0x${type.toString(16)} for channel $channelId")+ return+ }+ if (type == GalMessage.Microphone.REQUEST) {+ Log.d(TAG, "mic request (${payload.size}B); acking")+ ack()+ return+ }+ val chunk = AudioCodec.decodeMicData(type, payload)+ if (chunk == null) {+ Log.d(TAG, "unhandled mic message 0x${type.toString(16)}")+ return+ }+ val target = handler ?: run {+ ack()+ return+ }+ val snapshot = chunk.pcm.copyOf()+ target.post {+ if (retentionAllowed() && retained != null) {+ retained = retained!! + snapshot+ } else {+ onEvent(AudioEvent.MicIdle)+ }+ ack()+ }+ }++ /**+ * Opens a voice-reply turn for [MessagingAudio.beginVoiceReply]: retains+ * chunks until [endTurn] hands the PCM to [onResult]. No retention without+ * the permission grant -- the callback never fires and the turn yields+ * nothing, which the caller treats as "no reply".+ */+ fun beginTurn(onResult: (ByteArray) -> Unit) {+ val target = handler ?: return+ target.post {+ if (!retentionAllowed()) {+ Log.w(TAG, "mic turn without permission; retaining nothing")+ turnCallback = null+ retained = null+ return@post+ }+ retained = ByteArray(0)+ turnCallback = onResult+ Log.i(TAG, "mic turn started")+ }+ }++ /** Closes the turn: the buffered PCM goes to the turn callback, if any. */+ fun endTurn() {+ val target = handler ?: return+ target.post {+ val pcm = retained ?: ByteArray(0)+ val callback = turnCallback+ retained = null+ turnCallback = null+ if (callback != null && pcm.isNotEmpty()) {+ onEvent(AudioEvent.MicTurn(pcm.size.toLong()))+ callback(pcm)+ } else {+ Log.d(TAG, "mic turn ended with ${pcm.size}B; yielding nothing")+ }+ }+ }++ fun release() {+ handler?.removeCallbacksAndMessages(null)+ handler = null+ thread?.quitSafely()+ thread = null+ open = false+ retained = null+ turnCallback = null+ }++ private fun ack() {+ val (type, payload) = AudioCodec.encodeMicAck()+ runCatching { connection.send(channelId, type, payload) }+ onEvent(AudioEvent.MicAcked)+ }++ private fun startMicThread() {+ if (thread != null) return+ thread = HandlerThread("ma-auto-mic").also {+ it.start()+ handler = Handler(it.looper)+ }+ }++ private companion object {+ const val TAG = "MaAuto.Mic"+ }+}
auto/src/main/java/com/vayunmathur/auto/service/CarMessagingAudio.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/CarMessagingAudio.kt b/auto/src/main/java/com/vayunmathur/auto/service/CarMessagingAudio.ktnew file mode 100644index 0000000000..2a56950c77--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/service/CarMessagingAudio.kt@@ -0,0 +1,76 @@+package com.vayunmathur.auto.service+import android.os.Handler+import android.os.Looper+import android.util.Log+import com.vayunmathur.auto.platform.AudioEvent+import com.vayunmathur.auto.platform.AudioSinkChannel+import com.vayunmathur.auto.platform.CarTts+import com.vayunmathur.auto.platform.MessagingAudio+import com.vayunmathur.auto.platform.MicSourceChannel++/**+ * The audio half of messaging, backed by the Phase 3 channels.+ *+ * Lazily resolved: ch14 opens before ch4/6 in wire order, so the sinks+ * may not exist when the messaging owner is created -- and TTS starts+ * with the session, so early utterances must not need a sink yet. Both+ * lambdas are read per call; a missing channel drops with a count.+ *+ * Notify/TTS synthesizes phone-side and frames out the WAV on the system+ * sink (ch4). A voice reply opens a ch6 mic turn whose retained PCM comes+ * back on [onResult] -- transcription itself is the message app's job (or+ * a future on-device pass), so the raw bytes hand off undecoded exactly+ * like a typed reply's text hands off unsent: this service knows GAL, not+ * SMS.+ *+ * Retires [MessagingAudio.NoOp]: the seam interface is unchanged, so+ * `MessagingCarAppService` codes against the same two methods.+ */+class CarMessagingAudio(+ private val tts: () -> CarTts?,+ private val mic: () -> MicSourceChannel?,+ private val onEvent: (AudioEvent) -> Unit = {},+ /** Hands retained mic PCM to whoever transcribes; empty when nobody does. */+ private val transcribe: (ByteArray, (String) -> Unit) -> Unit = { _, _ -> },+) : MessagingAudio {++ override fun speakOnCar(text: String) {+ tts()?.speak(text) ?: onEvent(AudioEvent.TtsDropped("no-tts"))+ }++ override fun beginVoiceReply(threadId: String, onResult: (String) -> Unit) {+ val channel = mic() ?: run {+ Log.w(TAG, "voice reply for $threadId with no mic channel")+ return+ }+ channel.beginTurn { pcm ->+ if (pcm.isEmpty()) {+ Log.d(TAG, "mic turn for $threadId yielded nothing")+ return@beginTurn+ }+ transcribe(pcm) { text ->+ if (text.isNotBlank()) {+ Log.i(TAG, "mic turn for $threadId transcribed ${text.length} chars")+ onResult(text)+ } else {+ Log.d(TAG, "mic turn for $threadId transcribed nothing")+ }+ }+ // The turn stays open until the head unit ends it; the service+ // closes it on release or on the next reply-begin.+ channel.endTurn()+ }+ // Bound the turn: an unanswered mic stream must not retain forever.+ Handler(Looper.getMainLooper()).postDelayed(+ { channel.endTurn() },+ TURN_TIMEOUT_MS,+ )+ }++ private companion object {+ const val TAG = "MaAuto.MessagingAudio"++ /** A voice-reply turn longer than this is closed and yielded as-is. */+ const val TURN_TIMEOUT_MS = 15_000L+ }+}
auto/src/main/java/com/vayunmathur/auto/ui/AudioRow.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/AudioRow.kt b/auto/src/main/java/com/vayunmathur/auto/ui/AudioRow.ktnew file mode 100644index 0000000000..5ad55fd160--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AudioRow.kt@@ -0,0 +1,60 @@+package com.vayunmathur.auto.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.AudioSinkRole+import com.vayunmathur.auto.platform.AudioSinkState+import com.vayunmathur.auto.platform.AudioSinkStatus+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text++/**+ * What ch4/5/6 did this session: per-sink bring-up state and arbitrated+ * gain, PCM bytes framed out, mic turns and acks, TTS utterances spoken.+ * Counters reset per socket, like the frame/ack counts above.+ */+@Composable+fun AudioRow(+ sinkStatus: Map<AudioSinkRole, AudioSinkStatus>,+ bytesSent: Long,+ micTurns: Long,+ micAcks: Long,+ ttsSpoken: Long,+) {+ val sys = sinkStatus[AudioSinkRole.SYSTEM]+ val media = sinkStatus[AudioSinkRole.MEDIA]+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_audio_sys)) },+ supportingContent = { Text(sys.describe()) },+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_audio_media)) },+ supportingContent = { Text(media.describe()) },+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_audio_bytes)) },+ supportingContent = { Text(stringResource(R.string.session_audio_bytes_value, bytesSent)) },+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_audio_mic)) },+ supportingContent = {+ Text(stringResource(R.string.session_audio_mic_value, micTurns, micAcks))+ },+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_audio_tts)) },+ supportingContent = { Text(stringResource(R.string.session_audio_tts_value, ttsSpoken)) },+ )+}++@Composable+private fun AudioSinkStatus?.describe(): String = when {+ this == null -> stringResource(R.string.session_audio_sink_none)+ state == AudioSinkState.UNSUPPORTED -> stringResource(R.string.session_audio_sink_unsupported)+ state == AudioSinkState.STARTED -> stringResource(+ R.string.session_audio_sink_streaming,+ gain.name.lowercase().replaceFirstChar { it.uppercase() },+ )+ else -> stringResource(R.string.session_audio_sink_idle)+}
auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt b/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.ktnew file mode 100644index 0000000000..c57539b979--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt@@ -0,0 +1,80 @@+package com.vayunmathur.auto.ui++import android.Manifest+import android.content.pm.PackageManager+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompat+import com.vayunmathur.auto.R+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text++/**+ * Gates voice-reply retention on the microphone permission.+ *+ * The mic channel itself needs no permission -- chunks are acked and counted+ * regardless -- but retaining a turn for transcription does. Without the+ * grant the head unit still sees a live endpoint while the phone keeps+ * nothing ([MicSourceChannel] fail-closed). Denials report on the shared+ * snackbar host -- never a Toast.+ */+@Composable+fun MicPermissionCard(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ var granted by remember {+ mutableStateOf(+ ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==+ PackageManager.PERMISSION_GRANTED,+ )+ }+ val requestor = rememberLauncherForActivityResult(+ ActivityResultContracts.RequestPermission(),+ ) { granted = it }+ Card(modifier.fillMaxWidth()) {+ Column(Modifier.padding(vertical = 8.dp)) {+ SettingsSection(title = stringResource(R.string.mic_headline)) {+ Text(+ text = stringResource(R.string.mic_body),+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.mic_permission)) },+ supportingContent = {+ Text(+ stringResource(+ if (granted) R.string.mic_permission_granted+ else R.string.mic_permission_missing,+ ),+ )+ },+ trailingContent = {+ if (!granted) {+ Button(onClick = {+ requestor.launch(Manifest.permission.RECORD_AUDIO)+ }) {+ Text(stringResource(R.string.mic_allow))+ }+ }+ },+ )+ }+ }+ }+}