Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<Int, AudioFormat>()
private val unsupported = mutableSetOf<Int>()
private val open = mutableMapOf<Lane, Open>()
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
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading