diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeAudio.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeAudio.kt new file mode 100644 index 0000000..b944e65 --- /dev/null +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeAudio.kt @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-27 + +package org.openxplay.stream.carlife + +import kotlin.math.abs +import org.openxplay.stream.core.AudioCodec +import org.openxplay.stream.core.AudioFormat +import org.openxplay.stream.core.AudioPacket +import org.openxplay.stream.core.AudioRole + +/** Lane state belongs to the audio worker. The protocol thread can change music focus without waiting for I/O. */ +internal class CarlifeAudio( + private val send: (Int, Int, ByteArray) -> Boolean, + private val now: () -> Long = System::nanoTime, + private val diagnostic: (String) -> Unit = {}, +) { + enum class Lane( + val channel: Int, val initId: Int, val dataId: Int, val endId: Int, + val prebufferBytes: Int, val silenceHoldNanos: Long, + ) { + MUSIC(3, 196609, 196614, 196610, 51_200, 0), + PROMPT(4, 262145, 262147, 262146, 16_384, 800_000_000), + VOICE(5, 327682, 327683, 327684, 16_384, 2_000_000_000); + + companion object { + fun of(role: AudioRole): Lane = when (role) { + AudioRole.MEDIA -> MUSIC + AudioRole.ALERT, AudioRole.OTHER -> PROMPT + AudioRole.VOICE, AudioRole.TELEPHONY -> VOICE + } + } + } + + private class Open(val stream: Int, val format: AudioFormat, var lastSoundAt: Long) { + val frameBytes = format.channels * 2 + val chunkBytes = (format.sampleRate / 25) * frameBytes + var bytes = 0L + fun facts() = "stream=$stream role=${format.role} rate=${format.sampleRate} channels=${format.channels}" + } + + private val formats = mutableMapOf() + private val unsupported = mutableSetOf() + private val open = mutableMapOf() + private val bytes = LongArray(Lane.entries.size) + private val utterances = LongArray(Lane.entries.size) + private var dropped = 0L + private var lastStatsAt: Long? = null + @Volatile var stats: String = "audio=idle" + private set + + private val focus = Any() + private var musicHeld = false + private var musicInvalidated = false + private var musicOpen = false + val carriesMusic: Boolean get() = synchronized(focus) { musicOpen } + + /** Returns true once per permanent focus loss while music is playing. */ + fun musicFocusLost(): Boolean = synchronized(focus) { + if (!musicOpen) return false + musicOpen = false + musicHeld = true + musicInvalidated = true + true + } + + /** Returns whether a play key needs to be forwarded to the source. */ + fun musicResumed(): Boolean = synchronized(focus) { + musicHeld = false + !musicOpen + } + + fun format(stream: Int, format: AudioFormat?) { + val previous = formats.remove(stream) + open.entries.firstOrNull { it.value.stream == stream }?.key?.let { + end(it, if (format == null) "stream_ended" else "format_changed") + } + if (format == null) return + if (!accepts(format)) { + if (unsupported.add(stream)) { + diagnostic("audio_unsupported stream=$stream role=${format.role} codec=${format.codec} " + + "rate=${format.sampleRate} channels=${format.channels}") + } + return + } + formats[stream] = format + if (format.role == AudioRole.MEDIA && previous?.role != AudioRole.MEDIA) musicResumed() + } + + fun packet(packet: AudioPacket) { + val format = formats[packet.stream] ?: return + val lane = Lane.of(format.role) + if (lane == Lane.MUSIC && !allowMusic()) { dropped++; return } + val frameBytes = format.channels * 2 + val size = packet.data.size / frameBytes * frameBytes + if (size == 0) return + val time = now() + val loud = lane == Lane.MUSIC || audible(packet.data, size) + val current = open[lane] ?: run { + if (!loud) return + val init = ProtoWriter().number(1, format.sampleRate.toLong()) + .number(2, format.channels.toLong()).number(3, 16).build() + if (!send(lane.channel, lane.initId, init)) { dropped++; return } + Open(packet.stream, format, time).also { + open[lane] = it + if (lane == Lane.MUSIC) synchronized(focus) { musicOpen = !musicHeld && !musicInvalidated } + utterances[lane.ordinal]++ + diagnostic("audio_lane_started lane=$lane ${it.facts()}") + } + } + if (current.stream != packet.stream) { dropped++; return } + if (loud) current.lastSoundAt = time + write(lane, current, packet.data, size, send) + if (lane != Lane.MUSIC && time - current.lastSoundAt >= lane.silenceHoldNanos) end(lane, "silence") + } + + fun tick() { + allowMusic() + val time = now() + for (lane in Lane.entries) { + if (lane == Lane.MUSIC) continue + val current = open[lane] ?: continue + if (time - current.lastSoundAt >= lane.silenceHoldNanos) end(lane, "silence") + } + val last = lastStatsAt + if (last == null || time - last >= 100_000_000) { + lastStatsAt = time + stats = counters() + } + } + + fun channelReplaced(lane: Lane) { + end(lane, "channel_replaced", writer = null) + } + + fun reset() { + for (lane in Lane.entries) end(lane, "source_reset") + formats.clear() + synchronized(focus) { musicHeld = false; musicInvalidated = false } + } + + fun close(writeClosing: (Int, Int, ByteArray) -> Boolean = send) { + for (lane in Lane.entries) end(lane, "session_ended", writeClosing) + stats = counters() + diagnostic("audio_summary $stats") + } + + private fun counters(): String = Lane.entries.joinToString(" ") { + val name = it.name.lowercase() + "${name}Bytes=${bytes[it.ordinal]} ${name}Streams=${utterances[it.ordinal]}" + } + " audioDropped=$dropped" + + private fun allowMusic(): Boolean { + val invalidated = synchronized(focus) { musicInvalidated.also { musicInvalidated = false } } + if (invalidated) end(Lane.MUSIC, "headunit_focus_lost") + return synchronized(focus) { !musicHeld && !musicInvalidated } + } + + private fun write( + lane: Lane, current: Open, pcm: ByteArray, size: Int, writer: (Int, Int, ByteArray) -> Boolean, + ) { + var offset = 0 + while (offset < size) { + if (lane == Lane.MUSIC && !carriesMusic) break + val count = minOf(current.chunkBytes, size - offset) + if (writer(lane.channel, lane.dataId, pcm.copyOfRange(offset, offset + count))) { + current.bytes += count + bytes[lane.ordinal] += count + } else { + dropped++ + break + } + offset += count + } + } + + private fun end(lane: Lane, reason: String, writer: ((Int, Int, ByteArray) -> Boolean)? = send) { + val current = open.remove(lane) ?: return + if (lane == Lane.MUSIC) synchronized(focus) { musicOpen = false } + // Short spoken clips need a full prebuffer even when the source ends early. + if (writer != null && lane != Lane.MUSIC && current.bytes < lane.prebufferBytes) { + val missing = lane.prebufferBytes - current.bytes.toInt() + write(lane, current, ByteArray(missing), missing, writer) + } + if (writer != null && !writer(lane.channel, lane.endId, byteArrayOf())) dropped++ + diagnostic("audio_lane_ended lane=$lane ${current.facts()} reason=$reason bytes=${current.bytes}") + } + + companion object { + private fun accepts(format: AudioFormat): Boolean = + format.codec == AudioCodec.PCM_S16LE && format.sampleRate in 8_000..48_000 && format.channels in 1..2 + + private fun audible(pcm: ByteArray, size: Int): Boolean { + for (offset in 0 until size step 2) { + val sample = ((pcm[offset].toInt() and 0xff) or (pcm[offset + 1].toInt() shl 8)).toShort() + if (abs(sample.toInt()) > 32) return true + } + return false + } + } +} diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeInput.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeInput.kt index b3914ca..b4ea14f 100644 --- a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeInput.kt +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeInput.kt @@ -64,7 +64,9 @@ internal object CarlifeInput { } // Android key values are the only mapping supplied by this transport. Unknown keys stay local. - fun key(payload: ByteArray): KeyCode? = when (Proto.parse(payload).number(1)?.toInt()) { + fun key(payload: ByteArray): KeyCode? = key(Proto.parse(payload).number(1)?.toInt()) + + fun key(code: Int?): KeyCode? = when (code) { 3 -> KeyCode.HOME 4 -> KeyCode.BACK 19 -> KeyCode.KNOB_UP @@ -73,9 +75,9 @@ internal object CarlifeInput { 22 -> KeyCode.KNOB_RIGHT 23, 66 -> KeyCode.SELECT 79, 85 -> KeyCode.PLAY_PAUSE - 87 -> KeyCode.NEXT - 88 -> KeyCode.PREVIOUS - 219, 231 -> KeyCode.VOICE + 16, 87 -> KeyCode.NEXT + 15, 88 -> KeyCode.PREVIOUS + 33, 219, 231 -> KeyCode.VOICE else -> null } } diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeMicrophone.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeMicrophone.kt new file mode 100644 index 0000000..8f39466 --- /dev/null +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeMicrophone.kt @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-27 + +package org.openxplay.stream.carlife + +import org.openxplay.stream.core.AudioCodec +import org.openxplay.stream.core.ControlEvent +import org.openxplay.stream.core.MicRequest +import org.openxplay.stream.core.Origin +import org.openxplay.stream.core.audio.PcmResampler + +/** Converts and frames the head unit's 16 kHz mono S16LE microphone stream. */ +internal class CarlifeMicrophone(val request: MicRequest, private val origin: Origin) { + private val resampler = PcmResampler(16_000, 1, request.sampleRate, request.channels) + private val frameProduct = request.sampleRate.toLong() * request.frameMs + private val bytesPerSample = request.channels * 2 + private var framePhase = 0L + private var samplesSent = 0L + private var pending = byteArrayOf() + + fun append(pcm: ByteArray, emit: (ControlEvent.MicPacket) -> Unit) { + val converted = resampler.process(pcm) + val data = pending + converted + var offset = 0 + while (true) { + val phase = frameProduct + framePhase + val samples = phase / 1_000 + val bytes = samples * bytesPerSample + if (bytes > data.size - offset) break + val end = offset + bytes.toInt() + val ptsUs = samplesSent * 1_000_000 / request.sampleRate + emit(ControlEvent.MicPacket(request.stream, data.copyOfRange(offset, end), ptsUs, origin)) + offset = end + samplesSent += samples + framePhase = phase % 1_000 + } + pending = data.copyOfRange(offset, data.size) + } + + companion object { + fun accepts(request: MicRequest): Boolean = + request.codec == AudioCodec.PCM_S16LE && request.sampleRate in 8_000..48_000 && + request.channels in 1..2 && request.frameMs > 0 && + (request.sampleRate.toLong() * request.frameMs + 999) / 1_000 <= Int.MAX_VALUE / (request.channels * 2) + } +} diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt index d1319b7..55046e6 100644 --- a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt @@ -21,6 +21,8 @@ import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock import org.openxplay.stream.core.* import org.openxplay.stream.core.codec.AvcConfig import org.openxplay.stream.core.codec.Nal @@ -35,12 +37,60 @@ public class CarlifeOutput( private val listener: CarlifeListener = CarlifeListener {}, override val id: String = "carlife", ) : ProjectionOutput { + private companion object { + const val AUDIO_QUEUE_PACKETS = 32 + const val AUDIO_QUEUE_BYTES = 256 * 1024 + } + private data class PendingFrame(val frame: VideoFrame, val format: VideoFormat, val epoch: Long) + private class AudioAnnouncement(val format: AudioFormat) + private data class PendingAudio( + val packet: AudioPacket, + val formats: Map, + val owner: CarlifeSession, + ) + private data class AudioWork( + val owner: CarlifeSession?, + val epoch: Long, + val formats: Map, + val microphone: MicRequest?, + val packet: PendingAudio?, + val cleanup: (() -> Unit)?, + ) + private class Run(val host: OutputHost, val executor: ScheduledThreadPoolExecutor, val watchdog: ScheduledThreadPoolExecutor) { val active = AtomicBoolean(true) val servers = mutableListOf() val queue = ArrayBlockingQueue(3) val epoch = AtomicLong() + // The lock protects only the mailbox. All transport I/O happens after releasing it. + val audioLock = ReentrantLock() + val audioWake = audioLock.newCondition() + val audioQueue = ArrayDeque(AUDIO_QUEUE_PACKETS) + var audioQueueBytes = 0 + val droppedAudio = AtomicLong() + var audioChanged = false + var audioStopping = false + var audioFormats = emptyMap() + @Volatile var microphone: MicRequest? = null + var audioCleanup: (() -> Unit)? = null + @Volatile var audioEpoch = 0L + + fun signalAudio() { + audioChanged = true + audioWake.signal() + } + + fun pollAudio(): PendingAudio? = audioQueue.removeFirstOrNull()?.also { + audioQueueBytes -= it.packet.data.size + } + + fun clearAudioPackets() = audioLock.withLock { + droppedAudio.addAndGet(audioQueue.size.toLong()) + audioQueue.clear() + audioQueueBytes = 0 + signalAudio() + } val readers = Semaphore(14) val receivedFrames = AtomicLong() val droppedFrames = AtomicLong() @@ -86,6 +136,7 @@ public class CarlifeOutput( } } threads.newThread { media(fresh) }.start() + threads.newThread { audio(fresh) }.apply { name = "carlife-audio" }.start() } private fun publish(current: Run, next: CarlifeStatus) { @@ -105,10 +156,16 @@ public class CarlifeOutput( selected = CarlifeSession(peer, config, deviceInfo, fenced, Origin(id, "carlife-${System.nanoTime()}"), { if (live()) publish(current, it) }, { // Terminal diagnostics survive close; host callbacks and a later lifecycle remain fenced. - if (current.session === selected && (run === current || run == null)) runCatching { listener.diagnostic(it) } + val terminalAudio = !selected.active.get() && it.contains(" audio_") + if ((current.session === selected || terminalAudio) && (run === current || run == null)) { + runCatching { listener.diagnostic(it) } + } }, { current.format }, { "sourceFrames=${current.receivedFrames.get()} sourceKeyframes=${current.receivedKeyframes.get()} " + - "dropped=${current.droppedFrames.get()} queue=${current.queue.size}" }) + "dropped=${current.droppedFrames.get()} queue=${current.queue.size} audioQueueDropped=${current.droppedAudio.get()}" }, + wakeAudio = { current.audioLock.withLock { current.signalAudio() } }, + microphoneCurrent = { current.microphone === it }, + finishAudio = { finish, abort -> finishAudio(current, finish, abort) }) return selected } @@ -162,6 +219,7 @@ public class CarlifeOutput( val selected = if (existing == null || (channel == 1 && existing.ownsChannel(1))) { existing?.close("control_replaced") resetMedia(current) + current.clearAudioPackets() session(current, peer).also { current.session = it } } else existing selected.attach(connection) @@ -182,6 +240,7 @@ public class CarlifeOutput( if (!current.active.get() || !attached.get()) { connection.close(); return@execute } current.session?.close("accessory_replaced") resetMedia(current) + current.clearAudioPackets() val selected = session(current, "usb").also { current.session = it } selected.attach(connection) threads.newThread { read(current, selected, connection) }.start() @@ -232,6 +291,7 @@ public class CarlifeOutput( owner.failure(connection.channel, null, reason, "none") owner.close(reason) current.session = null + current.clearAudioPackets() resetMedia(current) publish(current, CarlifeStatus(CarlifeState.LISTENING, reason = reason)) } @@ -245,6 +305,7 @@ public class CarlifeOutput( selected.failure(0, null, reason, error.javaClass.simpleName) selected.close(reason) current.session = null + current.clearAudioPackets() resetMedia(current) publish(current, CarlifeStatus(CarlifeState.LISTENING, reason = reason)) } @@ -258,6 +319,7 @@ public class CarlifeOutput( runCatching { current.executor.execute { if (current.session === selected) { current.session = null + current.clearAudioPackets() resetMedia(current) publish(current, CarlifeStatus(CarlifeState.LISTENING, reason = reason)) } @@ -289,8 +351,19 @@ public class CarlifeOutput( override fun onSession(state: SessionState, config: SessionConfig) { val current = run ?: return - if (current.inputSession != state.id || state.phase == SessionPhase.ENDED) resetMedia(current) - current.inputSession = if (state.phase == SessionPhase.ENDED) null else state.id + current.audioLock.withLock { + if (current.inputSession != state.id || state.phase == SessionPhase.ENDED) { + // New source generations cannot inherit queued packets or active microphone requests. + if (current.inputSession != null || state.phase == SessionPhase.ENDED) { + current.audioFormats = emptyMap() + current.microphone = null + } + current.audioEpoch++ + current.clearAudioPackets() + resetMedia(current) + } + current.inputSession = if (state.phase == SessionPhase.ENDED) null else state.id + } } override fun onVideoFormat(screen: ScreenId, format: VideoFormat?) { @@ -402,9 +475,117 @@ public class CarlifeOutput( else -> "protocol_error" } - override fun onAudioFormat(stream: Int, format: AudioFormat?): Unit = Unit - override fun onAudioPacket(packet: AudioPacket): Unit = Unit - override fun onMicrophone(stream: Int, request: MicRequest?): Unit = Unit + override fun onAudioFormat(stream: Int, format: AudioFormat?) { + val current = run ?: return + if (format != null && format.stream != stream) return + current.audioLock.withLock { + current.audioFormats = if (format == null) current.audioFormats - stream + else current.audioFormats + (stream to AudioAnnouncement(format)) + current.signalAudio() + } + } + + override fun onAudioPacket(packet: AudioPacket) { + val current = run ?: return + current.audioLock.withLock { + if (!current.active.get() || packet.session != current.inputSession) return + val selected = current.session?.takeIf { it.active.get() && it.audio != null && it.carriesAudio } ?: return + if (packet.stream !in current.audioFormats) return + val size = packet.data.size + if (size > AUDIO_QUEUE_BYTES) { + current.droppedAudio.incrementAndGet() + return + } + while (current.audioQueue.size == AUDIO_QUEUE_PACKETS || + current.audioQueueBytes + size > AUDIO_QUEUE_BYTES) { + current.pollAudio() + current.droppedAudio.incrementAndGet() + } + current.audioQueue.addLast(PendingAudio(packet, current.audioFormats, selected)) + current.audioQueueBytes += size + current.signalAudio() + } + } + + override fun onMicrophone(stream: Int, request: MicRequest?) { + val current = run ?: return + if (request != null && (request.stream != stream || !CarlifeMicrophone.accepts(request))) return + current.audioLock.withLock { + if (request == current.microphone || (request == null && current.microphone?.stream != stream)) return + current.microphone = request + current.signalAudio() + } + } + + private fun audio(current: Run) { + var previous: CarlifeSession? = null + var epoch = -1L + var formats = emptyMap() + while (true) { + val work = current.audioLock.withLock { + if (!current.audioStopping && !current.audioChanged && current.audioQueue.isEmpty()) { + current.audioWake.await(100, TimeUnit.MILLISECONDS) + } + val cleanup = current.audioCleanup + current.audioCleanup = null + if (current.audioStopping && cleanup == null) return + current.audioChanged = false + val owner = current.session + val packet = current.pollAudio() + // Keep each packet ahead of format ends or changes announced after it. + val formatsAtPacket = packet?.takeIf { it.owner === owner }?.formats + AudioWork(owner, current.audioEpoch, formatsAtPacket ?: current.audioFormats, + current.microphone, packet, cleanup) + } + work.cleanup?.invoke() + val selected = work.owner ?: continue + if (selected !== current.session || !selected.active.get() || work.epoch != current.audioEpoch) continue + val audio = selected.audio ?: continue + if (selected !== previous || work.epoch != epoch) { + if (selected === previous) { + selected.setMicrophone(null) + audio.reset() + } + previous = selected + epoch = work.epoch + formats = emptyMap() + } + selected.refreshAudioChannels() + if (formats !== work.formats) { + for (stream in formats.keys - work.formats.keys) audio.format(stream, null) + for ((stream, announcement) in work.formats) { + if (formats[stream] !== announcement) audio.format(stream, announcement.format) + } + formats = work.formats + } + selected.setMicrophone(work.microphone) + val pending = work.packet + if (pending != null && pending.owner === selected && selected.carriesAudio && + current.audioEpoch == work.epoch && selected === current.session) { + audio.packet(pending.packet) + } else if (pending != null) current.droppedAudio.incrementAndGet() + audio.tick() + } + } + + private fun finishAudio(current: Run, finish: () -> Unit, abort: () -> Unit) { + // The watchdog can close the transport even if a final write or a prior packet is stalled. + val deadline = runCatching { current.watchdog.schedule({ abort() }, 4, TimeUnit.SECONDS) }.getOrNull() + val queued = current.audioLock.withLock { + if (current.audioStopping || current.audioCleanup != null || deadline == null) false + else { + current.audioCleanup = { + try { finish() } finally { deadline.cancel(false) } + } + current.signalAudio() + true + } + } + if (!queued) { + deadline?.cancel(false) + abort() + } + } override fun close() { val current = run ?: return @@ -420,8 +601,15 @@ public class CarlifeOutput( synchronized(current.servers) { current.servers.forEach { runCatching { it.close() } }; current.servers.clear() } current.session?.close("output_closed") current.queue.clear() + current.audioLock.withLock { + current.clearAudioPackets() + current.audioFormats = emptyMap() + current.microphone = null + current.audioStopping = true + current.signalAudio() + } current.executor.shutdownNow() - current.watchdog.shutdownNow() + current.watchdog.shutdown() if (run == null) runCatching { listener.onStatus(CarlifeStatus(CarlifeState.CLOSED)) } }.start() } diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt index 0a34521..44f3207 100644 --- a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt @@ -21,6 +21,9 @@ internal class CarlifeSession( private val diagnosticSink: (String) -> Unit, private val sourceFormat: () -> VideoFormat? = { null }, private val mediaCounters: () -> String = { "" }, + private val wakeAudio: () -> Unit = {}, + private val microphoneCurrent: (MicRequest) -> Boolean = { true }, + private val finishAudio: ((finish: () -> Unit, abort: () -> Unit) -> Unit)? = null, ) { val active = AtomicBoolean(true) private val channels = ConcurrentHashMap() @@ -61,10 +64,27 @@ internal class CarlifeSession( private var activeContacts: List = emptyList() private var lastSummary = createdAt private var knownFormat: VideoFormat? = null + private var displaySize: Pair? = null + @Volatile var audio: CarlifeAudio? = null + private set + val carriesAudio: Boolean get() = connected(3) + private data class Capture(val framer: CarlifeMicrophone, val startedAt: Long) { + @Volatile var sawPcm = false + var warned = false + } + @Volatile private var capture: Capture? = null + private var microphoneConnection: CarlifeConnection? = null + private var microphoneRequest: MicRequest? = null + private val audioConnections = mutableMapOf() private data class Failure(val channel: Int, val id: Int?, val cause: String) private val rootFailure = AtomicReference() private val wireLogAt = mutableMapOf() + private companion object { + val quietRxIds = setOf(131074, 425985, 425998, 360449) + val quietTxIds = setOf(131073, 131074) + CarlifeAudio.Lane.entries.map { it.dataId } + } + private fun diagnostic(event: String) { diagnosticSink("session=${origin.clientId} phase=$phase elapsedMs=${(System.nanoTime() - createdAt) / 1_000_000} $event") } @@ -88,18 +108,26 @@ internal class CarlifeSession( for (channel in 1..7) channels[channel] = connection } else channels.put(connection.channel, connection)?.close() diagnostic("transport_opened peer=$peer channel=${connection.channel} transport=${if (connection.usb) "usb" else "tcp"}") + if (connection.usb || connection.channel in 3..5) { + if (connection.usb || connection.channel == 3 || connection.channel == 5) { + displaySize?.let { (w, h) -> publishCapabilities(w, h) } + } + wakeAudio() + } } fun owns(connection: CarlifeConnection): Boolean = channels[connection.channel] === connection fun ownsChannel(channel: Int): Boolean = channels[channel] != null + private fun connected(channel: Int): Boolean = channels[channel]?.active?.get() == true + fun receive(wire: CarlifeMessage) { if (!active.get()) return val message = crypto.transform(wire, false) lastReceived.set(System.nanoTime()) received.incrementAndGet() - if (message.id !in setOf(131074, 425985, 425998)) { + if (message.id !in quietRxIds) { val now = System.nanoTime() val previous = wireLogAt[message.id] if ((previous != null && now - previous >= 10_000_000_000L) || (previous == null && wireLogAt.size < 64)) { @@ -107,6 +135,10 @@ internal class CarlifeSession( diagnostic("rx channel=${message.channel} id=${message.id} bytes=${message.payload.size}") } } + if (message.id == 360449 && message.channel == 5) { + receiveMicrophone(message.payload) + return + } if (!version && message.id != 98305) return val payload by lazy { Proto.parse(message.payload) } when (message.id) { @@ -151,7 +183,7 @@ internal class CarlifeSession( "CONNECT_TYPE" to if (channels[1]?.usb == true) 2 else 5) val writer = ProtoWriter().number(1, flags.size.toLong()) for ((key, value) in flags) writer.data(2, ProtoWriter().text(1, key).number(2, value.toLong()).build()) - send(1, 65617, writer.build()) + if (send(1, 65617, writer.build())) establishAudio() } 98386 -> { if (payload.messages(2).any { it.text(1) == "CONTENT_ENCRYPTION" && it.number(2) == 1L } && @@ -196,8 +228,9 @@ internal class CarlifeSession( encoderChannel = message.channel diagnostic("video_negotiated requested=${requestedWidth}x$requestedHeight selected=${width}x$height fps=$fps codec=H264") stage("video_negotiated") + displaySize = requestedWidth to requestedHeight publishCapabilities(requestedWidth, requestedHeight) - encoderInfo() + if (encoderInfo()) establishAudio() report(CarlifeState.AUTHENTICATED) } 98313 -> { @@ -228,15 +261,111 @@ internal class CarlifeSession( host.control(touch) }.onFailure { diagnostic("input_ignored id=${message.id} cause=invalid_touch") } } - 425992 -> if (authenticated) runCatching { CarlifeInput.key(message.payload) }.getOrNull()?.let { - diagnostic("input_key code=${it.name}") - host.control(ControlEvent.Key(it, true, origin)) - host.control(ControlEvent.Key(it, false, origin)) + 98344 -> { + val moduleStatus = runCatching { payload }.getOrNull() + val module = moduleStatus?.number(1) + val status = moduleStatus?.number(2) + diagnostic("headunit_module module=${module ?: "none"} status=${status ?: "none"}") + if (authenticated && module == 3L && status != null) { + if (status == 0L) { + if (carriesAudio && audio?.musicFocusLost() == true) { + wakeAudio() + forwardKey(KeyCode.PLAY_PAUSE) + } + } else audio?.musicResumed() + } + } + 425992 -> if (authenticated) { + val code = runCatching { payload.number(1)?.toInt() }.getOrNull() + when (code) { + 31 -> if (audio?.musicResumed() != false) { + wakeAudio() + forwardKey(KeyCode.PLAY_PAUSE) + } + 32 -> if (audio?.carriesMusic == true) forwardKey(KeyCode.PLAY_PAUSE) + else -> CarlifeInput.key(code)?.let { key -> + if (key == KeyCode.PLAY_PAUSE) audio?.musicResumed() + forwardKey(key) + } + } } // Empty keepalives and unknown extension messages are valid traffic, with no mandatory reply. } } + private fun forwardKey(key: KeyCode) { + diagnostic("input_key code=${key.name}") + host.control(ControlEvent.Key(key, true, origin)) + host.control(ControlEvent.Key(key, false, origin)) + } + + private fun establishAudio() { + if (!active.get() || audio != null) return + audio = CarlifeAudio({ channel, id, bytes -> sendAudio(channel, id, bytes) }, diagnostic = ::diagnostic) + wakeAudio() + } + + private fun sendAudio(channel: Int, id: Int, bytes: ByteArray = byteArrayOf(), closing: Boolean = false): Boolean = + runCatching { + val connection = if (channel in 3..5) audioConnections[channel] else channels[channel] + connection != null && sendOn(connection, channel, id, bytes, closing) + }.getOrElse { + diagnostic("audio_write_failed channel=$channel id=$id error=${it.javaClass.simpleName}") + false + } + + /** A replacement socket needs a fresh lane init even when the source format has not changed. */ + fun refreshAudioChannels() { + val audio = audio ?: return + for (lane in CarlifeAudio.Lane.entries) { + val wire = channels[lane.channel] ?: continue + val previous = audioConnections.put(lane.channel, wire) + if (previous != null && wire !== previous) audio.channelReplaced(lane) + } + } + + /** Called by the audio worker. The protocol reader owns the published framer's conversion state. */ + fun setMicrophone(request: MicRequest?) { + if (audio == null || !active.get()) return + val wire = channels[5]?.takeIf { it.active.get() } + if (wire !== microphoneConnection) { + microphoneConnection = wire + microphoneRequest = null + capture = null + } + if (request === microphoneRequest || wire == null) return + microphoneRequest = request + val previous = capture + if (request == null) { + capture = null + if (previous != null) microphoneControl(65571) + } else { + // Publish before starting capture so the first PCM can be handled as soon as it arrives. + val next = Capture(CarlifeMicrophone(request, origin), System.nanoTime()) + capture = next + if (previous == null && !microphoneControl(65572)) capture = null + } + } + + private fun microphoneControl(id: Int, closing: Boolean = false): Boolean { + val sent = sendAudio(1, id, closing = closing) + diagnostic("audio_mic_control id=$id outcome=${if (sent) "sent" else "failed"}") + return sent + } + + private fun receiveMicrophone(pcm: ByteArray) { + val current = capture ?: return + if (!microphoneCurrent(current.framer.request) || pcm.isEmpty() || pcm.size % 2 != 0) return + if (!current.sawPcm) { + current.sawPcm = true + diagnostic("audio_mic_first_pcm stream=${current.framer.request.stream} " + + "afterStartMs=${(System.nanoTime() - current.startedAt) / 1_000_000} bytes=${pcm.size}") + } + current.framer.append(pcm) { + if (capture === current && active.get() && microphoneCurrent(current.framer.request)) host.control(it) + } + } + private fun sendDevice() { if (deviceSent) return send(1, 65540, ProtoWriter().text(1, "Android").text(4, info.brand).text(14, info.model) @@ -250,7 +379,8 @@ internal class CarlifeSession( listOf(DecoderSupport("avc1.64002a", true), DecoderSupport("avc1.42e01f", true)), mapOf(ScreenId.MAIN to DisplayInfo(displayWidth, displayHeight, 160, fps.toDouble(), frameSize = Viewport(width, height))), touch = 10, keys = KeyCode.entries.toSet(), - audio = emptySet(), microphone = false, prefersH264 = true)) + audio = if (carriesAudio) setOf(AudioCodec.PCM_S16LE) else emptySet(), + microphone = carriesAudio && connected(5), prefersH264 = true)) } fun format(format: VideoFormat) { @@ -271,10 +401,9 @@ internal class CarlifeSession( } } - private fun encoderInfo() { + private fun encoderInfo(): Boolean = send(encoderChannel, 65544, ProtoWriter().number(1, width.toLong()).number(2, height.toLong()) .number(3, fps.toLong()).build()) - } fun video(payload: ByteArray): Boolean { if (!active.get() || !authenticated || !streaming) return false @@ -296,12 +425,18 @@ internal class CarlifeSession( if (sent.get() > 0) report(CarlifeState.STREAMING) } val now = System.nanoTime() + capture?.let { + if (!it.sawPcm && !it.warned && now - it.startedAt >= 2_000_000_000L) { + it.warned = true + diagnostic("audio_mic_silent stream=${it.framer.request.stream} msSinceStart=${(now - it.startedAt) / 1_000_000}") + } + } if (now - lastSummary >= 10_000_000_000L) { lastSummary = now diagnostic("summary rx=${received.get()} sent=${sent.get()} keyframeRequests=${keyframeRequests.get()} " + "inputDown=${inputDown.get()} inputUp=${inputUp.get()} inputMove=${inputMove.get()} " + "lastRxMs=${(now - lastReceived.get()) / 1_000_000} lastTxMs=${(now - lastSent.get()) / 1_000_000} " + - "encryption=${crypto.active} ${mediaCounters()}") + "encryption=${crypto.active} ${mediaCounters()} ${audio?.stats.orEmpty()}") } } @@ -312,12 +447,16 @@ internal class CarlifeSession( } private fun send(channel: Int, id: Int, payload: ByteArray = byteArrayOf()): Boolean { - if (!active.get()) return false val connection = channels[channel] ?: return false + return sendOn(connection, channel, id, payload, closing = false) + } + + private fun sendOn(connection: CarlifeConnection, channel: Int, id: Int, payload: ByteArray, closing: Boolean): Boolean { + if (!closing && !active.get()) return false val message = crypto.transform(CarlifeMessage(channel, id, payload), true) if (!connection.write(message)) return false lastSent.set(System.nanoTime()) - if (id != 131073 && id != 131074) diagnostic("tx channel=$channel id=$id bytes=${message.payload.size}") + if (id !in quietTxIds) diagnostic("tx channel=$channel id=$id bytes=${message.payload.size}") return true } @@ -348,12 +487,25 @@ internal class CarlifeSession( val endedCause = root?.cause ?: cause val rootChannel = root?.channel ?: 0 val affected = channels.keys.sorted().joinToString(",") - diagnostic("session_closed cause=$endedCause originChannel=$rootChannel affected=$affected sent=${sent.get()} ${mediaCounters()}") + diagnostic("session_closed cause=$endedCause originChannel=$rootChannel affected=$affected sent=${sent.get()} " + + "${mediaCounters()} ${audio?.stats.orEmpty()}") channels.values.toSet().forEach { diagnostic("transport_closed peer=$peer channel=${it.channel} transport=${if (it.usb) "usb" else "tcp"} cause=$endedCause originChannel=$rootChannel") - it.close() } - channels.clear() + fun closeTransports() { + channels.values.toSet().forEach { it.close() } + channels.clear() + } + if (audio != null && finishAudio != null) { + if (endedCause == "write_timeout") closeTransports() + finishAudio({ + try { + if (capture != null && connected(5)) microphoneControl(65571, closing = true) + capture = null + audio?.close { channel, id, bytes -> sendAudio(channel, id, bytes, closing = true) } + } finally { closeTransports() } + }, ::closeTransports) + } else closeTransports() releaseTouches() host.capabilities(OutputCapabilities(LatencyClass.INTERACTIVE, emptyList(), emptyMap(), 0, emptySet(), emptySet(), false)) diff --git a/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeAudioTest.kt b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeAudioTest.kt new file mode 100644 index 0000000..982bbbe --- /dev/null +++ b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeAudioTest.kt @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-27 + +package org.openxplay.stream.carlife + +import org.junit.jupiter.api.Test +import org.openxplay.stream.core.* +import kotlin.test.* + +class CarlifeAudioTest { + private class Fixture { + var nanos = 0L + val messages = mutableListOf() + val audio = CarlifeAudio({ channel, id, data -> + messages += CarlifeMessage(channel, id, data) + true + }, { nanos }) + + fun format(role: AudioRole, rate: Int = 16_000, channels: Int = 1) { + audio.format(7, AudioFormat(7, role, AudioCodec.PCM_S16LE, rate, channels)) + } + + fun packet(data: ByteArray) = audio.packet(AudioPacket(7, SessionId(1), data, 0)) + } + + @Test fun sendsTheLaneForEachRole() { + val protocol = mapOf( + AudioRole.MEDIA to listOf(3, 196609, 196614, 196610), + AudioRole.ALERT to listOf(4, 262145, 262147, 262146), + AudioRole.OTHER to listOf(4, 262145, 262147, 262146), + AudioRole.VOICE to listOf(5, 327682, 327683, 327684), + AudioRole.TELEPHONY to listOf(5, 327682, 327683, 327684), + ) + for ((role, ids) in protocol) { + val (channel, init, data, end) = ids + val fixture = Fixture() + fixture.format(role, rate = 44_101, channels = 2) + val pcm = ByteArray(16_387) { 1 } + fixture.packet(pcm) + fixture.audio.format(7, null) + + val messages = fixture.messages + assertTrue(messages.all { it.channel == channel }) + assertEquals(init, messages.first().id) + assertEquals(end, messages.last().id) + val format = Proto.parse(messages.first().payload) + assertEquals(listOf(44_101L, 2L, 16L), (1..3).map { format.number(it) }) + val chunks = messages.drop(1).dropLast(1) + assertTrue(chunks.all { it.id == data && it.payload.size % 4 == 0 && it.payload.size <= 7_056 }) + assertContentEquals(pcm.copyOf(16_384), chunks.flatMap { it.payload.asIterable() }.toByteArray()) + } + } + + @Test fun promptOpensOnSoundAndPadsOnAnIdleTick() { + val fixture = Fixture() + fixture.format(AudioRole.ALERT) + fixture.packet(ByteArray(320)) + assertTrue(fixture.messages.isEmpty()) + val sound = ByteArray(320) { 1 } + fixture.packet(sound) + fixture.nanos = 799_999_999 + fixture.audio.tick() + assertEquals(listOf(262145, 262147), fixture.messages.map { it.id }) + fixture.nanos++ + fixture.audio.tick() + + assertEquals(262146, fixture.messages.last().id) + val data = fixture.messages.filter { it.id == 262147 }.flatMap { it.payload.asIterable() }.toByteArray() + assertContentEquals(sound.copyOf(16_384), data) + } + + @Test fun aSilentVoicePacketClosesTheLaneAfterTwoSeconds() { + val fixture = Fixture() + fixture.format(AudioRole.VOICE) + fixture.packet(byteArrayOf(100, 0)) + fixture.nanos = 1_999_999_999 + fixture.packet(byteArrayOf(0, 0)) + assertEquals(327683, fixture.messages.last().id) + fixture.nanos++ + fixture.packet(byteArrayOf(0, 0)) + assertEquals(327684, fixture.messages.last().id) + } + + @Test fun permanentFocusLossHoldsMusicUntilPlayOrANewMediaStream() { + val fixture = Fixture() + fixture.format(AudioRole.MEDIA) + fixture.packet(byteArrayOf(0, 0)) + assertTrue(fixture.audio.carriesMusic) + assertTrue(fixture.audio.musicFocusLost()) + assertFalse(fixture.audio.musicFocusLost()) + assertFalse(fixture.audio.carriesMusic) + fixture.packet(byteArrayOf(0, 0)) + assertEquals(listOf(196609, 196614, 196610), fixture.messages.map { it.id }) + + fixture.format(AudioRole.MEDIA) + fixture.packet(byteArrayOf(0, 0)) + assertFalse(fixture.audio.carriesMusic) + assertTrue(fixture.audio.musicResumed()) + fixture.packet(byteArrayOf(0, 0)) + assertTrue(fixture.audio.carriesMusic) + + fixture.audio.musicFocusLost() + fixture.format(AudioRole.ALERT) + fixture.format(AudioRole.MEDIA) + fixture.packet(byteArrayOf(0, 0)) + assertTrue(fixture.audio.carriesMusic) + } + + @Test fun microphonePreservesPartialFramesAndSampleTimestamps() { + val origin = Origin("carlife", "test") + val microphone = CarlifeMicrophone(MicRequest(7, AudioCodec.PCM_S16LE, 16_000, 1, 20), origin) + val pcm = ByteArray(1_280) { it.toByte() } + val events = mutableListOf() + microphone.append(pcm.copyOfRange(0, 512)) { events += it } + assertTrue(events.isEmpty()) + microphone.append(pcm.copyOfRange(512, pcm.size)) { events += it } + assertEquals(listOf(0L, 20_000L), events.map { it.ptsUs }) + assertTrue(events.all { it.stream == 7 && it.origin == origin }) + assertContentEquals(pcm, events[0].data + events[1].data) + } + + @Test fun microphoneCarriesFractionalSamplesWhenResamplingToStereo() { + val request = MicRequest(7, AudioCodec.PCM_S16LE, 44_100, 2, 1) + val microphone = CarlifeMicrophone(request, Origin("carlife", "test")) + val events = mutableListOf() + repeat(4) { + microphone.append(ByteArray(128) { 1 }) { events += it } + } + val firstTen = events.take(10) + assertEquals(List(9) { 44 * 4 } + 45 * 4, firstTen.map { it.data.size }) + assertEquals((0 until 10).map { it * 44L * 1_000_000 / 44_100 }, firstTen.map { it.ptsUs }) + assertTrue(firstTen.all { packet -> + packet.data.asList().chunked(4).all { it[0] == it[2] && it[1] == it[3] } + }) + } +}