Modern Apps git

← Modern-Apps.git

youpipe: keep audio after PiP close, audio-only to save bandwidth

Commit
0c4cfc7070dabed37cc0bde6fced6329caa2938f
Author
Vayun Mathur <[email protected]>
When
2026-07-23 17:31 UTC (4 months ago)
Parents
5f13911
- PiP: previously onPictureInPictureModeChanged + onDestroy stopped PlaybackService,
  killing audio when PiP window closed. New behavior per request:
  video should keep playing even if PiP is closed, but stop streaming video
  and switch to audio only.

Changes:
- MainActivity: do NOT stop service in onPictureInPictureModeChanged or
  onDestroy. Service stays alive for background audio.
- VideoPlayer: DisposableEffect now tracks wasInPipMode. If player was ever
  in PiP, onDispose releases controller without stop() and first disables
  video track via setTrackTypeDisabled(VIDEO, true). This propagates to
  SabrDashMediaPeriod.updateActiveTracks -> setActiveTracks(video=false)
  which stops SABR video pump, saving bandwidth.
- PlaybackService: onTaskRemoved (app swiped away / PiP dismissed) now keeps
  audio playing if isPlaying, just disables video track, instead of pause/stop.
  Only stops if not playing.

- Audio: always highest quality opus per language, remove bitrate chooser
  - VideoPlayer: currentAudioStream = audioStreamOptions.maxBy(bitrate), LaunchedEffect updates to best on language change, remove isAudioMenuExpanded and dropdown UI.
  - VideoPage download dialog: same, always highest opus, language switch picks best bitrate, remove audioExpanded UI.

Build: assembleDebug SUCCESS

Diff

youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.ktindex acee494289..b22ad46b28 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt@@ -110,20 +110,17 @@ class MainActivity : ComponentActivity() {         newConfig: Configuration     ) {         super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)--        // If we were in PiP, and we are no longer in it, and the activity is-        // finishing, it means the user closed the PiP window.-        if (!isInPictureInPictureMode && isFinishing) {-            val intent = Intent(this, PlaybackService::class.java)-            stopService(intent) // This forces the service to die immediately-        }+        // Previously we stopped PlaybackService when PiP closed (isFinishing). New behavior:+        // Keep audio playing and switch to audio-only when PiP is dismissed. PlaybackService+        // handles the audio-only switch via track selection override; we do NOT stop it here.     }      override fun onDestroy() {-        // If the activity is destroyed (closing PiP window), stop the service.-        // This is the most reliable "kill switch" for the audio.-        val intent = Intent(this, PlaybackService::class.java)-        stopService(intent)+        // Only stop service when truly destroying the whole activity, not when entering PiP.+        // When the user swipes away PiP window, system destroys activity with isFinishing=true,+        // but we want to KEEP audio (background playback). So we do NOT stop service here.+        // PlaybackService's own onTaskRemoved will handle final cleanup when notification is+        // dismissed or user explicitly stops.         super.onDestroy()     } }
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.ktindex a6b9375050..67637a25c0 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPage.kt@@ -264,7 +264,8 @@ fun VideoDetails(      if (isDownloadDialogVisible) {         var selectedVideoStream by remember { mutableStateOf(videoStreams.maxByOrNull { it.height } ?: videoStreams.first()) }-        var selectedAudioStream by remember { mutableStateOf(audioStreams.firstOrNull()) }+        // Always highest quality opus for selected language in download as well+        var selectedAudioStream by remember { mutableStateOf(audioStreams.maxByOrNull { it.bitrate }) }          val languageEntriesDownload = remember(audioStreams) {             audioStreams.map { it.language to (it.displayName ?: it.language) }@@ -273,11 +274,9 @@ fun VideoDetails(         }         val languages = languageEntriesDownload.map { it.first }         var selectedLanguage by remember { mutableStateOf(selectedAudioStream?.language ?: languages.firstOrNull() ?: "Default") }-        val filteredAudioStreams = remember(selectedLanguage, audioStreams) { audioStreams.filter { it.language == selectedLanguage } }          var videoExpanded by remember { mutableStateOf(false) }         var languageExpanded by remember { mutableStateOf(false) }-        var audioExpanded by remember { mutableStateOf(false) }          Dialog(onDismissRequest = { isDownloadDialogVisible = false }) {             Card {@@ -340,7 +339,7 @@ fun VideoDetails(                                         text = { Text(display) },                                         onClick = {                                             selectedLanguage = code-                                            selectedAudioStream = audioStreams.firstOrNull { it.language == code }+                                            selectedAudioStream = audioStreams.filter { it.language == code }.maxByOrNull { it.bitrate }                                             languageExpanded = false                                         }                                     )@@ -349,39 +348,6 @@ fun VideoDetails(                         }                     } -                    if (filteredAudioStreams.isNotEmpty()) {-                        Spacer(Modifier.height(16.dp))-                        Text("Audio Bitrate", style = MaterialTheme.typography.titleMedium)-                        Spacer(Modifier.height(8.dp))-                        ExposedDropdownMenuBox(-                            expanded = audioExpanded,-                            onExpandedChange = { audioExpanded = it }-                        ) {-                            OutlinedTextField(-                                value = selectedAudioStream?.let { "${it.bitrate / 1000} kbps - ${Formatter.formatShortFileSize(context, it.size)}" } ?: "None",-                                onValueChange = {},-                                readOnly = true,-                                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = audioExpanded) },-                                colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(),-                                modifier = Modifier.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable, true).fillMaxWidth()-                            )-                            ExposedDropdownMenu(-                                expanded = audioExpanded,-                                onDismissRequest = { audioExpanded = false }-                            ) {-                                filteredAudioStreams.forEach { stream ->-                                    DropdownMenuItem(-                                        text = { Text("${stream.bitrate / 1000} kbps - ${Formatter.formatShortFileSize(context, stream.size)}") },-                                        onClick = {-                                            selectedAudioStream = stream-                                            audioExpanded = false-                                        }-                                    )-                                }-                            }-                        }-                    }-                                         Spacer(Modifier.height(24.dp))                     Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {                         TextButton(onClick = { isDownloadDialogVisible = false }) { Text("Cancel") }
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.ktindex a21a7f8965..116172737c 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayer.kt@@ -131,18 +131,19 @@ fun VideoPlayer(             language = if ("en" in languages) "en" else languages.firstOrNull() ?: ""         }     }+    // Highest quality opus per language (sorted desc bitrate in VM), so first is best.     val audioStreamOptions = remember(audioStreams, language) {         audioStreams.filter { it.language == language }     }      var controller by remember { mutableStateOf<MediaController?>(null) }     var currentVideoStream by remember(videoStreams) { mutableStateOf(videoStreams.first()) }-    var currentAudioStream by remember(audioStreamOptions) { mutableStateOf(audioStreamOptions.firstOrNull()) }-    // Ensure currentAudioStream stays consistent with language filter+    // Always highest quality audio for selected language (user request: remove bitrate chooser)+    var currentAudioStream by remember(audioStreamOptions) { mutableStateOf(audioStreamOptions.maxByOrNull { it.bitrate }) }+    // Ensure currentAudioStream stays consistent with language filter = best quality     LaunchedEffect(language) {         val filtered = audioStreams.filter { it.language == language }-        currentAudioStream = filtered.find { it.bitrate == currentAudioStream?.bitrate }-            ?: filtered.firstOrNull()+        currentAudioStream = filtered.maxByOrNull { it.bitrate } ?: filtered.firstOrNull()     }     var isControlsVisible by remember { mutableStateOf(true) }     var currentPosition by remember { mutableLongStateOf(0L) }@@ -153,13 +154,20 @@ fun VideoPlayer(      var isVideoMenuExpanded by remember { mutableStateOf(false) }     var isLanguageMenuExpanded by remember { mutableStateOf(false) }-    var isAudioMenuExpanded by remember { mutableStateOf(false) }     var isChapterMenuVisible by remember { mutableStateOf(false) }     var isCaptionMenuExpanded by remember { mutableStateOf(false) }      var selectedSubtitle by remember { mutableStateOf<SubtitleTrack?>(null) }     var cues by remember { mutableStateOf<List<Cue>>(emptyList()) } +    // Track if we are in PiP to avoid stopping playback on dispose when PiP is active or+    // when PiP is closed and we want to keep audio-only.+    val isPipModeForLifecycle = rememberIsInPipMode()+    var wasInPipMode by remember { mutableStateOf(false) }+    LaunchedEffect(isPipModeForLifecycle) {+        if (isPipModeForLifecycle) wasInPipMode = true+    }+     DisposableEffect(Unit) {         val sessionToken = SessionToken(context, ComponentName(context, PlaybackService::class.java))         val controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()@@ -169,9 +177,26 @@ fun VideoPlayer(         }, MoreExecutors.directExecutor())          onDispose {-            controller?.let {-                it.stop() // This is critical!-                it.release()+            // If we were ever in PiP (including PiP closed -> background audio), don't stop the+            // ExoPlayer inside the service. Just release the controller connection. The service+            // will itself switch to audio-only when PiP is dismissed to save bandwidth.+            val activity = try { context.findActivity() } catch (_: Exception) { null }+            val keepPlaying = wasInPipMode || activity?.isInPictureInPictureMode == true+            if (keepPlaying) {+                controller?.let {+                    // Disable video track to stop streaming video (audio-only background)+                    try {+                        it.trackSelectionParameters = it.trackSelectionParameters.buildUpon()+                            .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, true)+                            .build()+                    } catch (_: Exception) {}+                    it.release()+                }+            } else {+                controller?.let {+                    it.stop()+                    it.release()+                }             }             MediaController.releaseFuture(controllerFuture)         }@@ -454,27 +479,6 @@ fun VideoPlayer(                             }                         } -                        // Audio is opus-only now, so no need to surface codec to user. Only bitrate matters.-                        Box {-                            Surface(-                                onClick = { isAudioMenuExpanded = true },-                                color = Color.Black.copy(alpha = 0.5f),-                                shape = RoundedCornerShape(4.dp)-                            ) {-                                Row(modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {-                                    Text(text = stringResource(R.string.audio_bitrate, (currentAudioStream?.bitrate ?: 0) / 1000), color = Color.White, style = MaterialTheme.typography.labelMedium)-                                    IconArrowDropDown(tint = Color.White)-                                }-                            }-                        DropdownMenu(expanded = isAudioMenuExpanded, onDismissRequest = { isAudioMenuExpanded = false }) {-                                audioStreamOptions.forEach { stream ->-                                    DropdownMenuItem(-                                        text = { Text(stringResource(R.string.audio_bitrate, stream.bitrate / 1000)) },-                                        onClick = { currentAudioStream = stream; isAudioMenuExpanded = false }-                                    )-                                }-                            }-                        }                     }                      if (subtitles.isNotEmpty()) {
youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.ktindex f1e43bbbe7..4e353a5876 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt@@ -249,16 +249,27 @@ class PlaybackService : MediaSessionService() {      override fun onTaskRemoved(rootIntent: Intent?) {         val player = mediaSession?.player-        // Stop the player and release everything+        // When app is swiped away while playing, keep audio-only background playback.+        // User request: video should keep playing even if PiP is closed (audio only).+        // So don't stop here; switch to audio-only to save bandwidth.+        if (player?.isPlaying == true) {+            try {+                player.trackSelectionParameters = player.trackSelectionParameters.buildUpon()+                    .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, true)+                    .build()+            } catch (_: Exception) {}+            // Don't stopSelf() - keep foreground notification for audio+            return+        }         player?.let {             it.pause()             it.stop()         }-        stopSelf() // This will trigger onDestroy() in the service+        stopSelf()     }      override fun onUpdateNotification(session: MediaSession, startInForegroundRequired: Boolean) {-        // If the player is stopped or the activity has disconnected,+        // If the player is stopped or the activity has disconnected and not playing,         // we stop the service from being a foreground service.         if (session.player.playbackState == Player.STATE_IDLE ||             session.player.playbackState == Player.STATE_ENDED) {