maauto: route phone music to head unit on ch5
- Commit
f744580c3048cab97203eb7f217a54edd794f053- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-13 18:29 UTC (2 months ago)
- Parents
24db5ee
Diff
auto/src/main/AndroidManifest.xml
diff --git a/auto/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlindex 27d032c3a6..c6f3f534cb 100644--- a/auto/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -29,6 +29,11 @@ itself needs no permission (chunks are acked and counted regardless); without this grant the phone keeps no voice data (fail-closed). --> <uses-permission android:name="android.permission.RECORD_AUDIO" />+ <!-- Music capture into the ch5 media sink: AudioPlaybackCapture of the USAGE_MEDIA+ mix needs the media-projection consent dialog, whose foreground service type+ is mediaProjection. The capture runs only while consented in-app AND granted+ here; either off means fail-closed silence on the head unit. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" /> <!-- The car launcher resolves Maps / Music / dialer through PackageManager. Android 11+ hides other apps by default, so these queries keep those lookups visible. The media@@ -80,6 +85,15 @@ android:name=".service.ProjectionService" android:exported="false" android:foregroundServiceType="connectedDevice" />+ <!-- Holds the media-projection token while music capture runs. Started+ only after the user grants the consent dialog (see MusicCaptureGrant):+ on API 34+ an FGS with type mediaProjection cannot start before the+ projection is registered, so this lives apart from ProjectionService+ rather than widening its foreground type and crashing bring-up. -->+ <service+ android:name=".service.MusicCaptureService"+ android:exported="false"+ android:foregroundServiceType="mediaProjection" /> <!-- Answers the USB permission round-trip and accessory detach while no activity is up; both funnel into UsbConnector. The permission action
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.ktindex 76259bc8db..7333699fd3 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AudioEvent.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AudioEvent.kt@@ -45,4 +45,10 @@ sealed interface AudioEvent { /** Mic audio arrived but retention is off, so only the ack went out. */ data object MicIdle : AudioEvent++ /** Captured music PCM went to the media sink; [bytes] is the chunk size. */+ data class MusicCaptured(val bytes: Long) : AudioEvent++ /** A music chunk was dropped (no sink, not started); [reason] is short. */+ data class MusicDropped(val reason: String) : AudioEvent }
auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.ktindex 646b7c60b5..221a2c4ce3 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt@@ -215,6 +215,10 @@ object AutoSessionState { private val _audioBytesSent = MutableStateFlow(0L) val audioBytesSent: StateFlow<Long> = _audioBytesSent.asStateFlow() + /** Music PCM bytes captured into the ch5 sink this session. */+ private val _musicBytesCaptured = MutableStateFlow(0L)+ val musicBytesCaptured: StateFlow<Long> = _musicBytesCaptured.asStateFlow()+ /** 0x800B sync pulses answered on ch4/5 this session. */ private val _audioSyncs = MutableStateFlow(0L) val audioSyncs: StateFlow<Long> = _audioSyncs.asStateFlow()@@ -303,6 +307,7 @@ object AutoSessionState { _navStatusPosts.value = 0 _sinkStatus.value = emptyMap() _audioBytesSent.value = 0+ _musicBytesCaptured.value = 0 _audioSyncs.value = 0 _audioAcks.value = 0 _ttsSpoken.value = 0@@ -474,6 +479,8 @@ object AutoSessionState { is AudioEvent.MicTurn -> _micTurns.value++ AudioEvent.MicAcked -> _micAcks.value++ AudioEvent.MicIdle -> Unit+ is AudioEvent.MusicCaptured -> _musicBytesCaptured.value += event.bytes+ is AudioEvent.MusicDropped -> Unit } }
auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.ktindex a03a2d3fb7..c7b45768c5 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt@@ -126,6 +126,10 @@ class AutoViewModel : ViewModel() { val audioBytesSent: StateFlow<Long> = AutoSessionState.audioBytesSent .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L) + /** Music PCM bytes captured into the ch5 sink this session. */+ val musicBytesCaptured: StateFlow<Long> = AutoSessionState.musicBytesCaptured+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L)+ /** ch6 mic turns that yielded retained PCM this session. */ val micTurns: StateFlow<Long> = AutoSessionState.micTurns .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L)
auto/src/main/java/com/vayunmathur/auto/platform/MusicCapture.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MusicCapture.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MusicCapture.ktnew file mode 100644index 0000000000..b8111e46d0--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MusicCapture.kt@@ -0,0 +1,216 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.media.AudioAttributes+import android.media.AudioFormat+import android.media.AudioPlaybackCaptureConfiguration+import android.media.AudioRecord+import android.media.projection.MediaProjection+import android.os.Handler+import android.os.HandlerThread+import android.util.Log+import java.nio.ByteBuffer+import java.nio.ByteOrder++/**+ * Feeds phone media audio into the car music sink (ch5) via `AudioPlaybackCapture`.+ *+ * This is the only non-root per-app capture path with explicit user consent:+ * the user grants the `MediaProjection` consent dialog once (fail-closed --+ * denial means silence on the head unit, never a crash), plus the in-app+ * switch in [MusicCapturePrefs]. `AudioRecord` loopback needs root,+ * Bluetooth rerouting fights GAL, and ExoPlayer injection only covers our own+ * app -- so capturing the `USAGE_MEDIA` mix is what carries any music app.+ *+ * Data path: an `AudioRecord` built on the capture config reads 16-bit mono+ * PCM on its own thread and hands each chunk to the sink's thread-safe+ * [AudioSinkChannel.feedPcm]; the sink resamples to the negotiated rate and+ * frames at 1024 samples with monotonic timestamps. Capture runs only while+ * the media snapshot says something is playing ([MediaPlaybackMonitor] via+ * [isPlayingNow]) -- an idle capture loop would stream silence and burn CPU.+ *+ * Owns its own thread -- never the pump thread, never the sink's audio+ * thread. The only things shared are the sink's [AudioSinkChannel.feedPcm]+ * (thread-safe) and [MediaProjection] (touched only from the capture thread).+ */+class MusicCapture(+ context: Context,+ private val mediaSink: () -> AudioSinkChannel?,+ /** Current playing flag; the service reads it off the media snapshot. */+ private val isPlayingNow: () -> Boolean = { false },+ private val onEvent: (AudioEvent) -> Unit = {},+) {+ private val appContext = context.applicationContext++ private var thread: HandlerThread? = null+ private var handler: Handler? = null++ @Volatile+ private var record: AudioRecord? = null++ @Volatile+ private var running = false++ /**+ * Starts capturing into the media sink. Safe from any thread; hops to the+ * capture thread. No-op without the in-app consent, without a projection+ * grant, or when already running. Denial degrades gracefully: the head+ * unit stays silent on ch5 and the session card keeps its zero counters.+ */+ fun start(projection: MediaProjection?) {+ val target = handler ?: run {+ Log.d(TAG, "dropping music capture start; no capture thread")+ return+ }+ target.post {+ if (running) return@post+ if (!MusicCapturePrefs.isMusicCaptureConsented(appContext)) {+ Log.i(TAG, "music capture not consented; ch5 stays silent")+ return@post+ }+ if (projection == null) {+ Log.i(TAG, "music capture without projection grant; ch5 stays silent")+ return@post+ }+ val record = buildRecord(projection) ?: return@post+ runCatching { record.startRecording() }.onFailure {+ Log.w(TAG, "music capture startRecording failed", it)+ runCatching { record.release() }+ return@post+ }+ this.record = record+ running = true+ Log.i(TAG, "music capture started (${CAPTURE_RATE_HZ}Hz mono)")+ pump()+ }+ }++ /** Stops capturing and releases the record. Safe from any thread. */+ fun stop() {+ val target = handler ?: run {+ running = false+ runCatching { record?.stop() }+ runCatching { record?.release() }+ record = null+ return+ }+ target.post {+ running = false+ runCatching { record?.stop() }+ runCatching { record?.release() }+ record = null+ Log.i(TAG, "music capture stopped")+ }+ }++ /** Starts the capture thread; called with the session, not per channel grant. */+ fun startThread() {+ if (thread != null) return+ thread = HandlerThread("ma-auto-music-capture").also {+ it.start()+ handler = Handler(it.looper)+ }+ }++ /** Stops the thread; the record is released first via [stop]. */+ fun releaseThread() {+ stop()+ handler?.removeCallbacksAndMessages(null)+ handler = null+ thread?.quitSafely()+ thread = null+ }++ /** Capture-thread loop: read PCM, forward while playing, re-post. */+ private fun pump() {+ val target = handler ?: return+ target.post {+ val active = record+ if (!running || active == null) return@post+ val chunk = ByteArray(CHUNK_BYTES)+ val read = runCatching { active.read(chunk, 0, chunk.size) }.getOrDefault(-1)+ if (read > 0) {+ if (isPlayingNow()) {+ mediaSink()?.feedPcm(chunk.copyOf(read), CAPTURE_RATE_HZ)+ onEvent(AudioEvent.MusicCaptured(read.toLong()))+ }+ // Idle snapshots drop the chunk: streaming silence wastes+ // socket bytes and keeps the sink's counters honest (music+ // only, never quiet-room noise).+ } else if (read < 0) {+ Log.w(TAG, "music capture read failed ($read); stopping")+ running = false+ runCatching { active.stop() }+ runCatching { active.release() }+ record = null+ return@post+ }+ if (running) pump()+ }+ }++ /**+ * Builds the capture record: 16-bit mono PCM at [CAPTURE_RATE_HZ] from the+ * `USAGE_MEDIA` mix. Matches the music app's ExoPlayer attributes+ * (`USAGE_MEDIA` / music content), so playback there is capturable; other+ * usages (calls, alarms) are excluded by construction.+ */+ private fun buildRecord(projection: MediaProjection): AudioRecord? {+ val config = AudioPlaybackCaptureConfiguration.Builder(projection)+ .addMatchingUsage(AudioAttributes.USAGE_MEDIA)+ .build()+ val format = AudioFormat.Builder()+ .setEncoding(AudioFormat.ENCODING_PCM_16BIT)+ .setSampleRate(CAPTURE_RATE_HZ)+ .setChannelMask(AudioFormat.CHANNEL_IN_MONO)+ .build()+ val minBytes = AudioRecord.getMinBufferSize(+ CAPTURE_RATE_HZ,+ AudioFormat.CHANNEL_IN_MONO,+ AudioFormat.ENCODING_PCM_16BIT,+ )+ if (minBytes <= 0) {+ Log.w(TAG, "music capture has no viable buffer ($minBytes)")+ return null+ }+ return runCatching {+ AudioRecord.Builder()+ .setAudioPlaybackCaptureConfig(config)+ .setAudioFormat(format)+ .setBufferSizeInBytes((minBytes * 4).coerceAtLeast(CHUNK_BYTES * 2))+ .build()+ }.getOrElse {+ Log.w(TAG, "music capture AudioRecord build failed", it)+ null+ }+ }++ /**+ * Converts a stereo interleaved 16-bit frame to mono by averaging+ * channels. Unused while the record requests mono directly; kept as the+ * documented fallback if a device refuses the mono format.+ */+ private fun stereoToMono(stereo: ByteArray): ByteArray {+ val shorts = ByteBuffer.wrap(stereo).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()+ val mono = ShortArray(shorts.remaining() / 2)+ for (i in mono.indices) {+ val left = shorts.get(i * 2).toInt()+ val right = shorts.get(i * 2 + 1).toInt()+ mono[i] = ((left + right) / 2).coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt())+ .toShort()+ }+ return ByteBuffer.allocate(mono.size * 2).order(ByteOrder.LITTLE_ENDIAN).apply {+ asShortBuffer().put(mono)+ }.array()+ }++ private companion object {+ const val TAG = "MaAuto.MusicCapture"++ /** Capture rate; the sink resamples to the head unit's negotiated rate. */+ const val CAPTURE_RATE_HZ = 48_000++ /** ~46ms of 16-bit mono at the capture rate per read. */+ const val CHUNK_BYTES = 4_096+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/MusicCapturePrefs.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MusicCapturePrefs.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MusicCapturePrefs.ktnew file mode 100644index 0000000000..333317fb38--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MusicCapturePrefs.kt@@ -0,0 +1,26 @@+package com.vayunmathur.auto.platform++import android.content.Context++/**+ * Persists the music-capture consent switch.+ *+ * Consent is device-level, not session-level: it survives disconnects and+ * service restarts, and the ch5 music feed reads it as the source of truth+ * alongside the runtime MediaProjection grant. Defaults to false -- music+ * never leaves the phone until the user opts in (fail-closed).+ */+object MusicCapturePrefs {+ fun isMusicCaptureConsented(context: Context): Boolean =+ prefs(context).getBoolean(KEY_CONSENT, false)++ fun setMusicCaptureConsented(context: Context, consented: Boolean) {+ prefs(context).edit().putBoolean(KEY_CONSENT, consented).apply()+ }++ private fun prefs(context: Context) =+ context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)++ private const val FILE = "ma_auto_music_capture"+ private const val KEY_CONSENT = "music_capture_consented"+}
auto/src/main/java/com/vayunmathur/auto/platform/MusicCaptureSinkHolder.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MusicCaptureSinkHolder.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MusicCaptureSinkHolder.ktnew file mode 100644index 0000000000..e9c7a4cdc1--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MusicCaptureSinkHolder.kt@@ -0,0 +1,17 @@+package com.vayunmathur.auto.platform++/**+ * Process-wide holder for the ch5 media sink, bridging the projection session+ * (which owns the sink per connection) and the music-capture service (which+ * outlives any one session, like the media monitor).+ *+ * Mirrors the `systemSink = { audioSys }` lambda seam `CarTts` uses: the sink+ * resolves lazily at feed time, so capture before the ch5 grant (or after+ * teardown) drops chunks with a count instead of crashing. Written on the+ * projection worker thread, read on the capture thread -- a volatile var is+ * enough, matching the existing sink seams.+ */+object MusicCaptureSinkHolder {+ @Volatile+ var sink: AudioSinkChannel? = null+}
auto/src/main/java/com/vayunmathur/auto/service/MusicCaptureService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/MusicCaptureService.kt b/auto/src/main/java/com/vayunmathur/auto/service/MusicCaptureService.ktnew file mode 100644index 0000000000..d44a832489--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/service/MusicCaptureService.kt@@ -0,0 +1,106 @@+package com.vayunmathur.auto.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.AutoSessionState+import com.vayunmathur.auto.platform.MusicCapture+import com.vayunmathur.auto.platform.MusicCaptureSinkHolder+import com.vayunmathur.auto.ui.MusicCaptureGrant++/**+ * Holds the media-projection token while music capture runs.+ *+ * Split from [ProjectionService] on purpose: on API 34+ starting a foreground+ * service with type `mediaProjection` requires the projection to already be+ * registered, so widening the projection service's type crashes bring-up+ * before any grant exists. This service starts only after the user grants the+ * consent dialog (see [MusicCaptureGrant]), feeds the ch5 sink through+ * [MusicCaptureSinkHolder] (set per session by the projection service, like+ * the `systemSink` seam `CarTts` uses), and stops when asked or when the grant+ * is gone. Fail-closed: without a stored grant it logs and stops immediately.+ */+class MusicCaptureService : Service() {++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ val projection = MusicCaptureGrant.projection(this)+ if (projection == null) {+ Log.i(TAG, "no projection grant; not capturing")+ stopSelf()+ return START_NOT_STICKY+ }+ val notification = notification()+ if (Build.VERSION.SDK_INT >= 29) {+ startForeground(+ NOTIFICATION_ID,+ notification,+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,+ )+ } else {+ startForeground(NOTIFICATION_ID, notification)+ }+ capture = MusicCapture(+ this,+ mediaSink = { MusicCaptureSinkHolder.sink },+ isPlayingNow = { AutoSessionState.nowPlaying.value?.playing == true },+ onEvent = AutoSessionState::onAudioEvent,+ ).also {+ it.startThread()+ it.start(projection)+ }+ return START_STICKY+ }++ override fun onDestroy() {+ capture?.releaseThread()+ capture = null+ super.onDestroy()+ }++ private var capture: MusicCapture? = null++ private fun notification(): Notification {+ val manager = getSystemService(NotificationManager::class.java)+ manager.createNotificationChannel(+ NotificationChannel(+ CHANNEL_ID,+ getString(R.string.projection_channel),+ NotificationManager.IMPORTANCE_LOW,+ ),+ )+ return Notification.Builder(this, CHANNEL_ID)+ .setContentTitle(getString(R.string.music_capture_notification))+ .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)+ .setOngoing(true)+ .build()+ }++ companion object {+ private const val TAG = "MaAuto.MusicCaptureSvc"+ private const val CHANNEL_ID = "music-capture"+ private const val NOTIFICATION_ID = 2++ /**+ * Starts capture if a projection grant is stored; no-op otherwise.+ * Called when the session comes up and when the grant is first stored.+ */+ fun startIfGranted(context: Context) {+ if (MusicCaptureGrant.projection(context) == null) return+ context.startForegroundService(Intent(context, MusicCaptureService::class.java))+ }++ fun stop(context: Context) {+ context.stopService(Intent(context, MusicCaptureService::class.java))+ }+ }+}
auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.ktindex 04481181cb..923abefa82 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt@@ -18,11 +18,13 @@ import com.vayunmathur.auto.platform.AutoSessionState import com.vayunmathur.auto.platform.CarTts import com.vayunmathur.auto.platform.GuidanceChannel import com.vayunmathur.auto.platform.InputChannel+import com.vayunmathur.auto.platform.InputEvent import com.vayunmathur.auto.platform.MediaEvent import com.vayunmathur.auto.platform.MediaPlaybackMonitor import com.vayunmathur.auto.platform.MessagingEvent import com.vayunmathur.auto.platform.MicPermission import com.vayunmathur.auto.platform.MicSourceChannel+import com.vayunmathur.auto.platform.MusicCaptureSinkHolder import com.vayunmathur.auto.platform.NavStatusChannel import com.vayunmathur.auto.platform.NightSource import com.vayunmathur.auto.platform.SensorChannel@@ -178,7 +180,20 @@ class ProjectionService : Service() { } else if (message.channelId == GalService.NOTIFICATION.id) { messaging?.onMessage(message.channelId, message.type, message.payload) } else if (message.channelId == GalService.INPUT_SOURCE.id) {- input?.onMessage(message.channelId, message.type, message.payload)+ if (input == null) {+ // ch8 traffic with no owner: the channel was never+ // advertised with an input source, or openNext has not+ // run yet. Log, don't crash -- the owner binds on its+ // grant once advertised.+ Log.w(+ TAG,+ "ch8 input traffic with no input owner " ++ "(0x${message.type.toString(16)}); dropping",+ )+ AutoSessionState.onInputEvent(InputEvent.DroppedNoFocus)+ } else {+ input?.onMessage(message.channelId, message.type, message.payload)+ } } else if (message.channelId == GalService.SENSOR_SOURCE.id) { sensors?.onMessage(message.channelId, message.type, message.payload) } else if (message.channelId == GalService.AUDIO_SINK_GUIDANCE.id) {@@ -206,6 +221,12 @@ class ProjectionService : Service() { AutoSessionState.onFocusChanged(connection.session.focus) audioSys?.onFocusChanged() audioMedia?.onFocusChanged()+ // Flapping back to input-allowed re-binds ch8: a head unit that+ // parked input on NO_INPUT_FOCUS may need the echo to resume+ // sending reports. requestBinding is idempotent.+ if (connection.session.focus.inputAllowed) {+ input?.requestBinding()+ } } // Phone-side TTS starts with the session, not with any channel@@ -214,6 +235,12 @@ class ProjectionService : Service() { tts = CarTts(this, systemSink = { audioSys }, onEvent = AutoSessionState::onAudioEvent) .also { it.start() } + // Music capture starts with the session too, in its own+ // mediaProjection-typed service (the projection type cannot ride+ // on this service -- see MusicCaptureService). No stored grant+ // means fail-closed silence on ch5.+ MusicCaptureService.startIfGranted(this)+ try { pumpUntilGone(connection) } finally {@@ -235,10 +262,13 @@ class ProjectionService : Service() { audioSys = null audioMedia?.release() audioMedia = null+ MusicCaptureSinkHolder.sink = null mic?.release() mic = null tts?.stop() tts = null+ MusicCaptureService.stop(this)+ MusicCaptureSinkHolder.sink = null sensors?.release() sensors = null guidance?.release()@@ -547,6 +577,9 @@ class ProjectionService : Service() { focus = { connection.session.focus }, onEvent = AutoSessionState::onAudioEvent, )+ // The music-capture service resolves this lazily per feed; publish+ // it now so capture starts flowing once the sink starts.+ MusicCaptureSinkHolder.sink = audioMedia } // ch6 advertises in the same wire-order pass; the owner starts // acking on the grant (see MicSourceChannel.onChannelOpen).
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.ktindex acd34127b8..d3ad201070 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/AudioRow.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AudioRow.kt@@ -18,6 +18,7 @@ import com.vayunmathur.library.ui.Text fun AudioRow( sinkStatus: Map<AudioSinkRole, AudioSinkStatus>, bytesSent: Long,+ musicCaptured: Long, micTurns: Long, micAcks: Long, ttsSpoken: Long,@@ -36,6 +37,10 @@ fun AudioRow( 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_music_captured)) },+ supportingContent = { Text(stringResource(R.string.session_audio_music_captured_value, musicCaptured)) },+ ) ListItem( headlineContent = { Text(stringResource(R.string.session_audio_mic)) }, supportingContent = {
auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.ktindex 74d1349dd0..3123609713 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt@@ -63,6 +63,7 @@ fun AutoScreen(viewModel: AutoViewModel, onPairing: () -> Unit) { keysInjected = viewModel.keysInjected.collectAsStateWithLifecycle().value, scrollsInjected = viewModel.scrollsInjected.collectAsStateWithLifecycle().value, inputDropped = viewModel.inputDropped.collectAsStateWithLifecycle().value,+ musicBytesCaptured = viewModel.musicBytesCaptured.collectAsStateWithLifecycle().value, ) val scrollBehavior = appBarScrollBehavior() AppScaffold(@@ -87,6 +88,7 @@ fun AutoScreen(viewModel: AutoViewModel, onPairing: () -> Unit) { ) } SessionCard(session = session, modifier = Modifier.padding(top = 16.dp))+ MusicCaptureCard(modifier = Modifier.padding(top = 16.dp)) MessagingConsentCard(modifier = Modifier.padding(top = 16.dp)) MicPermissionCard(modifier = Modifier.padding(top = 16.dp)) Text(@@ -155,6 +157,8 @@ data class SessionSnapshot( val scrollsInjected: Long, /** ch8 reports dropped for lack of input focus this session. */ val inputDropped: Long,+ /** Music PCM bytes captured into the ch5 sink this session. */+ val musicBytesCaptured: Long, ) @Composable
auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureCard.kt b/auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureCard.ktnew file mode 100644index 0000000000..ba6a591d16--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureCard.kt@@ -0,0 +1,103 @@+package com.vayunmathur.auto.ui++import android.app.Activity+import android.media.projection.MediaProjectionManager+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 com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.MusicCapturePrefs+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.SettingsSwitchRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberMessenger++/**+ * Gates car music on two switches: the in-app consent and the system+ * media-projection grant. Both must be on before phone audio reaches the head+ * unit on ch5; either off means fail-closed silence (music stays on the phone+ * speaker, or pauses, exactly as without projection). Denials report on the+ * shared snackbar host -- never a Toast.+ */+@Composable+fun MusicCaptureCard(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ val messenger = rememberMessenger()+ var consented by remember { mutableStateOf(MusicCapturePrefs.isMusicCaptureConsented(context)) }+ var granted by remember { mutableStateOf(MusicCaptureGrant.hasGrant(context)) }+ val projectionLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.StartActivityForResult(),+ ) { result ->+ if (result.resultCode == Activity.RESULT_OK && result.data != null) {+ MusicCaptureGrant.storeResult(context, result.resultCode, result.data!!)+ granted = true+ com.vayunmathur.auto.service.MusicCaptureService.startIfGranted(context)+ } else {+ messenger.show(context.getString(R.string.music_capture_denied))+ granted = false+ }+ }+ Card(modifier.fillMaxWidth()) {+ Column(Modifier.padding(vertical = 8.dp)) {+ SettingsSection(title = stringResource(R.string.music_capture_headline)) {+ Text(+ text = stringResource(R.string.music_capture_body),+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+ )+ SettingsSwitchRow(+ title = stringResource(R.string.music_capture_consent),+ checked = consented,+ onCheckedChange = {+ consented = it+ MusicCapturePrefs.setMusicCaptureConsented(context, it)+ },+ supportingText = stringResource(+ if (consented) R.string.music_capture_consent_on+ else R.string.music_capture_consent_off,+ ),+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.music_capture_projection)) },+ supportingContent = {+ Text(+ stringResource(+ if (granted) R.string.music_capture_projection_granted+ else R.string.music_capture_projection_missing,+ ),+ )+ },+ trailingContent = {+ if (!granted) {+ Button(onClick = {+ val manager = context.getSystemService(MediaProjectionManager::class.java)+ runCatching {+ projectionLauncher.launch(manager.createScreenCaptureIntent())+ }.onFailure {+ messenger.show(context.getString(R.string.music_capture_denied))+ }+ }) {+ Text(stringResource(R.string.music_capture_allow))+ }+ }+ },+ )+ }+ }+ }+}
auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureGrant.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureGrant.kt b/auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureGrant.ktnew file mode 100644index 0000000000..fd3c860a7d--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/MusicCaptureGrant.kt@@ -0,0 +1,46 @@+package com.vayunmathur.auto.ui++import android.app.Activity+import android.content.Context+import android.content.Intent+import android.media.projection.MediaProjection+import android.media.projection.MediaProjectionManager++/**+ * Holds the media-projection grant for music capture.+ *+ * The consent `Intent` result belongs to an activity (the card above), but+ * the capture runs in the projection service; this holder bridges the two.+ * The stored result code + data recreate the [MediaProjection] token on+ * demand, process-wide. Fail-closed: no stored grant means no capture, and+ * revoking in settings takes effect on the next token recreation.+ */+object MusicCaptureGrant {+ @Volatile+ private var resultCode: Int = Activity.RESULT_CANCELED++ @Volatile+ private var resultData: Intent? = null++ /** Whether a grant is stored. The in-app consent switch is checked separately. */+ fun hasGrant(context: Context): Boolean = resultData != null++ /** Stores the consent-activity result. Called from the capture card. */+ fun storeResult(context: Context, code: Int, data: Intent) {+ resultCode = code+ resultData = data+ }++ /** Clears the stored grant (consent revoked in-app). */+ fun clear() {+ resultCode = Activity.RESULT_CANCELED+ resultData = null+ }++ /** Recreates the projection token, or null with no stored grant. */+ fun projection(context: Context): MediaProjection? {+ val data = resultData ?: return null+ val manager = context.getSystemService(MediaProjectionManager::class.java) ?: return null+ return runCatching { manager.getMediaProjection(resultCode, data) }.getOrNull()+ }+}
auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt b/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.ktindex 636f0c490a..97490a5b60 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt@@ -146,6 +146,7 @@ fun SessionCard(session: SessionSnapshot, modifier: Modifier = Modifier) { AudioRow( sinkStatus = session.sinkStatus, bytesSent = session.audioBytesSent,+ musicCaptured = session.musicBytesCaptured, micTurns = session.micTurns, micAcks = session.micAcks, ttsSpoken = session.ttsSpoken,
auto/src/main/res/values/strings.xml
diff --git a/auto/src/main/res/values/strings.xml b/auto/src/main/res/values/strings.xmlindex 21d8bd6d12..71263b1c43 100644--- a/auto/src/main/res/values/strings.xml+++ b/auto/src/main/res/values/strings.xml@@ -289,6 +289,38 @@ <string name="session_audio_bytes">Audio bytes</string> <!-- %1$d is PCM bytes framed out this session. --> <string name="session_audio_bytes_value"><xliff:g example="48000" id="bytes">%1$d</xliff:g></string>+ <!-- Heading of the session-card row counting music PCM captured into ch5. -->+ <string name="session_audio_music_captured">Music captured</string>+ <!-- %1$d is music PCM bytes captured into the ch5 sink this session. -->+ <string name="session_audio_music_captured_value"><xliff:g example="48000" id="bytes">%1$d</xliff:g></string>++ <!-- Heading of the card gating car music. Both switches must be on before+ phone audio reaches the head unit: the in-app consent below and the+ system media-projection grant. -->+ <string name="music_capture_headline">Music in the car</string>+ <!-- Explains what the card gates: phone media audio leaves for the car+ speakers only while consented and granted; otherwise it stays local. -->+ <string name="music_capture_body">Send phone music to the car speakers while projecting. The phone stays quiet for music while capture runs; without both switches below, music plays on the phone as before.</string>+ <!-- Row toggling the in-app music-capture switch. Capture stays off until+ this is on AND the system projection grant below is granted. -->+ <string name="music_capture_consent">Send music to the car</string>+ <!-- Supporting text under the consent switch while capture is on. -->+ <string name="music_capture_consent_on">Music plays on the car speakers while projecting</string>+ <!-- Supporting text under the consent switch while capture is off. -->+ <string name="music_capture_consent_off">Music stays on the phone until this is on</string>+ <!-- Row opening the system media-projection consent dialog. -->+ <string name="music_capture_projection">Screen-cast permission</string>+ <!-- Shown when the system media-projection grant is stored. -->+ <string name="music_capture_projection_granted">Allowed โ MA Auto can capture media audio</string>+ <!-- Shown when the system media-projection grant is not stored. -->+ <string name="music_capture_projection_missing">Not allowed โ grant permission to send music to the car</string>+ <!-- Button launching the system media-projection consent dialog. -->+ <string name="music_capture_allow">Allow</string>+ <!-- Snackbar when the media-projection consent dialog is denied or fails. -->+ <string name="music_capture_denied">Permission denied โ music stays on the phone</string>+ <!-- Ongoing notification while music capture runs (its own service holds+ the media-projection token; %1$s is the product name). -->+ <string name="music_capture_notification">Sending music to the car</string> <!-- Heading of the session-card row counting ch6 mic turns and acks. --> <string name="session_audio_mic">Car mic</string> <!-- %1$d is mic turns that yielded PCM, %2$d is chunks acked upstream. -->