Modern Apps git

← Modern-Apps.git

youpipe: share one media volume level with the TV

Commit
e862073f624ed7d69b2b99bc60b29b96cfa0df09
Author
vayun-mathur <[email protected]>
When
2026-08-23 07:20 UTC (3 months ago)
Parents
fa701b2

Diff

cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.ktindex e0ece9dac5..d076a66c13 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/AudioPlayer.kt@@ -130,6 +130,24 @@ class AudioPlayer {         }     } +    /**+     * Set the output gain, 0..1.+     *+     * **A gain on the track rather than a change to the TV's own volume.** The level is the phone's,+     * shared between the two ends so that turning the sound down here leaves the phone quiet when+     * playback comes back to it. Moving the television's device volume instead would put the shared+     * level and the box's own setting in a fight, and the user would have two controls doing the same+     * job badly.+     *+     * Called from the media loop, like everything else that touches [track] - see `pump`'s note on why+     * nothing outside that coroutine may.+     */+    fun setVolume(level: Float) {+        val activeTrack = track ?: return+        runCatching { activeTrack.setVolume(level.coerceIn(0f, 1f)) }+            .onFailure { Log.w(TAG, "could not set the output volume", it) }+    }+     /**      * Queue one Opus packet and write out whatever the decoder finished.      *
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.ktindex 6304cf1752..d3851ea298 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt@@ -211,8 +211,17 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {             KeyEvent.KEYCODE_MEDIA_PREVIOUS ->                 ReceiverController.send(PlaybackCommand(PlaybackAction.Previous)) -            // Volume is left to the system for now: the level is shared with the phone, and wiring-            // only this end would have the two disagree the moment either was touched.+            // The shared level, not this box's own volume: the phone owns it, so the press goes there+            // and the gain follows on the next snapshot. Declining when there is no session lets the+            // key fall through to the box's ordinary volume control.+            KeyEvent.KEYCODE_DPAD_UP,+            KeyEvent.KEYCODE_VOLUME_UP,+            -> if (!ReceiverController.nudgeVolume(up = true)) return super.dispatchKeyEvent(event)++            KeyEvent.KEYCODE_DPAD_DOWN,+            KeyEvent.KEYCODE_VOLUME_DOWN,+            -> if (!ReceiverController.nudgeVolume(up = false)) return super.dispatchKeyEvent(event)+             else -> return super.dispatchKeyEvent(event)         }         return true
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex e07c65c2ee..20c61cc9dc 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -86,6 +86,9 @@ private const val CODEC_CONFIG_TIMEOUT_MS = 5_000L  */ private const val RECEIVE_BUFFER_BYTES = 2 * 1024 * 1024 +/** One press of the remote's volume key. Sixteen steps end to end, which is what a TV usually offers. */+private const val VOLUME_STEP = 1f / 16f+ /**  * The single owner of the live receiving session.  *@@ -142,6 +145,16 @@ object ReceiverController {     @Volatile     private var videoCodecConfig: ByteArray? = null +    /**+     * The output gain the phone last asked for, 0..1.+     *+     * A field rather than a call into [AudioPlayer], because that object belongs to the media loop+     * outright - see `pump`. The loop picks this up on its next pass, which is at most one socket+     * timeout away and imperceptible for a volume change.+     */+    @Volatile+    private var castVolume: Float = 1f+     private val pairingGate = PairingGate()      /**@@ -172,6 +185,23 @@ object ReceiverController {         send(PlaybackCommand(if (forward) PlaybackAction.SkipForward else PlaybackAction.SkipBack))     } +    /**+     * Nudge the shared volume level up or down by one step.+     *+     * Sent to the phone rather than applied here, even though the sound comes out of this end. The+     * phone owns the level - it stores it, it reports it, and it keeps it for local playback once the+     * cast is over - so the round trip is what makes the two ends agree. The gain follows about half a+     * second later when the next snapshot arrives, which is faster than a hand leaves a button.+     *+     * Returns false with no session, so the key falls through to the box's own volume control.+     */+    fun nudgeVolume(up: Boolean): Boolean {+        val current = _state.value.playback?.state?.volume ?: return false+        val level = (current + if (up) VOLUME_STEP else -VOLUME_STEP).coerceIn(0f, 1f)+        send(PlaybackCommand(PlaybackAction.SetVolume, value = level.toDouble()))+        return true+    }+     fun start(context: Context) {         if (acceptJob != null) return         val appContext = context.applicationContext@@ -382,6 +412,7 @@ object ReceiverController {      * else about a session is diagnosed from.      */     private fun onPlaybackState(message: PlaybackState) {+        castVolume = message.volume         _state.update {             it.copy(                 playback = PlaybackSnapshot(@@ -613,6 +644,8 @@ object ReceiverController {         var lastFeedback = 0L         var lastStatsLog = 0L         var lastResync = 0L+        // The gain currently on the track, so it is written only when the phone actually changes it.+        var appliedVolume = Float.NaN         // When the wait for a codec configuration began, or 0 while nothing is waiting. Started from         // the moment the decoder *could* otherwise have been built, so it does not run down while the         // Activity is still producing a surface.@@ -710,6 +743,10 @@ object ReceiverController {                     active.render()                 }                 if (player != null) {+                    if (castVolume != appliedVolume) {+                        appliedVolume = castVolume+                        player.setVolume(appliedVolume)+                    }                     while (true) {                         val frame = audioPlayout.due(now) ?: break                         player.play(frame.payload, audioRtpToMicros(frame.rtpTimestamp))
youpipe/src/main/AndroidManifest.xml
diff --git a/youpipe/src/main/AndroidManifest.xml b/youpipe/src/main/AndroidManifest.xmlindex 5f68d82d37..0cface2eee 100644--- a/youpipe/src/main/AndroidManifest.xml+++ b/youpipe/src/main/AndroidManifest.xml@@ -10,6 +10,9 @@     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />      <uses-permission android:name="com.vayunmathur.cast.permission.STREAM_CONTENT" />+    <!-- The TV remote's volume keys move this phone's media volume, which is the level both ends+         share, so it is still there when playback comes back to the phone. -->+    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />      <queries>         <package android:name="com.vayunmathur.cast" />
youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.ktindex edc1183502..281c2ee4ac 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt@@ -1,10 +1,13 @@ package com.vayunmathur.youpipe.platform  import android.content.Context+import android.media.AudioManager import android.os.ParcelFileDescriptor import android.util.Log import android.view.Surface import androidx.annotation.OptIn+import androidx.compose.runtime.getValue+import androidx.core.content.getSystemService import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.audio.TeeAudioProcessor@@ -139,6 +142,14 @@ object CastPlayback {      */     private var player: Player? = null +    /**+     * The phone's own media volume, which is the level both ends share.+     *+     * Held from [open]'s context rather than asked for per call: the reporting loop reads it twice a+     * second, and a `getSystemService` per tick would be work for nothing.+     */+    private var audio: AudioManager? = null+     /** Called by the player screen once its `MediaController` has connected, and with null as it goes. */     fun attachPlayer(newPlayer: Player?) {         player = newPlayer@@ -197,6 +208,14 @@ object CastPlayback {         close()         _state.value = State.Connecting         val newClient = CastClient(context)+        // **The shared volume level is the phone's own media volume, and that is the whole trick.** A+        // level invented for casting would have to be persisted, reconciled with the device volume, and+        // explained to a user who found their phone quiet afterwards. `STREAM_MUSIC` is already the+        // thing the user reaches for, already survives the session, and already applies to local+        // playback when the cast ends - so it is reported to the TV as a gain and moved by the TV's+        // remote through `SET_VOLUME`.+        audio = context.applicationContext.getSystemService<AudioManager>()+        audio?.let { manager -> update { it.copy(volume = manager.mediaLevel()) } }         return try {             val session = newClient.openSession(width, height, wantAudio = true)             client = newClient@@ -240,6 +259,7 @@ object CastPlayback {         CastAudioTap.detach()         client?.close()         client = null+        audio = null         _transport.update { it.copy(hasNext = false, hasPrevious = false) }         _state.value = State.Idle     }@@ -268,6 +288,11 @@ object CastPlayback {             }             while (isActive) {                 delay(HEARTBEAT_MS)+                // Re-read rather than trusting the last write. The level is the device's, so the+                // hardware keys and every other app can move it - which is exactly why intercepting+                // the volume keys here is unnecessary: the system already applies them to the shared+                // level, and this is what carries the result to the television.+                audio?.let { manager -> update { it.copy(volume = manager.mediaLevel()) } }                 activeClient.reportPlaybackState(_transport.value.asPlaybackState())             }         }@@ -310,8 +335,10 @@ object CastPlayback {                 // `playbackParameters` here would drop whatever pitch the user had chosen.                 update { it.copy(speed = speed.toFloat().coerceIn(MIN_SPEED, MAX_SPEED)) }             }-            // Volume is somebody else's to answer; ignored rather than guessed at.-            PlaybackAction.SetVolume -> Unit+            // The television asked for a level. Applied to the device's media volume, so it is still+            // there when playback comes back to the phone - which is the point of sharing one level+            // rather than inventing a cast-only one.+            PlaybackAction.SetVolume -> command.value?.let { setVolume(it.toFloat()) }             // Only offered when the phone said there was something to go to, but checked again here:             // the TV's copy of that is up to half a second old.             PlaybackAction.Next ->@@ -337,6 +364,44 @@ object CastPlayback {         update { it.copy(positionMs = clamped) }     } +    /**+     * Move the shared level, from a television that asked.+     *+     * Written to the device volume *and* to [transport], rather than only to the device: the next+     * snapshot is up to half a second away, and a seek bar's worth of latency on a volume press is the+     * difference between a remote that feels connected and one that does not.+     */+    private fun setVolume(level: Float) {+        val clamped = level.coerceIn(0f, 1f)+        audio?.setMediaLevel(clamped)+        update { it.copy(volume = clamped) }+    }++    /**+     * `STREAM_MUSIC` as a 0..1 fraction.+     *+     * A fraction rather than an index because the two devices do not have the same number of steps - a+     * phone commonly has 15 or 25, a television 16 or 100 - and sending an index would mean the TV's+     * idea of "half" depended on the phone's hardware.+     */+    private fun AudioManager.mediaLevel(): Float {+        val max = getStreamMaxVolume(AudioManager.STREAM_MUSIC)+        if (max <= 0) return 1f+        return getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() / max+    }++    private fun AudioManager.setMediaLevel(level: Float) {+        val max = getStreamMaxVolume(AudioManager.STREAM_MUSIC)+        if (max <= 0) return+        runCatching {+            setStreamVolume(AudioManager.STREAM_MUSIC, Math.round(level * max), 0)+        }.onFailure {+            // A device with a volume policy that refuses the write - a work profile, a restriction.+            // Nothing to report: the level the TV asked for simply does not take.+            Log.w(TAG, "could not set the media volume", it)+        }+    }+     /** Matches the phone's own skip buttons, so the two remotes move by the same amount. */     private const val SKIP_MS = 10_000L