From d9e0a2f66a89ff10dc34555a6d865899b1263eef Mon Sep 17 00:00:00 2001 From: Altay Date: Sun, 15 Nov 2026 17:09:03 +0300 Subject: [PATCH 1/3] feat(mobile): phone and tablet show the player notices iOS shows --- .../android/playback/PlaybackModels.kt | 10 +- .../android/playback/PlaybackTrackRecovery.kt | 155 ++++++++++++++++++ .../playback/PlaybackConversionReducerTest.kt | 16 ++ .../playback/PlaybackTrackRecoveryTest.kt | 59 ++++--- .../android/auth/ChromeStoreListing.kt | 13 +- .../files/MobileFilesActionsController.kt | 31 +++- .../android/files/MobileFilesScreen.kt | 7 +- .../putdotio/android/playback/MobileCast.kt | 2 +- .../android/playback/MobileCastPlayback.kt | 19 ++- .../android/playback/MobilePlayerScreen.kt | 120 +++++++++++++- .../android/playback/MobilePlayerStates.kt | 15 +- .../android/playback/MobileVideoSheets.kt | 3 +- mobile/src/main/res/values/strings.xml | 6 + .../android/MobilePlayerScreenTest.kt | 92 ++++++++++- .../files/MobileFilesActionsControllerTest.kt | 20 ++- .../android/playback/MobileCastLabelTest.kt | 29 ++++ .../android/tv/player/TvPlayerScreen.kt | 19 ++- .../android/tv/player/TvTrackRecovery.kt | 139 +--------------- 18 files changed, 555 insertions(+), 200 deletions(-) create mode 100644 domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackTrackRecovery.kt rename tv/src/test/kotlin/io/putdotio/android/tv/player/TvTrackRecoveryTest.kt => domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackTrackRecoveryTest.kt (73%) create mode 100644 mobile/src/test/kotlin/io/putdotio/android/playback/MobileCastLabelTest.kt diff --git a/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackModels.kt b/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackModels.kt index f14ce6066..f084d1f27 100644 --- a/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackModels.kt +++ b/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackModels.kt @@ -95,8 +95,10 @@ public sealed interface PlaybackContent { val fileType: PutioFileType, ) : PlaybackContent + /** [conversionStart] marks a refused request to start converting, not a failure to play. */ public data class Failed( val failure: PlaybackFailure, + val conversionStart: Boolean = false, ) : PlaybackContent } @@ -463,12 +465,12 @@ private fun PlaybackState.resolveFailed(event: PlaybackEvent.ResolveFailed): Pla if (!isLoading(event.requestId)) { return PlaybackTransition(this, consumed = false) } - val conversion = (content as? PlaybackContent.Conversion) - ?.takeIf { it.readsStatus && event.failure.lostConnection } + val conversion = content as? PlaybackContent.Conversion + val statusRead = conversion?.takeIf { it.readsStatus && event.failure.lostConnection } return PlaybackTransition( copy( - content = conversion?.copy(refreshRequestId = null, statusCheckFailed = true) - ?: PlaybackContent.Failed(event.failure), + content = statusRead?.copy(refreshRequestId = null, statusCheckFailed = true) + ?: PlaybackContent.Failed(event.failure, conversionStart = conversion?.readsStatus == false), ), ) } diff --git a/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackTrackRecovery.kt b/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackTrackRecovery.kt new file mode 100644 index 000000000..ef8a83dc0 --- /dev/null +++ b/domain/playback/src/main/kotlin/io/putdotio/android/playback/PlaybackTrackRecovery.kt @@ -0,0 +1,155 @@ +package io.putdotio.android.playback + +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player +import androidx.media3.common.TrackSelectionParameters +import androidx.media3.common.util.UnstableApi +import androidx.media3.datasource.HttpDataSource +import androidx.media3.exoplayer.ExoPlaybackException +import androidx.media3.exoplayer.hls.HlsManifest + +public sealed interface PlaybackTrackRecoveryStep { + public data class DropSubtitles( + public val uris: Set, + public val notify: Boolean, + ) : PlaybackTrackRecoveryStep + + public data class RestoreAudio(public val switch: PlaybackAudioSwitch) : PlaybackTrackRecoveryStep +} + +public class PlaybackTrackFailure( + public val code: Int, + public val uri: String? = null, + public val audioRenderer: Boolean? = null, +) + +@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) +public fun PlaybackException.toTrackFailure(): PlaybackTrackFailure = + PlaybackTrackFailure( + code = errorCode, + uri = (cause as? HttpDataSource.HttpDataSourceException)?.dataSpec?.uri?.toString(), + audioRenderer = (this as? ExoPlaybackException) + ?.takeIf { it.type == ExoPlaybackException.TYPE_RENDERER } + ?.rendererFormat?.sampleMimeType?.let(MimeTypes::isAudio), + ) + +public class PlaybackAudioSwitch( + public val parameters: TrackSelectionParameters, + public val selection: AudioSelection, +) + +public class PlaybackTrackRecovery( + private val sidecarUris: () -> Set, + private val manifestSubtitleUris: () -> Set = { emptySet() }, +) { + public constructor( + sidecarUris: Set, + manifestSubtitleUris: () -> Set = { emptySet() }, + ) : this({ sidecarUris }, manifestSubtitleUris) + + private val failingSubtitles = mutableMapOf() + private var droppedAtMillis: Long? = null + private var droppedUris = emptySet() + private var audioSwitch: PlaybackAudioSwitch? = null + private var audioSwitchedAtMillis = 0L + + public fun loadFailed( + trackType: Int, + uri: String, + gaveUp: Boolean, + atMillis: Long, + ): PlaybackTrackRecoveryStep.DropSubtitles? { + if (!isSubtitle(trackType, uri)) return null + forgetBefore(atMillis) + failingSubtitles[uri] = atMillis + return if (gaveUp) drop(atMillis) else null + } + + public fun loadCompleted(uri: String) { + failingSubtitles -= uri + } + + public fun audioSwitching(from: PlaybackAudioSwitch, atMillis: Long) { + audioSwitch = from + audioSwitchedAtMillis = atMillis + } + + public fun audioPlaying() { + audioSwitch = null + } + + public fun recover(failure: PlaybackTrackFailure, atMillis: Long): PlaybackTrackRecoveryStep? { + val switch = audioSwitch?.takeIf { atMillis - audioSwitchedAtMillis <= TRACK_FAILURE_WINDOW_MILLIS } + forgetBefore(atMillis) + val justDropped = droppedAtMillis?.let { atMillis - it <= TRACK_FAILURE_WINDOW_MILLIS } == true + val dropped = droppedUris.takeIf { justDropped }.orEmpty() + droppedAtMillis = null + droppedUris = emptySet() + val subtitleLoad = failure.uri + ?.let { it in failingSubtitles || it in dropped || isSubtitle(C.TRACK_TYPE_UNKNOWN, it) } != false + return when { + switch != null && failure.code in AUDIO_FAILURES && failure.audioRenderer != false -> { + audioSwitch = null + PlaybackTrackRecoveryStep.RestoreAudio(switch) + } + failure.code in LOAD_FAILURES && subtitleLoad && (failingSubtitles.isNotEmpty() || justDropped) -> + drop(atMillis = null) + else -> null + } + } + + private fun drop(atMillis: Long?): PlaybackTrackRecoveryStep.DropSubtitles { + val step = PlaybackTrackRecoveryStep.DropSubtitles( + uris = failingSubtitles.keys intersect sidecarUris(), + notify = failingSubtitles.isNotEmpty(), + ) + droppedUris = failingSubtitles.keys.toSet() + failingSubtitles.clear() + droppedAtMillis = atMillis + return step + } + + private fun forgetBefore(atMillis: Long) { + failingSubtitles.values.removeAll { atMillis - it > TRACK_FAILURE_WINDOW_MILLIS } + } + + private fun isSubtitle(trackType: Int, uri: String): Boolean = + trackType == C.TRACK_TYPE_TEXT || uri in sidecarUris() || uri in manifestSubtitleUris() +} + +@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) +public fun TrackSelectionParameters.withAudioOf(before: TrackSelectionParameters): TrackSelectionParameters { + val builder = buildUpon() + .clearOverridesOfType(C.TRACK_TYPE_AUDIO) + .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, C.TRACK_TYPE_AUDIO in before.disabledTrackTypes) + before.overrides.values.filter { it.type == C.TRACK_TYPE_AUDIO }.forEach(builder::addOverride) + return builder.build() +} + +@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) +public fun Player.manifestSubtitleUris(): Set = + (currentManifest as? HlsManifest)?.multivariantPlaylist?.subtitles.orEmpty().map { it.url.toString() }.toSet() + +public fun MediaItem.sidecarSubtitleUris(): Set = + localConfiguration?.subtitleConfigurations.orEmpty().map { it.uri.toString() }.toSet() + +public fun Player.continueWithout(step: PlaybackTrackRecoveryStep.DropSubtitles) { + val positionMillis = currentPosition.coerceAtLeast(0L) + trackSelectionParameters = trackSelectionParameters.withSubtitleSelection(SubtitleSelection.Off, emptyList()) + val item = currentMediaItem + if (step.uris.isNotEmpty() && item != null) { + val kept = item.localConfiguration?.subtitleConfigurations.orEmpty() + .filterNot { it.uri.toString() in step.uris } + setMediaItem(item.buildUpon().setSubtitleConfigurations(kept).build(), positionMillis) + } + prepare() +} + +private const val TRACK_FAILURE_WINDOW_MILLIS = 10_000L +private val LOAD_FAILURES = + PlaybackException.ERROR_CODE_IO_UNSPECIFIED until PlaybackException.ERROR_CODE_DECODER_INIT_FAILED +private val AUDIO_FAILURES = + PlaybackException.ERROR_CODE_DECODER_INIT_FAILED until PlaybackException.ERROR_CODE_DRM_UNSPECIFIED diff --git a/domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackConversionReducerTest.kt b/domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackConversionReducerTest.kt index 9a681077e..05f6268db 100644 --- a/domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackConversionReducerTest.kt +++ b/domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackConversionReducerTest.kt @@ -249,6 +249,22 @@ class PlaybackConversionReducerTest { assertEquals(PlaybackContent.Failed(failure), failed.state.content) } + @Test + fun aRefusedConversionStartFailsAsAConversionStartAndAStatusReadDoesNot() { + val failure = PlaybackFailure.Putio(PutioFailure.ServerUnavailable(503, PutioConfigurationException("down"))) + val opening = conversion(PlaybackConversionState.NotAvailable) + val again = PlaybackReducer.reduce(conversion(PlaybackConversionState.Failed), PlaybackEvent.StartConversion) + assertEquals(PlaybackEffect.StartConversion(Target, PlaybackRequestId(2L)), again.effect) + listOf(opening, again.state).forEach { starting -> + val failed = PlaybackReducer.reduce(starting, PlaybackEvent.ResolveFailed(PlaybackRequestId(2L), failure)) + assertEquals(PlaybackContent.Failed(failure, conversionStart = true), failed.state.content) + } + + val read = PlaybackReducer.reduce(conversion(PlaybackConversionState.Queued), PlaybackEvent.RefreshConversion) + val readFailed = PlaybackReducer.reduce(read.state, PlaybackEvent.ResolveFailed(PlaybackRequestId(2L), failure)) + assertEquals(PlaybackContent.Failed(failure, conversionStart = false), readFailed.state.content) + } + private fun conversion(state: PlaybackConversionState): PlaybackState = PlaybackReducer.reduce( PlaybackReducer.start(Target).state, diff --git a/tv/src/test/kotlin/io/putdotio/android/tv/player/TvTrackRecoveryTest.kt b/domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackTrackRecoveryTest.kt similarity index 73% rename from tv/src/test/kotlin/io/putdotio/android/tv/player/TvTrackRecoveryTest.kt rename to domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackTrackRecoveryTest.kt index 19f4c3bfd..2193780b8 100644 --- a/tv/src/test/kotlin/io/putdotio/android/tv/player/TvTrackRecoveryTest.kt +++ b/domain/playback/src/test/kotlin/io/putdotio/android/playback/PlaybackTrackRecoveryTest.kt @@ -1,4 +1,4 @@ -package io.putdotio.android.tv.player +package io.putdotio.android.playback import androidx.media3.common.C import androidx.media3.common.Format @@ -8,7 +8,6 @@ import androidx.media3.common.TrackGroup import androidx.media3.common.TrackSelectionOverride import androidx.media3.common.TrackSelectionParameters import androidx.test.ext.junit.runners.AndroidJUnit4 -import io.putdotio.android.playback.AudioSelection import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -19,21 +18,21 @@ import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(sdk = [35]) -class TvTrackRecoveryTest { +class PlaybackTrackRecoveryTest { @Test fun aSubtitleTheLoaderGivesUpOnIsDroppedSoPlaybackContinues() { - val recovery = TvTrackRecovery(setOf(FOUND, FOLDER)) + val recovery = PlaybackTrackRecovery(setOf(FOUND, FOLDER)) assertNull(recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, VIDEO, gaveUp = true, atMillis = 0L)) assertNull(recovery.fail(PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED, atMillis = 0L)) assertEquals( - TvTrackRecoveryStep.DropSubtitles(setOf(FOUND), notify = true), + PlaybackTrackRecoveryStep.DropSubtitles(setOf(FOUND), notify = true), recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, FOUND, gaveUp = true, atMillis = 1_000L), ) assertEquals( "The player error the dropped subtitle raises shows no second notice", - TvTrackRecoveryStep.DropSubtitles(emptySet(), notify = false), + PlaybackTrackRecoveryStep.DropSubtitles(emptySet(), notify = false), recovery.fail(PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND, atMillis = 2_000L), ) assertNull( @@ -44,19 +43,19 @@ class TvTrackRecoveryTest { @Test fun aSubtitleErrorThrownWhileTheLoaderStillRetriesIsDroppedWithANotice() { - val recovery = TvTrackRecovery(setOf(FOUND)) + val recovery = PlaybackTrackRecovery(setOf(FOUND)) assertNull(recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, FOUND, gaveUp = false, atMillis = 0L)) assertNull(recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, FOUND, gaveUp = false, atMillis = 1_000L)) assertEquals( - TvTrackRecoveryStep.DropSubtitles(setOf(FOUND), notify = true), + PlaybackTrackRecoveryStep.DropSubtitles(setOf(FOUND), notify = true), recovery.fail(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, atMillis = 1_500L), ) } @Test fun aSubtitleThatLoadsOnRetryIsNotBlamedForALaterVideoError() { - val recovery = TvTrackRecovery(setOf(FOUND)) + val recovery = PlaybackTrackRecovery(setOf(FOUND)) recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, FOUND, gaveUp = false, atMillis = 0L) recovery.loadCompleted(FOUND) @@ -65,23 +64,23 @@ class TvTrackRecoveryTest { @Test fun aManifestSubtitleThatFailsTurnsSubtitlesOffWithoutDroppingSidecars() { - val recovery = TvTrackRecovery(setOf(FOUND)) + val recovery = PlaybackTrackRecovery(setOf(FOUND)) assertEquals( - TvTrackRecoveryStep.DropSubtitles(emptySet(), notify = true), + PlaybackTrackRecoveryStep.DropSubtitles(emptySet(), notify = true), recovery.loadFailed(C.TRACK_TYPE_TEXT, MANIFEST_SEGMENT, gaveUp = true, atMillis = 0L), ) } @Test fun theErrorADroppedManifestSegmentRaisesContinuesPlayback() { - val recovery = TvTrackRecovery(emptySet()) + val recovery = PlaybackTrackRecovery(emptySet()) recovery.loadFailed(C.TRACK_TYPE_TEXT, MANIFEST_SEGMENT, gaveUp = true, atMillis = 0L) assertEquals( - TvTrackRecoveryStep.DropSubtitles(emptySet(), notify = false), + PlaybackTrackRecoveryStep.DropSubtitles(emptySet(), notify = false), recovery.recover( - TvPlayerFailure(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, uri = MANIFEST_SEGMENT), + PlaybackTrackFailure(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, uri = MANIFEST_SEGMENT), atMillis = 500L, ), ) @@ -89,18 +88,18 @@ class TvTrackRecoveryTest { @Test fun aManifestSubtitlePlaylistThatFailsCountsAsASubtitleFailure() { - val recovery = TvTrackRecovery(emptySet()) { setOf(SUBTITLE_PLAYLIST) } + val recovery = PlaybackTrackRecovery(emptySet()) { setOf(SUBTITLE_PLAYLIST) } assertNull(recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, SUBTITLE_PLAYLIST, gaveUp = false, atMillis = 0L)) assertEquals( - TvTrackRecoveryStep.DropSubtitles(emptySet(), notify = true), + PlaybackTrackRecoveryStep.DropSubtitles(emptySet(), notify = true), recovery.fail(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, atMillis = 0L), ) } @Test fun aNetworkDropLongAfterASubtitleFailedIsNotBlamedOnTheSubtitle() { - val recovery = TvTrackRecovery(emptySet()) + val recovery = PlaybackTrackRecovery(emptySet()) recovery.loadFailed(C.TRACK_TYPE_TEXT, MANIFEST_SEGMENT, gaveUp = false, atMillis = 0L) assertNull(recovery.fail(PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED, atMillis = 60_000L)) @@ -110,12 +109,12 @@ class TvTrackRecoveryTest { @Test fun aDecoderFailureAfterAnAudioSwitchRestoresTheTrackThatPlayed() { - val recovery = TvTrackRecovery(emptySet()) - val before = TvAudioSwitch(TrackSelectionParameters.Builder().build(), AudioSelection.Automatic) + val recovery = PlaybackTrackRecovery(emptySet()) + val before = PlaybackAudioSwitch(TrackSelectionParameters.Builder().build(), AudioSelection.Automatic) recovery.audioSwitching(before, atMillis = 0L) val step = recovery.fail(PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, atMillis = 0L) - assertSame(before, (step as TvTrackRecoveryStep.RestoreAudio).switch) + assertSame(before, (step as PlaybackTrackRecoveryStep.RestoreAudio).switch) recovery.audioSwitching(before, atMillis = 0L) recovery.audioPlaying() @@ -124,19 +123,19 @@ class TvTrackRecoveryTest { @Test fun aVideoRequestThatFailsWhileASubtitleRetriesIsTheVideosOwn() { - val recovery = TvTrackRecovery(setOf(FOUND)) + val recovery = PlaybackTrackRecovery(setOf(FOUND)) recovery.loadFailed(C.TRACK_TYPE_UNKNOWN, FOUND, gaveUp = false, atMillis = 0L) assertNull( recovery.recover( - TvPlayerFailure(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, uri = VIDEO), + PlaybackTrackFailure(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, uri = VIDEO), atMillis = 1_000L, ), ) assertEquals( - TvTrackRecoveryStep.DropSubtitles(setOf(FOUND), notify = true), + PlaybackTrackRecoveryStep.DropSubtitles(setOf(FOUND), notify = true), recovery.recover( - TvPlayerFailure(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, uri = FOUND), + PlaybackTrackFailure(PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, uri = FOUND), atMillis = 1_500L, ), ) @@ -144,15 +143,15 @@ class TvTrackRecoveryTest { @Test fun aVideoDecoderFailureAfterAnAudioSwitchIsTheVideosOwn() { - val recovery = TvTrackRecovery(emptySet()) + val recovery = PlaybackTrackRecovery(emptySet()) recovery.audioSwitching( - TvAudioSwitch(TrackSelectionParameters.Builder().build(), AudioSelection.Automatic), + PlaybackAudioSwitch(TrackSelectionParameters.Builder().build(), AudioSelection.Automatic), atMillis = 0L, ) assertNull( recovery.recover( - TvPlayerFailure(PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, audioRenderer = false), + PlaybackTrackFailure(PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, audioRenderer = false), atMillis = 1_000L, ), ) @@ -160,10 +159,10 @@ class TvTrackRecoveryTest { @Test fun aDecoderFailureLongAfterAnAudioSwitchIsTheVideosOwn() { - val recovery = TvTrackRecovery(emptySet()) + val recovery = PlaybackTrackRecovery(emptySet()) recovery.audioSwitching( - TvAudioSwitch(TrackSelectionParameters.Builder().build(), AudioSelection.Automatic), + PlaybackAudioSwitch(TrackSelectionParameters.Builder().build(), AudioSelection.Automatic), atMillis = 0L, ) assertNull(recovery.fail(PlaybackException.ERROR_CODE_DECODING_FAILED, atMillis = 60_000L)) @@ -187,7 +186,7 @@ class TvTrackRecoveryTest { assertFalse(C.TRACK_TYPE_TEXT in restored.disabledTrackTypes) } - private fun TvTrackRecovery.fail(code: Int, atMillis: Long) = recover(TvPlayerFailure(code), atMillis) + private fun PlaybackTrackRecovery.fail(code: Int, atMillis: Long) = recover(PlaybackTrackFailure(code), atMillis) private companion object { const val VIDEO = "https://api.put.io/v2/files/42/hls/media.m3u8" diff --git a/mobile/src/main/kotlin/io/putdotio/android/auth/ChromeStoreListing.kt b/mobile/src/main/kotlin/io/putdotio/android/auth/ChromeStoreListing.kt index 024fb15b5..fa2444ca9 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/auth/ChromeStoreListing.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/auth/ChromeStoreListing.kt @@ -1,17 +1,22 @@ package io.putdotio.android.auth +import android.app.Activity import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import androidx.core.net.toUri -internal fun openChromeStoreListing(context: Context): Boolean = +internal fun openChromeStoreListing(context: Context): Boolean = openStoreListing(context, CHROME_PACKAGE) + +internal fun openStoreListing(context: Context, appPackage: String): Boolean = listOf( - "market://details?id=$CHROME_PACKAGE", - "https://play.google.com/store/apps/details?id=$CHROME_PACKAGE", + "market://details?id=$appPackage", + "https://play.google.com/store/apps/details?id=$appPackage", ).any { listing -> try { - context.startActivity(Intent(Intent.ACTION_VIEW, listing.toUri()).setPackage(PLAY_STORE_PACKAGE)) + val intent = Intent(Intent.ACTION_VIEW, listing.toUri()).setPackage(PLAY_STORE_PACKAGE) + if (context !is Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) true } catch (_: ActivityNotFoundException) { false diff --git a/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesActionsController.kt b/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesActionsController.kt index abe902bcf..db40f7187 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesActionsController.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesActionsController.kt @@ -1,5 +1,6 @@ package io.putdotio.android.files +import androidx.annotation.StringRes import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent @@ -14,6 +15,7 @@ import androidx.lifecycle.compose.LocalLifecycleOwner import io.putdotio.android.PutioFailure import io.putdotio.android.PutioResult import io.putdotio.android.R +import io.putdotio.android.auth.openStoreListing import io.putdotio.android.apiReason import io.putdotio.android.trash.TrashRepository import io.putdotio.android.trash.undoTrashMove @@ -35,14 +37,16 @@ import kotlinx.coroutines.launch /** * A line the Files snackbar shows: an item action that did not go through, or a copied link. With - * a [count], [message] is a plural that names how many items instead of [name]. + * a [count], [message] is a plural that names how many items instead of [name]. An [action] shows + * as [actionLabel]. */ internal class MobileFilesNotice( val message: Int, val name: String, val failure: PutioFailure? = null, val count: Int? = null, - val retry: (() -> Unit)? = null, + val action: (() -> Unit)? = null, + @param:StringRes val actionLabel: Int = R.string.mobile_action_retry, ) { fun text(context: Context): String { val reason = failure?.let { it.apiReason ?: context.getString(it.mobileMessageResource()) }.orEmpty() @@ -176,7 +180,14 @@ internal class MobileFilesActionsController( ensureActive() when (stream) { is FilesStreamUrlResult.Ready -> if (!handoff.open(stream.url, name)) { - mutableNotices.tryEmit(MobileFilesNotice(R.string.mobile_files_vlc_missing, name)) + mutableNotices.tryEmit( + MobileFilesNotice( + R.string.mobile_files_vlc_missing, + name, + action = handoff::install, + actionLabel = R.string.mobile_files_get_vlc, + ), + ) } FilesStreamUrlResult.DownloadTokenUnavailable -> mutableNotices.tryEmit(MobileFilesNotice(R.string.mobile_files_vlc_unavailable, name)) @@ -234,15 +245,17 @@ private fun watchedRefusal( retry: (() -> Unit)?, ) = when { count == 1 && watched -> - MobileFilesNotice(R.string.mobile_files_mark_watched_failed, item.name, failure, retry = retry) - count == 1 -> MobileFilesNotice(R.string.mobile_files_mark_unwatched_failed, item.name, failure, retry = retry) + MobileFilesNotice(R.string.mobile_files_mark_watched_failed, item.name, failure, action = retry) + count == 1 -> MobileFilesNotice(R.string.mobile_files_mark_unwatched_failed, item.name, failure, action = retry) watched -> MobileFilesNotice(R.plurals.mobile_files_mark_watched_failed_many, "", failure, count, retry) else -> MobileFilesNotice(R.plurals.mobile_files_mark_unwatched_failed_many, "", failure, count, retry) } -/** Opens a stream in VLC; false when VLC is not installed. */ -internal fun interface MobileVlcHandoff { +/** Opens a stream in VLC, false when VLC is not installed, or VLC's store page. */ +internal interface MobileVlcHandoff { fun open(streamUrl: String, name: String): Boolean + + fun install() } /** VLC by package, with the file's name as its title; the URL goes only into the intent, never a log. */ @@ -261,6 +274,10 @@ internal class MobileVlcIntentHandoff(private val context: Context) : MobileVlcH } catch (_: ActivityNotFoundException) { false } + + override fun install() { + openStoreListing(context, VLC_PACKAGE) + } } /** Open in VLC reads the original video, which put.io serves to any player. */ diff --git a/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesScreen.kt b/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesScreen.kt index 0df14e354..f7ccda04f 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesScreen.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesScreen.kt @@ -51,6 +51,7 @@ import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.input.InputMode import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.platform.LocalView @@ -701,16 +702,16 @@ internal fun MobileFilesNoticeHost(notices: Flow, modifier: M @Composable private fun MobileFilesNotices(notices: Flow, snackbarHostState: SnackbarHostState) { val context = LocalContext.current - val retryLabel = stringResource(R.string.mobile_action_retry) + val resources = LocalResources.current LaunchedEffect(notices) { notices.collect { notice -> snackbarHostState.currentSnackbarData?.dismiss() val result = snackbarHostState.showSnackbar( message = notice.text(context), - actionLabel = retryLabel.takeIf { notice.retry != null }, + actionLabel = notice.action?.let { resources.getString(notice.actionLabel) }, duration = SnackbarDuration.Long, ) - if (result == SnackbarResult.ActionPerformed) notice.retry?.invoke() + if (result == SnackbarResult.ActionPerformed) notice.action?.invoke() } } } diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCast.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCast.kt index 3247dcc06..78a819920 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCast.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCast.kt @@ -587,7 +587,7 @@ private const val RECEIVER_REPORT_WAIT_MILLIS = 10_000L private const val RECEIVER_LOAD_WAIT_MILLIS = 20_000L -private val PLAYED_STATES = setOf(CastRemoteState.Playing, CastRemoteState.Paused) +internal val PLAYED_STATES = setOf(CastRemoteState.Playing, CastRemoteState.Paused) /** Receiver states with the file still playable there. */ private val LIVE_STATES = setOf(CastRemoteState.Buffering, CastRemoteState.Playing, CastRemoteState.Paused) diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt index a81b6bd4d..d3c60ded8 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt @@ -1,5 +1,6 @@ package io.putdotio.android.playback +import androidx.annotation.StringRes import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable @@ -225,6 +226,7 @@ internal fun MobileCastPlayback( val fileId = target.fileId.value val source = (state.content as? PlaybackContent.Ready)?.source var failed by remember(fileId) { mutableStateOf(false) } + var played by remember(fileId) { mutableStateOf(false) } // Try again reruns the handover: a lookup that failed for a moment never needs a new session. var attempt by remember(fileId) { mutableIntStateOf(0) } val currentPolicy by rememberUpdatedState(subtitleStartupPolicy) @@ -239,6 +241,7 @@ internal fun MobileCastPlayback( return@LaunchedEffect } failed = false + played = false // One player at a time: session audio stops once the receiver takes over, for a video too. playerFactory.stopAudio(context) val load: suspend (PlaybackSource?) -> PlaybackRepositoryResult = { source -> @@ -264,10 +267,10 @@ internal fun MobileCastPlayback( val current = status?.takeIf { it.fileId == fileId } // A receiver that failed to load the file no longer holds it, so another handover sends it again. val castFailed = failed || current?.state == CastRemoteState.Failed - val label = stringResource( - if (castFailed) R.string.mobile_cast_failed else R.string.mobile_cast_playing_on, - deviceName, - ) + LaunchedEffect(current?.state) { + if (current?.state in PLAYED_STATES) played = true + } + val label = stringResource(castLabel(castFailed, current?.state, played), deviceName) val onRetry: (() -> Unit)? = if (castFailed) ({ attempt++ }) else null val seekEnabled = current?.seekable == true val intervals = if (target.mediaType == PlaybackMediaType.AUDIO) AudioSeekIntervals else VideoSeekIntervals @@ -469,3 +472,11 @@ private fun bareItem(fileId: Long, title: String, artist: String): MediaItem = .setMediaId(fileId.toString()) .setMediaMetadata(MediaMetadata.Builder().setTitle(title).setArtist(artist).build()) .build() + +@StringRes +internal fun castLabel(failed: Boolean, state: CastRemoteState?, played: Boolean): Int = + when { + failed -> R.string.mobile_cast_failed + !played && (state == null || state == CastRemoteState.Buffering) -> R.string.mobile_cast_loading_on + else -> R.string.mobile_cast_playing_on + } diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt index 02823e6c7..d20a618c1 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt @@ -62,6 +62,7 @@ import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalAccessibilityManager import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.clearAndSetSemantics @@ -96,7 +97,18 @@ import io.putdotio.android.files.hasVlc import io.putdotio.sdk.files.PlaybackSource import io.putdotio.sdk.files.PlaybackSourceKind import java.io.Closeable +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.receiveAsFlow +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.analytics.AnalyticsListener +import androidx.media3.exoplayer.source.LoadEventInfo +import androidx.media3.exoplayer.source.MediaLoadData +import io.putdotio.android.MobileSnackbarHost +import io.putdotio.sdk.files.PlaybackSubtitles +import java.io.IOException +import androidx.compose.material3.SnackbarHostState import io.putdotio.android.MobileIconButton internal const val MOBILE_PLAYER_TAG = "mobile-player" @@ -246,7 +258,7 @@ internal fun MobilePlayerScreen( is PlaybackContent.Failed -> MobilePlaybackFailureState( - title = stringResource(content.failure.errorTitle(state.target.mediaType)), + title = stringResource(content.errorTitle(state.target.mediaType)), failure = content.failure, onRetry = onRetry, video = isVideo, @@ -581,6 +593,7 @@ private fun MobileReadyPlayer( onSourceRequired = onSourceRequired, ) SubtitleStartupEffect(playerState, fileId, retainedSubtitleSelection, subtitleStartupPolicy) + SubtitlesUnavailableNotice(playerState, source.takeUnless { isAudio }) val touchExplorationEnabled = rememberTouchExplorationEnabled() ControlsVisibilityEffects( @@ -738,6 +751,44 @@ private class ReadyPlayerState( /** The video frame's full-screen bounds in the window, which picture-in-picture animates from. */ var videoFrame by mutableStateOf(null) + val recovery = PlaybackTrackRecovery( + sidecarUris = { player.currentMediaItem?.sidecarSubtitleUris().orEmpty() }, + manifestSubtitleUris = player::manifestSubtitleUris, + ) + + /** The player's own snackbar lines, as string resources; each waits for the screen to show it. */ + val notices = Channel(Channel.BUFFERED) + + fun audioSwitching(preferences: RetainedPlayerPreferences) { + recovery.audioSwitching( + PlaybackAudioSwitch(player.trackSelectionParameters, preferences.audioSelection), + SystemClock.elapsedRealtime(), + ) + } + + fun dropSubtitles(step: PlaybackTrackRecoveryStep.DropSubtitles, preferences: RetainedPlayerPreferences) { + preferences.subtitleSelection = SubtitleSelection.Off + cueHistory.clear() + player.continueWithout(step) + if (step.notify) notices.trySend(R.string.mobile_playback_subtitles_failed) + } + + fun recoverTrack(error: PlaybackException, preferences: RetainedPlayerPreferences): Boolean = + when (val step = recovery.recover(error.toTrackFailure(), SystemClock.elapsedRealtime())) { + is PlaybackTrackRecoveryStep.DropSubtitles -> { + dropSubtitles(step, preferences) + true + } + is PlaybackTrackRecoveryStep.RestoreAudio -> { + preferences.audioSelection = step.switch.selection + player.trackSelectionParameters = player.trackSelectionParameters.withAudioOf(step.switch.parameters) + player.prepare() + notices.trySend(R.string.mobile_playback_audio_failed) + true + } + null -> false + } + fun refreshKeepScreenOn(isAudio: Boolean) { keepScreenOn = !stalled && player.keepsVideoScreenOn(isAudio) } @@ -1093,6 +1144,7 @@ private fun PlayerListenerEffect( object : Media3Player.Listener { override fun onPlayerError(error: PlaybackException) { if (playerState.playerReleased) return + if (playerState.recoverTrack(error, currentPreferences.value)) return if (!playerState.ownsPlayer) currentPreferences.value.adoptPlaybackOptions(player) val errorPositionMillis = player.currentPosition.coerceAtLeast(0L) retainedPosition.longValue = errorPositionMillis @@ -1213,9 +1265,12 @@ private fun PlayerListenerEffect( } } player.addListener(listener) + val loads = playerState.trackLoadListener(currentPreferences) + (player as? ExoPlayer)?.addAnalyticsListener(loads) resolveRetainedSubtitleSelection(player.currentTracks.playbackSubtitleTracks()) onDispose { player.removeListener(listener) + (player as? ExoPlayer)?.removeAnalyticsListener(loads) if (playerState.playerReleased) return@onDispose retainedPosition.longValue = retainedPositionOnDispose( @@ -1236,6 +1291,55 @@ private fun PlayerListenerEffect( } } +@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) +private fun ReadyPlayerState.trackLoadListener(preferences: State): AnalyticsListener = + object : AnalyticsListener { + override fun onLoadError( + eventTime: AnalyticsListener.EventTime, + loadEventInfo: LoadEventInfo, + mediaLoadData: MediaLoadData, + error: IOException, + wasCanceled: Boolean, + ) { + recovery.loadFailed( + trackType = mediaLoadData.trackType, + uri = loadEventInfo.dataSpec.uri.toString(), + gaveUp = wasCanceled, + atMillis = SystemClock.elapsedRealtime(), + )?.let { dropSubtitles(it, preferences.value) } + } + + override fun onLoadCompleted( + eventTime: AnalyticsListener.EventTime, + loadEventInfo: LoadEventInfo, + mediaLoadData: MediaLoadData, + ) { + recovery.loadCompleted(loadEventInfo.dataSpec.uri.toString()) + } + + override fun onAudioPositionAdvancing(eventTime: AnalyticsListener.EventTime, playoutStartSystemTimeMs: Long) { + recovery.audioPlaying() + } + } + +@Composable +private fun SubtitlesUnavailableNotice(playerState: ReadyPlayerState, video: PlaybackSource?) { + val unavailable = video?.subtitles is PlaybackSubtitles.Unavailable + LaunchedEffect(playerState, video, unavailable) { + if (unavailable) playerState.notices.send(R.string.mobile_playback_subtitles_failed) + } +} + +@Composable +private fun MobilePlayerNotices(notices: Channel, modifier: Modifier) { + val resources = LocalResources.current + val hostState = remember { SnackbarHostState() } + LaunchedEffect(notices) { + notices.receiveAsFlow().collectLatest { hostState.showSnackbar(resources.getString(it)) } + } + MobileSnackbarHost(hostState, modifier) +} + @UnstableApi @Composable private fun MobileReadyPlayerContent( @@ -1306,6 +1410,10 @@ private fun MobileReadyPlayerContent( LaunchedEffect(keyFocus) { keyFocus.requestFocus() } val options = rememberPlayerOptionsSnapshot(player) + val onAudioSelectionChanged = { selection: AudioSelection -> + playerState.audioSwitching(preferences) + preferences.audioSelection = selection + } var footerHeight by remember { mutableStateOf(0.dp) } val appearance = rememberSubtitleAppearanceStore() // The window shows only the video, so a sheet open when it starts goes with the controls. @@ -1386,7 +1494,7 @@ private fun MobileReadyPlayerContent( onSeek = ::seek, onScrub = { pendingSeek.value = null }, onPlay = onPlay, - onAudioSelectionChanged = { preferences.audioSelection = it }, + onAudioSelectionChanged = onAudioSelectionChanged, castButton = castButton, modifier = Modifier.zIndex(2f).observeControlNavigation(onPointerNavigation, onKeyboardNavigation), ) @@ -1446,11 +1554,19 @@ private fun MobileReadyPlayerContent( appearance = appearance, preferences = preferences, onSubtitleSelectionChanged = onSubtitleSelectionChanged, + onAudioSelectionChanged = onAudioSelectionChanged, stream = stream, modifier = Modifier.zIndex(2.5f), panelModifier = optionModifier, ) } + MobilePlayerNotices( + playerState.notices, + Modifier + .align(Alignment.BottomCenter) + .zIndex(3.5f) + .padding(bottom = shownFooterHeight), + ) MobilePlaybackStallLayer( stall = stall, pictureInPicture = pictureInPicture, diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerStates.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerStates.kt index 79fb88b30..f2d9a5674 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerStates.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerStates.kt @@ -52,6 +52,7 @@ import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import androidx.media3.common.PlaybackException import io.putdotio.android.MobileEmptyState import io.putdotio.android.MobileErrorState import io.putdotio.android.PutioFailure @@ -90,11 +91,16 @@ internal fun MobilePlaybackFailureState( return } val needsAnotherPlayer = failure is PlaybackFailure.MediaUnsupported + val videoMessage = when { + needsAnotherPlayer -> stringResource(R.string.mobile_playback_cant_play_message) + failure.playerFault -> stringResource(R.string.mobile_playback_error_player) + else -> message + } MobilePlayerStateBox { PutioEmptyState( glyph = PutioEmptyGlyph.CantPlay, headline = if (needsAnotherPlayer) stringResource(R.string.mobile_playback_cant_play_title) else title, - message = if (needsAnotherPlayer) stringResource(R.string.mobile_playback_cant_play_message) else message, + message = videoMessage, action = when { failure.retryable -> { { MobilePlayerStateAction(stringResource(R.string.mobile_action_retry), onClick = onRetry) } @@ -423,6 +429,13 @@ internal fun PlaybackMediaType.loadingMessage(): Int = R.string.mobile_playback_loading } +private val PlaybackFailure.playerFault: Boolean + get() = putioFailure is PutioFailure.Unexpected && cause is PlaybackException + +@StringRes +internal fun PlaybackContent.Failed.errorTitle(mediaType: PlaybackMediaType): Int = + if (conversionStart) R.string.mobile_playback_conversion_start_failed else failure.errorTitle(mediaType) + @StringRes internal fun PlaybackFailure.errorTitle(mediaType: PlaybackMediaType): Int = when { diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileVideoSheets.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileVideoSheets.kt index 66cf6c605..1c5f639a7 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileVideoSheets.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileVideoSheets.kt @@ -112,6 +112,7 @@ internal fun MobileVideoSheets( appearance: SubtitleAppearanceStore, preferences: RetainedPlayerPreferences, onSubtitleSelectionChanged: (SubtitleSelection) -> Unit, + onAudioSelectionChanged: (AudioSelection) -> Unit, stream: PlaybackStreamSwitch?, modifier: Modifier, panelModifier: Modifier, @@ -137,7 +138,7 @@ internal fun MobileVideoSheets( MobileVideoSheet.Audio -> MobileAudioSheetContent( player = player, snapshot = options, - onAudioSelectionChanged = { preferences.audioSelection = it }, + onAudioSelectionChanged = onAudioSelectionChanged, onDone = close, ) MobileVideoSheet.Subtitles -> MobileSubtitlesSheetContent( diff --git a/mobile/src/main/res/values/strings.xml b/mobile/src/main/res/values/strings.xml index 16c724a1a..bc058058e 100644 --- a/mobile/src/main/res/values/strings.xml +++ b/mobile/src/main/res/values/strings.xml @@ -156,6 +156,10 @@ This device can’t play the original file, and it has no converted version. Couldn’t play this video Couldn’t play this audio + The video could not be played. Try again. + Could not convert video + Couldn’t load subtitles + Couldn’t switch audio track Connection lost You don’t have access to this file. Playback access expired. Retry to refresh it. @@ -730,6 +734,7 @@ Looking for devices… Stop casting Playing on %1$s + Loading on %1$s Can’t play this on %1$s. This video can’t play in its original format, so put.io started a conversion. It keeps going if you leave. This text is too long. Paste fewer links. @@ -879,6 +884,7 @@ Couldn’t mark “%1$s” as unwatched. %2$s File not found Install VLC to open “%1$s”. + Get VLC Couldn’t prepare “%1$s” for VLC. Sign in again. Couldn’t prepare “%1$s” for VLC. %2$s diff --git a/mobile/src/test/kotlin/io/putdotio/android/MobilePlayerScreenTest.kt b/mobile/src/test/kotlin/io/putdotio/android/MobilePlayerScreenTest.kt index 379338625..f348d85e2 100644 --- a/mobile/src/test/kotlin/io/putdotio/android/MobilePlayerScreenTest.kt +++ b/mobile/src/test/kotlin/io/putdotio/android/MobilePlayerScreenTest.kt @@ -115,6 +115,7 @@ import io.putdotio.sdk.files.PlaybackSource import io.putdotio.sdk.files.PlaybackSourceKind import io.putdotio.sdk.files.PlaybackSubtitle import io.putdotio.sdk.files.PlaybackSubtitles +import io.putdotio.sdk.files.PlaybackSubtitleFailure import io.putdotio.sdk.files.PutioCredentialUrl import io.putdotio.sdk.files.PutioFileType import org.junit.Assert.assertEquals @@ -491,6 +492,74 @@ class MobilePlayerScreenTest { compose.onNodeWithText("Check again").assertDoesNotExist() } + @Test + fun aFailedAudioSwitchGoesBackToTheTrackThatPlayedWithANotice() { + val player = RecordingPlayer() + val audio = TrackGroup( + Format.Builder().setId("en").setLanguage("en").setSampleMimeType(MimeTypes.AUDIO_AAC).build(), + Format.Builder().setId("de").setLanguage("de").setSampleMimeType(MimeTypes.AUDIO_AAC).build(), + ) + var failures = 0 + compose.setBuiltContent { + PutioTheme { + MobilePlayerScreen( + state = state(PlaybackContent.Ready(videoSource())), + onRetry = {}, + onPlayerFailure = { _, _ -> failures += 1 }, + onBack = {}, + playerFactory = MobilePlayerFactory { _, _ -> player }, + ) + } + } + compose.runOnIdle { + player.updateTracks( + Tracks( + listOf( + Tracks.Group( + audio, + false, + intArrayOf(C.FORMAT_HANDLED, C.FORMAT_HANDLED), + booleanArrayOf(true, false), + ), + ), + ), + ) + } + compose.onNodeWithContentDescription("Audio: English").performClick() + compose.onNode(hasText("Deutsch") and isSelectable()).performClick() + compose.runOnIdle { assertEquals(listOf(1), player.trackSelectionParameters.overrides[audio]?.trackIndices) } + + compose.runOnIdle { + player.fail(PlaybackException("audio", null, PlaybackException.ERROR_CODE_DECODER_INIT_FAILED)) + } + + compose.onNodeWithText("Couldn’t switch audio track").assertIsDisplayed() + compose.runOnIdle { + assertEquals(0, failures) + assertNull(player.trackSelectionParameters.overrides[audio]) + } + } + + @Test + fun aVideoWhoseSubtitlesPutioCannotListSaysSo() { + val unavailable = videoSource().copy( + subtitles = PlaybackSubtitles.Unavailable(PlaybackSubtitleFailure.InvalidResponse), + ) + compose.setBuiltContent { + PutioTheme { + MobilePlayerScreen( + state = state(PlaybackContent.Ready(unavailable)), + onRetry = {}, + onPlayerFailure = { _, _ -> }, + onBack = {}, + playerFactory = MobilePlayerFactory { _, _ -> RecordingPlayer() }, + ) + } + } + + compose.onNodeWithText("Couldn’t load subtitles").assertIsDisplayed() + } + @Test fun failureStatesShowTheirCopyAndOfferTryAgainOnlyWhenRetryable() { val rows = failureRows() @@ -540,6 +609,25 @@ private fun failureRows(): List = "Connection lost", retry = true, ), + FailureRow( + PlaybackContent.Failed( + PlaybackFailure.Putio(PutioFailure.ServerUnavailable(503, PutioConfigurationException("down"))), + conversionStart = true, + ), + "Could not convert video", + retry = true, + ), + FailureRow( + PlaybackContent.Failed( + PlaybackFailure.Putio( + PutioFailure.Unexpected( + PlaybackException("renderer", null, PlaybackException.ERROR_CODE_DECODING_FAILED), + ), + ), + ), + "The video could not be played. Try again.", + retry = true, + ), FailureRow( PlaybackContent.Failed(PlaybackFailure.MediaUnsupported(IllegalStateException("codec"))), "Can’t play this here", @@ -640,7 +728,7 @@ class MobilePlayerLifecycleTest { } compose.runOnIdle { players.single().failDecodingAt(54_321L) } - compose.onNodeWithText("put.io is temporarily unavailable. Try again.").assertIsDisplayed() + compose.onNodeWithText("The video could not be played. Try again.").assertIsDisplayed() compose.runOnIdle { assertTrue(players.single().released) } compose.runOnIdle { @@ -659,7 +747,7 @@ class MobilePlayerLifecycleTest { } val readyContent = content compose.runOnIdle { players.last().failDecodingAt(0L) } - compose.onNodeWithText("put.io is temporarily unavailable. Try again.").assertIsDisplayed() + compose.onNodeWithText("The video could not be played. Try again.").assertIsDisplayed() compose.runOnIdle { content = readyContent } compose.runOnIdle { assertEquals(3, players.size) diff --git a/mobile/src/test/kotlin/io/putdotio/android/files/MobileFilesActionsControllerTest.kt b/mobile/src/test/kotlin/io/putdotio/android/files/MobileFilesActionsControllerTest.kt index 29b5a4bf4..c64c40127 100644 --- a/mobile/src/test/kotlin/io/putdotio/android/files/MobileFilesActionsControllerTest.kt +++ b/mobile/src/test/kotlin/io/putdotio/android/files/MobileFilesActionsControllerTest.kt @@ -21,6 +21,7 @@ import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith @@ -43,6 +44,7 @@ class MobileFilesActionsControllerTest { private val trash = RecordingTrash() private val opened = mutableListOf>() private var vlcInstalled = true + private var installs = 0 private var rejected = 0 private var stream: FilesStreamUrlResult = FilesStreamUrlResult.Ready(STREAM) private var streamGate: CompletableDeferred? = null @@ -130,7 +132,7 @@ class MobileFilesActionsControllerTest { assertEquals(videos.map { it.id }, watched.positions.map { it.first }) watched.failing = emptySet() - checkNotNull(notices.single().retry).invoke() + checkNotNull(notices.single().action).invoke() advanceUntilIdle() assertEquals(videos.map { it.id } + videos[2].id, watched.positions.map { it.first }) assertEquals( @@ -148,7 +150,7 @@ class MobileFilesActionsControllerTest { watched.failing = setOf(video.id) controller.setWatched(video, watched = true) advanceUntilIdle() - assertEquals(null, notices.single().retry) + assertEquals(null, notices.single().action) } @Test @@ -210,6 +212,11 @@ class MobileFilesActionsControllerTest { listOf(R.string.mobile_files_vlc_missing, R.string.mobile_files_vlc_unavailable), notices.map { it.message }, ) + val missing = notices.first() + assertEquals(R.string.mobile_files_get_vlc, missing.actionLabel) + checkNotNull(missing.action).invoke() + assertEquals(1, installs) + assertNull(notices.last().action) } @Test @@ -340,7 +347,14 @@ class MobileFilesActionsControllerTest { onFilesEvent = { events += it; true }, onPositionSaved = row::positionSaved, onAuthenticationRequired = { rejected++ }, - handoff = { url, name -> vlcInstalled.also { if (it) opened += url to name } }, + handoff = object : MobileVlcHandoff { + override fun open(streamUrl: String, name: String) = + vlcInstalled.also { if (it) opened += streamUrl to name } + + override fun install() { + installs++ + } + }, ) private fun entry() = ContinueWatchingEntry(video.id, video.name, 600.0, 3_000.0, watchedAt = 1L) diff --git a/mobile/src/test/kotlin/io/putdotio/android/playback/MobileCastLabelTest.kt b/mobile/src/test/kotlin/io/putdotio/android/playback/MobileCastLabelTest.kt new file mode 100644 index 000000000..97e74d8af --- /dev/null +++ b/mobile/src/test/kotlin/io/putdotio/android/playback/MobileCastLabelTest.kt @@ -0,0 +1,29 @@ +package io.putdotio.android.playback + +import io.putdotio.android.R +import org.junit.Assert.assertEquals +import org.junit.Test + +class MobileCastLabelTest { + @Test + fun theReceiverLoadsUntilItFirstPlaysThenPlaysOrFails() { + assertEquals(R.string.mobile_cast_loading_on, castLabel(failed = false, state = null, played = false)) + assertEquals( + R.string.mobile_cast_loading_on, + castLabel(failed = false, state = CastRemoteState.Buffering, played = false), + ) + assertEquals( + R.string.mobile_cast_playing_on, + castLabel(failed = false, state = CastRemoteState.Playing, played = false), + ) + assertEquals( + "A receiver buffering after it played still plays the file", + R.string.mobile_cast_playing_on, + castLabel(failed = false, state = CastRemoteState.Buffering, played = true), + ) + assertEquals( + R.string.mobile_cast_failed, + castLabel(failed = true, state = CastRemoteState.Buffering, played = false), + ) + } +} diff --git a/tv/src/main/kotlin/io/putdotio/android/tv/player/TvPlayerScreen.kt b/tv/src/main/kotlin/io/putdotio/android/tv/player/TvPlayerScreen.kt index a9005a307..010abb73f 100644 --- a/tv/src/main/kotlin/io/putdotio/android/tv/player/TvPlayerScreen.kt +++ b/tv/src/main/kotlin/io/putdotio/android/tv/player/TvPlayerScreen.kt @@ -97,6 +97,13 @@ import io.putdotio.android.playback.withReportingLease import io.putdotio.android.playback.captionLanguages import io.putdotio.android.playback.inFileSubtitleLanguage import io.putdotio.android.playback.withSubtitleSelection +import io.putdotio.android.playback.PlaybackAudioSwitch +import io.putdotio.android.playback.PlaybackTrackRecovery +import io.putdotio.android.playback.PlaybackTrackRecoveryStep +import io.putdotio.android.playback.manifestSubtitleUris +import io.putdotio.android.playback.sidecarSubtitleUris +import io.putdotio.android.playback.toTrackFailure +import io.putdotio.android.playback.withAudioOf import io.putdotio.sdk.files.PlaybackSource import io.putdotio.sdk.files.PlaybackSourceKind import io.putdotio.sdk.files.PlaybackSubtitle @@ -318,7 +325,7 @@ private fun TvReadyPlayer( source.preparePlayback(target.name, target.mediaType, stoppedAtMillis ?: resumePositionMillis) } val recovery = remember(player) { - TvTrackRecovery(prepared.mediaItem.sidecarSubtitleUris(), player::manifestSubtitleUris) + PlaybackTrackRecovery(prepared.mediaItem.sidecarSubtitleUris(), player::manifestSubtitleUris) } val subtitlesFailed by rememberUpdatedState(stringResource(R.string.tv_player_subtitles_failed)) val audioFailed by rememberUpdatedState(stringResource(R.string.tv_player_audio_failed)) @@ -365,7 +372,7 @@ private fun TvReadyPlayer( var firstFrameShown by remember(player) { mutableStateOf(false) } val currentSubtitlePolicy by rememberUpdatedState(subtitleStartupPolicy) DisposableEffect(player) { - val dropSubtitles = { step: TvTrackRecoveryStep.DropSubtitles -> + val dropSubtitles = { step: PlaybackTrackRecoveryStep.DropSubtitles -> options = options.copy(subtitles = SubtitleSelection.Off) cueHistory.clear() player.continueWithout(step, snackbar, subtitlesFailed) @@ -398,12 +405,12 @@ private fun TvReadyPlayer( override fun onPlayerError(error: PlaybackException) { val position = player.currentPosition.coerceAtLeast(0L) - when (val step = recovery.recover(error.toTvPlayerFailure(), SystemClock.elapsedRealtime())) { - is TvTrackRecoveryStep.DropSubtitles -> { + when (val step = recovery.recover(error.toTrackFailure(), SystemClock.elapsedRealtime())) { + is PlaybackTrackRecoveryStep.DropSubtitles -> { dropSubtitles(step) return } - is TvTrackRecoveryStep.RestoreAudio -> { + is PlaybackTrackRecoveryStep.RestoreAudio -> { options = options.copy(audio = step.switch.selection) player.trackSelectionParameters = player.trackSelectionParameters.withAudioOf(step.switch.parameters) @@ -663,7 +670,7 @@ private fun TvReadyPlayer( actions = TvPlayerSheetActions( onAudio = { track -> recovery.audioSwitching( - TvAudioSwitch(player.trackSelectionParameters, options.audio), + PlaybackAudioSwitch(player.trackSelectionParameters, options.audio), SystemClock.elapsedRealtime(), ) options = options.copy(audio = AudioSelection.Track(track.identity)) diff --git a/tv/src/main/kotlin/io/putdotio/android/tv/player/TvTrackRecovery.kt b/tv/src/main/kotlin/io/putdotio/android/tv/player/TvTrackRecovery.kt index 1001f98f9..9cf24827b 100644 --- a/tv/src/main/kotlin/io/putdotio/android/tv/player/TvTrackRecovery.kt +++ b/tv/src/main/kotlin/io/putdotio/android/tv/player/TvTrackRecovery.kt @@ -3,142 +3,23 @@ package io.putdotio.android.tv.player import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.res.stringResource -import androidx.media3.common.C -import androidx.media3.common.MediaItem -import androidx.media3.common.MimeTypes -import androidx.media3.common.PlaybackException import androidx.media3.common.Player -import androidx.media3.common.TrackSelectionParameters -import androidx.media3.common.util.UnstableApi -import androidx.media3.datasource.HttpDataSource -import androidx.media3.exoplayer.ExoPlaybackException -import androidx.media3.exoplayer.hls.HlsManifest import io.putdotio.android.R -import io.putdotio.android.playback.AudioSelection import io.putdotio.android.playback.PlaybackMediaType import io.putdotio.android.playback.PlaybackTarget -import io.putdotio.android.playback.SubtitleSelection -import io.putdotio.android.playback.withSubtitleSelection +import io.putdotio.android.playback.PlaybackTrackRecoveryStep +import io.putdotio.android.playback.continueWithout import io.putdotio.android.tv.TvSnackbarMessage import io.putdotio.android.tv.TvSnackbarState import io.putdotio.sdk.files.PlaybackSource import io.putdotio.sdk.files.PlaybackSubtitles -internal sealed interface TvTrackRecoveryStep { - data class DropSubtitles(val uris: Set, val notify: Boolean) : TvTrackRecoveryStep - - data class RestoreAudio(val switch: TvAudioSwitch) : TvTrackRecoveryStep -} - -internal class TvPlayerFailure(val code: Int, val uri: String? = null, val audioRenderer: Boolean? = null) - -@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) -internal fun PlaybackException.toTvPlayerFailure(): TvPlayerFailure = - TvPlayerFailure( - code = errorCode, - uri = (cause as? HttpDataSource.HttpDataSourceException)?.dataSpec?.uri?.toString(), - audioRenderer = (this as? ExoPlaybackException) - ?.takeIf { it.type == ExoPlaybackException.TYPE_RENDERER } - ?.rendererFormat?.sampleMimeType?.let(MimeTypes::isAudio), - ) - -internal class TvAudioSwitch(val parameters: TrackSelectionParameters, val selection: AudioSelection) - -internal class TvTrackRecovery( - private val sidecarUris: Set, - private val manifestSubtitleUris: () -> Set = { emptySet() }, +internal fun Player.continueWithout( + step: PlaybackTrackRecoveryStep.DropSubtitles, + notice: TvSnackbarState, + message: String, ) { - private val failingSubtitles = mutableMapOf() - private var droppedAtMillis: Long? = null - private var droppedUris = emptySet() - private var audioSwitch: TvAudioSwitch? = null - private var audioSwitchedAtMillis = 0L - - fun loadFailed(trackType: Int, uri: String, gaveUp: Boolean, atMillis: Long): TvTrackRecoveryStep.DropSubtitles? { - if (!isSubtitle(trackType, uri)) return null - forgetBefore(atMillis) - failingSubtitles[uri] = atMillis - return if (gaveUp) drop(atMillis) else null - } - - fun loadCompleted(uri: String) { - failingSubtitles -= uri - } - - fun audioSwitching(from: TvAudioSwitch, atMillis: Long) { - audioSwitch = from - audioSwitchedAtMillis = atMillis - } - - fun audioPlaying() { - audioSwitch = null - } - - fun recover(failure: TvPlayerFailure, atMillis: Long): TvTrackRecoveryStep? { - val switch = audioSwitch?.takeIf { atMillis - audioSwitchedAtMillis <= TRACK_FAILURE_WINDOW_MILLIS } - forgetBefore(atMillis) - val justDropped = droppedAtMillis?.let { atMillis - it <= TRACK_FAILURE_WINDOW_MILLIS } == true - val dropped = droppedUris.takeIf { justDropped }.orEmpty() - droppedAtMillis = null - droppedUris = emptySet() - val subtitleLoad = failure.uri - ?.let { it in failingSubtitles || it in dropped || isSubtitle(C.TRACK_TYPE_UNKNOWN, it) } != false - return when { - switch != null && failure.code in AUDIO_FAILURES && failure.audioRenderer != false -> { - audioSwitch = null - TvTrackRecoveryStep.RestoreAudio(switch) - } - failure.code in LOAD_FAILURES && subtitleLoad && (failingSubtitles.isNotEmpty() || justDropped) -> - drop(atMillis = null) - else -> null - } - } - - private fun drop(atMillis: Long?): TvTrackRecoveryStep.DropSubtitles { - val step = TvTrackRecoveryStep.DropSubtitles( - uris = failingSubtitles.keys intersect sidecarUris, - notify = failingSubtitles.isNotEmpty(), - ) - droppedUris = failingSubtitles.keys.toSet() - failingSubtitles.clear() - droppedAtMillis = atMillis - return step - } - - private fun forgetBefore(atMillis: Long) { - failingSubtitles.values.removeAll { atMillis - it > TRACK_FAILURE_WINDOW_MILLIS } - } - - private fun isSubtitle(trackType: Int, uri: String): Boolean = - trackType == C.TRACK_TYPE_TEXT || uri in sidecarUris || uri in manifestSubtitleUris() -} - -@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) -internal fun TrackSelectionParameters.withAudioOf(before: TrackSelectionParameters): TrackSelectionParameters { - val builder = buildUpon() - .clearOverridesOfType(C.TRACK_TYPE_AUDIO) - .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, C.TRACK_TYPE_AUDIO in before.disabledTrackTypes) - before.overrides.values.filter { it.type == C.TRACK_TYPE_AUDIO }.forEach(builder::addOverride) - return builder.build() -} - -@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) -internal fun Player.manifestSubtitleUris(): Set = - (currentManifest as? HlsManifest)?.multivariantPlaylist?.subtitles.orEmpty().map { it.url.toString() }.toSet() - -internal fun MediaItem.sidecarSubtitleUris(): Set = - localConfiguration?.subtitleConfigurations.orEmpty().map { it.uri.toString() }.toSet() - -internal fun Player.continueWithout(step: TvTrackRecoveryStep.DropSubtitles, notice: TvSnackbarState, message: String) { - val positionMillis = currentPosition.coerceAtLeast(0L) - trackSelectionParameters = trackSelectionParameters.withSubtitleSelection(SubtitleSelection.Off, emptyList()) - val item = currentMediaItem - if (step.uris.isNotEmpty() && item != null) { - val kept = item.localConfiguration?.subtitleConfigurations.orEmpty() - .filterNot { it.uri.toString() in step.uris } - setMediaItem(item.buildUpon().setSubtitleConfigurations(kept).build(), positionMillis) - } - prepare() + continueWithout(step) if (step.notify) notice.show(TvSnackbarMessage(message)) } @@ -150,9 +31,3 @@ internal fun TvSubtitlesUnavailableNotice(source: PlaybackSource, target: Playba if (unavailable) snackbar.show(TvSnackbarMessage(message)) } } - -private const val TRACK_FAILURE_WINDOW_MILLIS = 10_000L -private val LOAD_FAILURES = - PlaybackException.ERROR_CODE_IO_UNSPECIFIED until PlaybackException.ERROR_CODE_DECODER_INIT_FAILED -private val AUDIO_FAILURES = - PlaybackException.ERROR_CODE_DECODER_INIT_FAILED until PlaybackException.ERROR_CODE_DRM_UNSPECIFIED From 57b849eefba6c1fee69dd81ff4c99d0fba8914c4 Mon Sep 17 00:00:00 2001 From: Altay Date: Sun, 15 Nov 2026 17:40:27 +0300 Subject: [PATCH 2/3] fix(mobile): player notices stay out of picture-in-picture, and a Cast reconnect keeps the played label --- .../io/putdotio/android/playback/MobileCastPlayback.kt | 5 +++-- .../io/putdotio/android/playback/MobilePlayerScreen.kt | 9 +++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt index d3c60ded8..4767ccef9 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobileCastPlayback.kt @@ -237,11 +237,12 @@ internal fun MobileCastPlayback( LaunchedEffect(fileId, source, connected, attempt) { if (!connected) return@LaunchedEffect val startMillis = state.castStartMillis(preferences) - if (!cast.holds(fileId) && currentOnOriginalRejected(PlaybackFallbackReason.CastReceiver, startMillis)) { + val held = cast.holds(fileId) + if (!held && currentOnOriginalRejected(PlaybackFallbackReason.CastReceiver, startMillis)) { return@LaunchedEffect } failed = false - played = false + if (!held) played = false // One player at a time: session audio stops once the receiver takes over, for a video too. playerFactory.stopAudio(context) val load: suspend (PlaybackSource?) -> PlaybackRepositoryResult = { source -> diff --git a/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt b/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt index d20a618c1..710336f66 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/playback/MobilePlayerScreen.kt @@ -1331,13 +1331,13 @@ private fun SubtitlesUnavailableNotice(playerState: ReadyPlayerState, video: Pla } @Composable -private fun MobilePlayerNotices(notices: Channel, modifier: Modifier) { +private fun MobilePlayerNotices(notices: Channel, shown: Boolean, modifier: Modifier) { val resources = LocalResources.current val hostState = remember { SnackbarHostState() } - LaunchedEffect(notices) { - notices.receiveAsFlow().collectLatest { hostState.showSnackbar(resources.getString(it)) } + LaunchedEffect(notices, shown) { + if (shown) notices.receiveAsFlow().collectLatest { hostState.showSnackbar(resources.getString(it)) } } - MobileSnackbarHost(hostState, modifier) + if (shown) MobileSnackbarHost(hostState, modifier) } @UnstableApi @@ -1562,6 +1562,7 @@ private fun MobileReadyPlayerContent( } MobilePlayerNotices( playerState.notices, + shown = !pictureInPicture, Modifier .align(Alignment.BottomCenter) .zIndex(3.5f) From 54fcc67b53132bac7cb0b7bfd31130212199be68 Mon Sep 17 00:00:00 2001 From: Altay Date: Sun, 15 Nov 2026 17:59:56 +0300 Subject: [PATCH 3/3] test(mobile): pin the Cast reconnect played label and the notices held back in picture-in-picture --- .../android/MobileCastPlaybackTest.kt | 18 +++++++++++++ .../android/MobilePictureInPictureTest.kt | 26 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/mobile/src/test/kotlin/io/putdotio/android/MobileCastPlaybackTest.kt b/mobile/src/test/kotlin/io/putdotio/android/MobileCastPlaybackTest.kt index 1e516f84d..c6c394c0a 100644 --- a/mobile/src/test/kotlin/io/putdotio/android/MobileCastPlaybackTest.kt +++ b/mobile/src/test/kotlin/io/putdotio/android/MobileCastPlaybackTest.kt @@ -9,6 +9,7 @@ import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithTag import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import io.putdotio.android.design.PutioTheme import io.putdotio.android.files.FilesItemId @@ -185,6 +186,23 @@ class MobileCastPlaybackTest { compose.runOnIdle { assertEquals(listOf(1L, 1L), gateway.loads) } } + @Test + fun aSessionThatReconnectsWhileTheReceiverPlaysKeepsSayingItPlays() { + setCastScreen(playback) { source, _ -> + PlaybackRepositoryResult.Success(requireNotNull(requireNotNull(source).toCastMedia(Episode1, TOKEN))) + } + compose.runOnIdle { assertEquals(listOf(1L), gateway.loads) } + gateway.report(1L, CastRemoteState.Playing) + + compose.runOnIdle { gateway.availability.value = CastAvailability.Connecting("Living room TV") } + compose.runOnIdle { gateway.availability.value = CastAvailability.Connected("Living room TV") } + gateway.report(1L, CastRemoteState.Buffering) + + compose.onNodeWithText("Playing on Living room TV").assertExists() + compose.onNodeWithText("Loading on Living room TV").assertDoesNotExist() + compose.runOnIdle { assertEquals(listOf(1L), gateway.loads) } + } + @Test fun anHlsVideoAsksTheReceiverForThePlaylistSubtitleTheAccountSelects() { val hls = PlaybackController(Episode1, HlsEpisode, scope) diff --git a/mobile/src/test/kotlin/io/putdotio/android/MobilePictureInPictureTest.kt b/mobile/src/test/kotlin/io/putdotio/android/MobilePictureInPictureTest.kt index 68a9ff57f..154fc426f 100644 --- a/mobile/src/test/kotlin/io/putdotio/android/MobilePictureInPictureTest.kt +++ b/mobile/src/test/kotlin/io/putdotio/android/MobilePictureInPictureTest.kt @@ -17,6 +17,7 @@ import androidx.compose.ui.geometry.Rect import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.media3.common.Player as Media3Player import androidx.media3.common.VideoSize @@ -37,6 +38,7 @@ import io.putdotio.android.playback.pictureInPictureAspectRatio import io.putdotio.android.playback.playbackState import io.putdotio.sdk.files.PlaybackSource import io.putdotio.sdk.files.PlaybackSourceKind +import io.putdotio.sdk.files.PlaybackSubtitleFailure import io.putdotio.sdk.files.PlaybackSubtitles import io.putdotio.sdk.files.PutioCredentialUrl import org.junit.Assert.assertEquals @@ -233,6 +235,30 @@ class MobilePictureInPictureTest { host.close() } + @Test + fun aNoticeRaisedInTheWindowWaitsUntilItExpands() { + val host = launchHost() + val activity = host.get() + val player = RecordingPlayer() + val listed = source(VideoTarget, PlaybackSourceKind.MP4) + var state by mutableStateOf(videoState()) + activity.setContent { PutioTheme { PlayerScreen(state, MobilePlayerFactory { _, _ -> player }) } } + compose.onNodeWithContentDescription("Back").assertIsDisplayed() + + compose.runOnIdle { activity.pictureInPicture(true) } + compose.runOnIdle { + val unlisted = listed.copy( + subtitles = PlaybackSubtitles.Unavailable(PlaybackSubtitleFailure.InvalidResponse), + ) + state = videoState(content = PlaybackContent.Ready(unlisted)) + } + compose.onNodeWithText("Couldn’t load subtitles").assertDoesNotExist() + + compose.runOnIdle { activity.pictureInPicture(false) } + compose.onNodeWithText("Couldn’t load subtitles").assertIsDisplayed() + host.close() + } + @Test fun autoplayNextKeepsPlayingInTheWindow() { val host = launchHost()