feat: release v0.1.2 with playback quality selection
This commit is contained in:
1 parent
93f1221e6a
commit
e8cd96eb5e
16 files changed
+598
-43
No files matched your search
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "dev.bulubulu.tv"
|
||||
minSdk = 23
|
||||
targetSdk = 34
|
||||
versionCode = 2
|
||||
versionName = "0.1.1"
|
||||
versionCode = 3
|
||||
versionName = "0.1.2"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
buildFeatures { compose = true; buildConfig = true }
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
|
||||
|
||||
package dev.bulubulu.tv.player
|
||||
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.test.assertIsFocused
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.performKeyInput
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import dev.bulubulu.tv.core.PlaybackQuality
|
||||
import dev.bulubulu.tv.core.PlaybackStream
|
||||
import dev.bulubulu.tv.ui.BulubuluTheme
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class QualityNavigationTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private fun quality(id: Int) = PlaybackQuality(id, "清晰度 $id", PlaybackStream("https://cdn.example/$id.m4s"))
|
||||
|
||||
@Test fun currentQualityGetsFocusAndRemoteSelectsNextOption() {
|
||||
var selected: Int? = null
|
||||
compose.setContent {
|
||||
BulubuluTheme {
|
||||
QualityDialog(listOf(quality(80), quality(64), quality(32)), 80, false, { selected = it.id }, {})
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(300)
|
||||
compose.onNodeWithTag("quality_80").assertIsFocused().performKeyInput {
|
||||
keyDown(Key.DirectionDown); keyUp(Key.DirectionDown)
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.runOnIdle { assertEquals(64, selected) }
|
||||
}
|
||||
|
||||
@Test fun lowerCurrentQualityIsScrolledIntoViewAndBackDismisses() {
|
||||
var dismissed = false
|
||||
compose.setContent {
|
||||
BulubuluTheme {
|
||||
QualityDialog(listOf(120, 116, 112, 80, 74, 64, 32, 16).map(::quality), 16, false, {}, { dismissed = true })
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(400)
|
||||
compose.onNodeWithTag("quality_16").assertIsFocused()
|
||||
InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
|
||||
compose.runOnIdle { assertEquals(true, dismissed) }
|
||||
}
|
||||
|
||||
@Test fun inFlightChangePreventsDuplicateSelectionAndKeepsCloseFocusable() {
|
||||
compose.setContent {
|
||||
BulubuluTheme { QualityDialog(listOf(quality(80), quality(32)), 80, true, {}, {}) }
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithTag("quality_80").assertIsNotEnabled()
|
||||
compose.onNodeWithTag("quality_32").assertIsNotEnabled()
|
||||
compose.onNodeWithTag("quality_close").assertIsFocused()
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ data class VideoEpisode(
|
||||
)
|
||||
data class VideoDetails(val title: String, val description: String, val episodes: List<VideoEpisode>)
|
||||
data class PlaybackStream(val url: String, val backupUrls: List<String> = emptyList())
|
||||
data class PlaybackQuality(val id: Int, val label: String, val video: PlaybackStream)
|
||||
data class PlaybackSource(
|
||||
val title: String,
|
||||
val video: PlaybackStream,
|
||||
@@ -34,6 +35,8 @@ data class PlaybackSource(
|
||||
val qualityLabel: String = "",
|
||||
val durationMs: Long = 0,
|
||||
val referer: String = "https://www.bilibili.com/",
|
||||
val qualityId: Int = 0,
|
||||
val qualities: List<PlaybackQuality> = emptyList(),
|
||||
)
|
||||
data class QrLoginCode(val url: String, val key: String)
|
||||
sealed interface QrLoginStatus {
|
||||
|
||||
@@ -4,6 +4,7 @@ import dev.bulubulu.tv.core.BiliApiException
|
||||
import dev.bulubulu.tv.core.ContentTab
|
||||
import dev.bulubulu.tv.core.FeedPage
|
||||
import dev.bulubulu.tv.core.PlaybackSource
|
||||
import dev.bulubulu.tv.core.PlaybackQuality
|
||||
import dev.bulubulu.tv.core.PlaybackStream
|
||||
import dev.bulubulu.tv.core.VideoDetails
|
||||
import dev.bulubulu.tv.core.VideoEpisode
|
||||
@@ -102,7 +103,9 @@ class ContentRepository(private val http: BiliHttpClient) {
|
||||
}
|
||||
|
||||
suspend fun resolvePlayback(episode: VideoEpisode): PlaybackSource {
|
||||
val common = mapOf("qn" to "80", "fnval" to "16", "fnver" to "0", "fourk" to "0")
|
||||
// Ask for the available DASH ladder, but still start at no more than
|
||||
// ordinary 1080P. The server enforces account rights for every URL.
|
||||
val common = mapOf("qn" to "120", "fnval" to "16", "fnver" to "0", "fourk" to "1")
|
||||
val response = if (episode.epId != null) {
|
||||
http.getJson(
|
||||
"$API/pgc/player/web/playurl",
|
||||
@@ -259,19 +262,18 @@ internal object ContentJson {
|
||||
}
|
||||
val dash = data.optJSONObject("dash")
|
||||
if (dash != null) {
|
||||
val video = dash.optJSONArray("video").objects()
|
||||
val candidates = dash.optJSONArray("video").objects()
|
||||
.filter { stream ->
|
||||
val codec = stream.optString("codecs").lowercase()
|
||||
(codec.startsWith("avc1") || stream.optInt("codecid") == 7) &&
|
||||
streamUrl(stream).isNotBlank()
|
||||
(codec.startsWith("avc1") || (codec.isBlank() && stream.optInt("codecid") == 7)) &&
|
||||
stream.optInt("id") > 0 && streamUrl(stream).isNotBlank()
|
||||
}
|
||||
.let { candidates ->
|
||||
val standard = candidates.filter { it.optInt("id", 80) <= 80 }
|
||||
(standard.ifEmpty { candidates }).maxWithOrNull(
|
||||
compareBy<JSONObject> { it.optInt("height") }
|
||||
.thenBy { it.optLong("bandwidth") },
|
||||
)
|
||||
} ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
|
||||
.groupBy { it.optInt("id") }
|
||||
.values.map { variants -> variants.maxBy { it.optLong("bandwidth") } }
|
||||
val standard = candidates.filter { it.optInt("id") <= 80 }
|
||||
val video = (standard.ifEmpty { candidates }).maxWithOrNull(
|
||||
compareBy<JSONObject> { it.optInt("height") }.thenBy { it.optLong("bandwidth") },
|
||||
) ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
|
||||
val audio = dash.optJSONArray("audio").objects()
|
||||
.filter { stream ->
|
||||
(stream.optString("codecs").startsWith("mp4a") || stream.optString("codecs").isBlank()) &&
|
||||
@@ -288,6 +290,11 @@ internal object ContentJson {
|
||||
durationMs = data.optLong("timelength").takeIf { it > 0 }
|
||||
?: (dash.optDouble("duration", 0.0) * 1_000).toLong(),
|
||||
referer = referer(episode),
|
||||
qualityId = quality,
|
||||
qualities = candidates.sortedByDescending { it.optInt("id") }.map { candidate ->
|
||||
val id = candidate.optInt("id")
|
||||
PlaybackQuality(id, qualityLabel(data, id), stream(candidate))
|
||||
},
|
||||
)
|
||||
}
|
||||
val parts = data.optJSONArray("durl").objects()
|
||||
@@ -305,6 +312,7 @@ internal object ContentJson {
|
||||
qualityLabel = qualityLabel(data, data.optInt("quality")),
|
||||
durationMs = data.optLong("timelength", part.optLong("length")),
|
||||
referer = referer(episode),
|
||||
qualityId = data.optInt("quality"),
|
||||
)
|
||||
}
|
||||
throw ClientException("没有获取到可播放的视频流,请确认已登录、账号权限及所在地区")
|
||||
@@ -326,6 +334,8 @@ internal object ContentJson {
|
||||
}
|
||||
|
||||
private fun qualityLabel(data: JSONObject, quality: Int): String {
|
||||
data.optJSONArray("support_formats").objects().firstOrNull { it.optInt("quality") == quality }
|
||||
?.optString("new_description")?.takeIf { it.isNotBlank() }?.let { return it }
|
||||
val ids = data.optJSONArray("accept_quality")
|
||||
val descriptions = data.optJSONArray("accept_description")
|
||||
if (ids != null && descriptions != null) {
|
||||
|
||||
@@ -4,6 +4,13 @@ package dev.bulubulu.tv.player
|
||||
|
||||
import androidx.media3.datasource.DefaultHttpDataSource
|
||||
import dev.bulubulu.tv.data.BiliHttpClient
|
||||
import dev.bulubulu.tv.core.PlaybackSource
|
||||
import dev.bulubulu.tv.core.PlaybackStream
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.exoplayer.source.MediaSource
|
||||
import androidx.media3.exoplayer.source.MergingMediaSource
|
||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||
|
||||
/** CDN requests must use the same browser identity as the playback API request. */
|
||||
internal fun mediaHttpDataSourceFactory(referer: String): DefaultHttpDataSource.Factory =
|
||||
@@ -13,3 +20,16 @@ internal fun mediaHttpDataSourceFactory(referer: String): DefaultHttpDataSource.
|
||||
.setConnectTimeoutMs(15_000)
|
||||
.setReadTimeoutMs(20_000)
|
||||
.setAllowCrossProtocolRedirects(false)
|
||||
|
||||
internal fun playbackMediaSource(source: PlaybackSource, video: PlaybackStream = source.video): MediaSource {
|
||||
val http = mediaHttpDataSourceFactory(source.referer)
|
||||
val alternatives = buildMap {
|
||||
put(video.url, video.backupUrls)
|
||||
source.audio?.let { put(it.url, it.backupUrls) }
|
||||
}
|
||||
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
|
||||
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
|
||||
.createMediaSource(MediaItem.fromUri(url))
|
||||
val videoSource = track(video.url)
|
||||
return source.audio?.let { MergingMediaSource(true, true, videoSource, track(it.url)) } ?: videoSource
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.bulubulu.tv.player
|
||||
|
||||
import dev.bulubulu.tv.core.PlaybackQuality
|
||||
import dev.bulubulu.tv.core.PlaybackSource
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
internal data class PlaybackCheckpoint(val positionMs: Long, val playWhenReady: Boolean)
|
||||
internal data class QualitySelectionState(
|
||||
val current: PlaybackQuality,
|
||||
val switchingTo: PlaybackQuality? = null,
|
||||
val restoring: Boolean = false,
|
||||
)
|
||||
|
||||
/** Keeps a quality change transactional until both tracks are ready. Main-thread owned. */
|
||||
internal class PlaybackQualitySwitcher(
|
||||
source: PlaybackSource,
|
||||
private val checkpoint: () -> PlaybackCheckpoint,
|
||||
private val load: (PlaybackQuality, PlaybackCheckpoint) -> Unit,
|
||||
) {
|
||||
private val initial = source.qualities.firstOrNull { it.id == source.qualityId }
|
||||
?: source.qualities.firstOrNull { it.video.url == source.video.url }
|
||||
?: PlaybackQuality(source.qualityId, source.qualityLabel.ifBlank { "当前清晰度" }, source.video)
|
||||
val options = (source.qualities + initial).distinctBy { it.id }.sortedByDescending { it.id }
|
||||
private val _state = MutableStateFlow(QualitySelectionState(initial))
|
||||
val state = _state.asStateFlow()
|
||||
private data class Request(
|
||||
val previous: PlaybackQuality,
|
||||
val target: PlaybackQuality,
|
||||
val checkpoint: PlaybackCheckpoint,
|
||||
val restoring: Boolean = false,
|
||||
)
|
||||
private var pending: Request? = null
|
||||
private var closed = false
|
||||
|
||||
fun select(id: Int): Boolean {
|
||||
if (closed || pending != null || id == _state.value.current.id) return false
|
||||
val target = options.firstOrNull { it.id == id } ?: return false
|
||||
val request = Request(_state.value.current, target, checkpoint())
|
||||
pending = request
|
||||
_state.value = QualitySelectionState(request.previous, target)
|
||||
return try {
|
||||
load(target, request.checkpoint)
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
onFailure()
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true only after recovery is ready, so the UI can report it accurately. */
|
||||
fun onReady(): Boolean {
|
||||
if (closed) return false
|
||||
val request = pending ?: return false
|
||||
pending = null
|
||||
_state.value = QualitySelectionState(if (request.restoring) request.previous else request.target)
|
||||
return request.restoring
|
||||
}
|
||||
|
||||
/** A failed new source is restored once; failure of the original source is surfaced normally. */
|
||||
fun onFailure(): Boolean {
|
||||
if (closed) return false
|
||||
val request = pending ?: return false
|
||||
if (request.restoring) {
|
||||
pending = null
|
||||
_state.value = QualitySelectionState(request.previous)
|
||||
return false
|
||||
}
|
||||
pending = request.copy(restoring = true)
|
||||
_state.value = QualitySelectionState(request.previous, request.previous, restoring = true)
|
||||
return try {
|
||||
load(request.previous, request.checkpoint)
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
pending = null
|
||||
_state.value = QualitySelectionState(request.previous)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun close() { closed = true; pending = null }
|
||||
}
|
||||
@@ -34,11 +34,14 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalWindowInfo
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -47,18 +50,14 @@ import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.exoplayer.DefaultLoadControl
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.source.MediaSource
|
||||
import androidx.media3.exoplayer.source.MergingMediaSource
|
||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||
import androidx.media3.ui.PlayerView
|
||||
import dev.bulubulu.tv.core.PlaybackSource
|
||||
import dev.bulubulu.tv.ui.TvAccent
|
||||
@@ -72,9 +71,14 @@ import kotlinx.coroutines.isActive
|
||||
fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
val windowFocused = LocalWindowInfo.current.isWindowFocused
|
||||
val errorCallback by rememberUpdatedState(onPlaybackError)
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val retryFocus = remember { FocusRequester() }
|
||||
val qualityFocus = remember { FocusRequester() }
|
||||
var qualityMenuOpen by remember(source) { mutableStateOf(false) }
|
||||
var qualityButtonFocused by remember(source) { mutableStateOf(false) }
|
||||
var focusQualityRequested by remember(source) { mutableStateOf(false) }
|
||||
var isPlaying by remember(source) { mutableStateOf(false) }
|
||||
var buffering by remember(source) { mutableStateOf(true) }
|
||||
var ended by remember(source) { mutableStateOf(false) }
|
||||
@@ -86,28 +90,35 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
var lastSeekEvent by remember(source) { mutableLongStateOf(0) }
|
||||
val player = remember(context, source) {
|
||||
androidx.media3.common.util.Log.setLogLevel(androidx.media3.common.util.Log.LOG_LEVEL_OFF)
|
||||
val http = mediaHttpDataSourceFactory(source.referer)
|
||||
val alternatives = buildMap {
|
||||
put(source.video.url, source.video.backupUrls)
|
||||
source.audio?.let { put(it.url, it.backupUrls) }
|
||||
}
|
||||
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
|
||||
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
|
||||
.createMediaSource(MediaItem.fromUri(url))
|
||||
val video = track(source.video.url)
|
||||
val media = source.audio?.let { MergingMediaSource(true, true, video, track(it.url)) } ?: video
|
||||
ExoPlayer.Builder(context)
|
||||
.setRenderersFactory(DefaultRenderersFactory(context).setEnableDecoderFallback(true))
|
||||
.setLoadControl(DefaultLoadControl.Builder().setBufferDurationsMs(10_000, 30_000, 1_000, 2_000).build())
|
||||
.build().apply {
|
||||
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
|
||||
setHandleAudioBecomingNoisy(true)
|
||||
setMediaSource(media)
|
||||
setMediaSource(playbackMediaSource(source))
|
||||
playWhenReady = true
|
||||
prepare()
|
||||
}
|
||||
}
|
||||
DisposableEffect(player, lifecycleOwner) {
|
||||
val qualitySwitcher = remember(player, source) {
|
||||
PlaybackQualitySwitcher(
|
||||
source,
|
||||
checkpoint = { PlaybackCheckpoint(player.currentPosition.coerceAtLeast(0), player.playWhenReady) },
|
||||
load = { quality, checkpoint ->
|
||||
// Separate progressive tracks can change decoder dimensions/profile.
|
||||
// Release the old track resources before preparing the replacement.
|
||||
player.stop()
|
||||
player.setMediaSource(playbackMediaSource(source, quality.video))
|
||||
player.seekTo(checkpoint.positionMs)
|
||||
player.playWhenReady = checkpoint.playWhenReady && lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)
|
||||
player.prepare()
|
||||
position = checkpoint.positionMs
|
||||
},
|
||||
)
|
||||
}
|
||||
val qualityState by qualitySwitcher.state.collectAsStateWithLifecycle()
|
||||
DisposableEffect(player, lifecycleOwner, qualitySwitcher) {
|
||||
val listener = object : Player.Listener {
|
||||
override fun onIsPlayingChanged(playing: Boolean) { isPlaying = playing }
|
||||
override fun onPlaybackStateChanged(state: Int) {
|
||||
@@ -115,9 +126,18 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
ended = state == Player.STATE_ENDED
|
||||
if (ended) controlsVisible = true
|
||||
if (player.duration > 0) duration = player.duration
|
||||
if (state == Player.STATE_READY && qualitySwitcher.onReady()) {
|
||||
errorCallback("切换未成功,已恢复原清晰度")
|
||||
}
|
||||
}
|
||||
override fun onPlayerError(exception: PlaybackException) {
|
||||
if (qualitySwitcher.onFailure()) {
|
||||
buffering = true
|
||||
return
|
||||
}
|
||||
buffering = false
|
||||
qualityMenuOpen = false
|
||||
focusQualityRequested = false
|
||||
val message = when (exception.errorCode) {
|
||||
PlaybackException.ERROR_CODE_DECODING_FAILED,
|
||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
|
||||
@@ -147,6 +167,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
onDispose {
|
||||
lifecycleOwner.lifecycle.removeObserver(observer)
|
||||
player.removeListener(listener)
|
||||
qualitySwitcher.close()
|
||||
player.release()
|
||||
}
|
||||
}
|
||||
@@ -159,14 +180,21 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
delay(400)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(lastInteraction, isPlaying, error) {
|
||||
if (isPlaying && error == null) {
|
||||
LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen) {
|
||||
if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen) {
|
||||
delay(4_000)
|
||||
controlsVisible = false
|
||||
} else {
|
||||
controlsVisible = true
|
||||
}
|
||||
}
|
||||
LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused) {
|
||||
if (focusQualityRequested && controlsVisible && !qualityMenuOpen && error == null && windowFocused) {
|
||||
delay(100)
|
||||
qualityFocus.requestFocus()
|
||||
focusQualityRequested = false
|
||||
}
|
||||
}
|
||||
LaunchedEffect(error) {
|
||||
if (error != null) { delay(100); retryFocus.requestFocus() }
|
||||
}
|
||||
@@ -184,9 +212,13 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
modifier = Modifier.fillMaxSize().background(Color.Black)
|
||||
.focusRequester(focusRequester)
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (error != null) return@onPreviewKeyEvent false
|
||||
if (error != null || qualityMenuOpen) return@onPreviewKeyEvent false
|
||||
val native = event.nativeKeyEvent
|
||||
val key = native.keyCode
|
||||
// Let the focused action receive its own confirm events.
|
||||
if (qualityButtonFocused && key in setOf(KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)) {
|
||||
return@onPreviewKeyEvent false
|
||||
}
|
||||
val supported = key in setOf(
|
||||
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
|
||||
KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY,
|
||||
@@ -208,7 +240,14 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
}
|
||||
interact()
|
||||
}
|
||||
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> interact()
|
||||
KeyEvent.KEYCODE_DPAD_UP -> {
|
||||
interact()
|
||||
focusQualityRequested = true
|
||||
}
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> {
|
||||
interact()
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
KeyEvent.KEYCODE_MEDIA_PLAY -> if (native.repeatCount == 0) { player.play(); interact() }
|
||||
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (native.repeatCount == 0) { player.pause(); interact() }
|
||||
else -> if (native.repeatCount == 0) togglePlayback()
|
||||
@@ -240,9 +279,20 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
}
|
||||
if (controlsVisible && error == null) {
|
||||
Box(Modifier.fillMaxWidth().height(110.dp).align(Alignment.TopCenter).background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent))))
|
||||
Column(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp)) {
|
||||
Text(source.title, color = TvText, fontSize = 21.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (source.qualityLabel.isNotBlank()) Text(source.qualityLabel, color = TvMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp))
|
||||
Row(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(source.title, color = TvText, fontSize = 21.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
when {
|
||||
qualityState.restoring -> "正在恢复 ${qualityState.current.label}…"
|
||||
qualityState.switchingTo != null -> "正在切换到 ${qualityState.switchingTo?.label}…"
|
||||
else -> qualityState.current.label
|
||||
},
|
||||
color = TvMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
}
|
||||
TvAction("清晰度", { qualityMenuOpen = true; interact() }, Modifier.focusRequester(qualityFocus)
|
||||
.onFocusChanged { qualityButtonFocused = it.isFocused }.testTag("quality_button"))
|
||||
}
|
||||
Column(
|
||||
Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
@@ -259,7 +309,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height)
|
||||
drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height)
|
||||
}
|
||||
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 返回键 退出", color = TvMuted, fontSize = 12.sp)
|
||||
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 上键 清晰度 返回键 退出", color = TvMuted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
error?.let { message ->
|
||||
@@ -277,5 +327,21 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
}
|
||||
}
|
||||
}
|
||||
if (qualityMenuOpen) {
|
||||
QualityDialog(
|
||||
options = qualitySwitcher.options,
|
||||
selectedId = qualityState.current.id,
|
||||
switching = qualityState.switchingTo != null,
|
||||
onSelected = { quality ->
|
||||
qualityMenuOpen = false
|
||||
focusQualityRequested = true
|
||||
interact()
|
||||
if (quality.id != qualityState.current.id && !qualitySwitcher.select(quality.id)) {
|
||||
errorCallback("暂时无法切换清晰度,请重试")
|
||||
}
|
||||
},
|
||||
onDismiss = { qualityMenuOpen = false; focusQualityRequested = true; interact() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package dev.bulubulu.tv.player
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.LocalWindowInfo
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.DialogWindowProvider
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import dev.bulubulu.tv.core.PlaybackQuality
|
||||
import dev.bulubulu.tv.ui.TvAction
|
||||
import dev.bulubulu.tv.ui.TvMuted
|
||||
import dev.bulubulu.tv.ui.TvPanel
|
||||
import dev.bulubulu.tv.ui.TvText
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable
|
||||
internal fun QualityDialog(
|
||||
options: List<PlaybackQuality>,
|
||||
selectedId: Int,
|
||||
switching: Boolean,
|
||||
onSelected: (PlaybackQuality) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val selectedFocus = remember { FocusRequester() }
|
||||
val closeFocus = remember { FocusRequester() }
|
||||
val list = rememberLazyListState()
|
||||
val selectedIndex = options.indexOfFirst { it.id == selectedId }.coerceAtLeast(0)
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
|
||||
) {
|
||||
val view = LocalView.current
|
||||
val windowFocused = LocalWindowInfo.current.isWindowFocused
|
||||
LaunchedEffect(view) {
|
||||
// Keep the video surface at its fullscreen size while the menu owns focus.
|
||||
(view.parent as? DialogWindowProvider)?.window?.let { window ->
|
||||
WindowCompat.getInsetsController(window, view).apply {
|
||||
hide(WindowInsetsCompat.Type.systemBars())
|
||||
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(switching, windowFocused) {
|
||||
if (!windowFocused) return@LaunchedEffect
|
||||
if (switching || options.isEmpty()) {
|
||||
delay(100)
|
||||
closeFocus.requestFocus()
|
||||
} else {
|
||||
list.scrollToItem(selectedIndex)
|
||||
delay(100)
|
||||
selectedFocus.requestFocus()
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
color = TvPanel, contentColor = TvText, shape = RoundedCornerShape(22.dp),
|
||||
modifier = Modifier.widthIn(max = 460.dp).fillMaxWidth(0.9f)
|
||||
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(22.dp)).testTag("quality_menu"),
|
||||
) {
|
||||
Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("清晰度", fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
if (switching) "正在切换,请稍候…" else "切换后从当前进度继续",
|
||||
color = TvMuted, fontSize = 14.sp,
|
||||
)
|
||||
LazyColumn(
|
||||
state = list, modifier = Modifier.fillMaxWidth().heightIn(max = 210.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(options, key = { it.id }) { quality ->
|
||||
val selected = quality.id == options.getOrNull(selectedIndex)?.id
|
||||
TvAction(
|
||||
quality.label + if (quality.id == selectedId) " · 当前" else "",
|
||||
{ onSelected(quality) },
|
||||
Modifier.fillMaxWidth().testTag("quality_${quality.id}").then(
|
||||
if (selected) Modifier.focusRequester(selectedFocus) else Modifier,
|
||||
),
|
||||
selected = quality.id == selectedId, enabled = !switching,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
if (options.size == 1) "当前仅提供这一档清晰度" else "可选项取决于视频、账号权限和设备兼容性",
|
||||
color = TvMuted, fontSize = 12.sp,
|
||||
)
|
||||
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus).testTag("quality_close"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package dev.bulubulu.tv
|
||||
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.core.VideoEpisode
|
||||
import dev.bulubulu.tv.data.ContentJson
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class PlaybackQualityJsonTest {
|
||||
private val episode = VideoEpisode("p1", "P1", "视频", bvid = "BV1test", cid = 123)
|
||||
|
||||
@Test fun advertisedButUnavailableQualitiesAreNotSelectable() {
|
||||
val source = parse("""{
|
||||
"quality":64,"accept_quality":[112,80,64,32,16],
|
||||
"accept_description":["1080P+","1080P","720P","480P","360P"],
|
||||
"dash":{"video":[${video(32, 480)},${video(16, 360)}],"audio":[$audio]}
|
||||
}""")
|
||||
assertEquals(listOf(32, 16), source.qualities.map { it.id })
|
||||
assertEquals(32, source.qualityId)
|
||||
assertEquals("480P", source.qualityLabel)
|
||||
}
|
||||
|
||||
@Test fun onlyCompatibleTracksAreKeptAndDuplicateRenditionsAreCombined() {
|
||||
val higherBitrate = JSONObject(video(64, 720)).put("bandwidth", 2_000).put("baseUrl", "https://cdn.example/better.m4s")
|
||||
.put("backupUrl", org.json.JSONArray("""["https://backup.example/better.m4s"]"""))
|
||||
val source = parse("""{"dash":{"video":[
|
||||
${video(80, 1080, "hvc1.1.6", 12)},${video(74, 720, "av01.0.08", 13)},
|
||||
${video(64, 720)},$higherBitrate,${video(16, 360)}
|
||||
],"audio":[$audio]}}""")
|
||||
assertEquals(listOf(64, 16), source.qualities.map { it.id })
|
||||
assertEquals("https://cdn.example/better.m4s", source.video.url)
|
||||
assertEquals(listOf("https://backup.example/better.m4s"), source.qualities.first().video.backupUrls)
|
||||
}
|
||||
|
||||
@Test fun higherAvailableQualitiesAreOfferedButDefaultRemainsOrdinary1080p() {
|
||||
val source = parse("""{"support_formats":[{"quality":112,"new_description":"1080P 高码率"}],
|
||||
"dash":{"video":[${video(120, 2160)},${video(112, 1080)},${video(80, 1080)},${video(32, 480)}],"audio":[$audio]}}
|
||||
""")
|
||||
assertEquals(80, source.qualityId)
|
||||
assertEquals(listOf(120, 112, 80, 32), source.qualities.map { it.id })
|
||||
assertEquals("1080P 高码率", source.qualities.first { it.id == 112 }.label)
|
||||
}
|
||||
|
||||
@Test fun brokenAndContradictoryCodecTracksCannotBecomeOptions() {
|
||||
val invalid = JSONObject(video(80, 1080)).put("baseUrl", "file:///private/data")
|
||||
val source = parse("""{"dash":{"video":[
|
||||
${video(80, 1080, "hvc1.1.6", 7)},$invalid,${video(16, 360)}
|
||||
],"audio":[$audio]}}""")
|
||||
assertEquals(listOf(16), source.qualities.map { it.id })
|
||||
}
|
||||
|
||||
@Test fun missingAacIsRejectedForEveryQuality() {
|
||||
try {
|
||||
parse("""{"dash":{"video":[${video(80, 1080)}],"audio":[]}}""")
|
||||
fail("A silent source must not be offered")
|
||||
} catch (_: ClientException) { }
|
||||
}
|
||||
|
||||
@Test fun progressiveSourceKeepsItsActualQuality() {
|
||||
val source = parse("""{"quality":32,"durl":[{"url":"https://cdn.example/file.mp4"}]}""")
|
||||
assertEquals(32, source.qualityId)
|
||||
assertEquals("480P", source.qualityLabel)
|
||||
assertTrue(source.qualities.isEmpty())
|
||||
}
|
||||
|
||||
private fun parse(value: String) = ContentJson.playback(JSONObject(value), episode)
|
||||
private fun video(id: Int, height: Int, codec: String = "avc1.64001f", codecId: Int = 7) =
|
||||
"""{"id":$id,"height":$height,"bandwidth":1000,"codecs":"$codec","codecid":$codecId,"baseUrl":"https://cdn.example/$id.m4s"}"""
|
||||
private val audio = """{"codecs":"mp4a.40.2","baseUrl":"https://cdn.example/audio.m4s"}"""
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package dev.bulubulu.tv.player
|
||||
|
||||
import dev.bulubulu.tv.core.PlaybackQuality
|
||||
import dev.bulubulu.tv.core.PlaybackSource
|
||||
import dev.bulubulu.tv.core.PlaybackStream
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class PlaybackQualitySwitcherTest {
|
||||
private val hd = PlaybackQuality(80, "1080P", PlaybackStream("https://cdn.example/hd.m4s"))
|
||||
private val low = PlaybackQuality(32, "480P", PlaybackStream("https://cdn.example/low.m4s"))
|
||||
private val source = PlaybackSource("投稿", hd.video, qualityLabel = hd.label, qualityId = hd.id, qualities = listOf(hd, low))
|
||||
|
||||
@Test fun selectionKeepsPositionAndOnlyCommitsAfterTracksAreReady() {
|
||||
val checkpoint = PlaybackCheckpoint(94_600, true)
|
||||
val loaded = mutableListOf<Pair<PlaybackQuality, PlaybackCheckpoint>>()
|
||||
val switcher = PlaybackQualitySwitcher(source, { checkpoint }) { quality, at -> loaded += quality to at }
|
||||
assertTrue(switcher.select(32))
|
||||
assertEquals(listOf(low to checkpoint), loaded)
|
||||
assertEquals(hd, switcher.state.value.current)
|
||||
assertEquals(low, switcher.state.value.switchingTo)
|
||||
assertFalse(switcher.onReady())
|
||||
assertEquals(low, switcher.state.value.current)
|
||||
assertNull(switcher.state.value.switchingTo)
|
||||
}
|
||||
|
||||
@Test fun switchingPausedVideoDoesNotStartPlayback() {
|
||||
var captured: PlaybackCheckpoint? = null
|
||||
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(120_000, false) }) { _, at -> captured = at }
|
||||
switcher.select(32)
|
||||
assertEquals(PlaybackCheckpoint(120_000, false), captured)
|
||||
switcher.onReady()
|
||||
assertEquals(32, switcher.state.value.current.id)
|
||||
}
|
||||
|
||||
@Test fun currentUnknownAndOverlappingChoicesDoNotReload() {
|
||||
var requests = 0
|
||||
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(100, true) }) { _, _ -> requests++ }
|
||||
assertFalse(switcher.select(80))
|
||||
assertFalse(switcher.select(120))
|
||||
assertTrue(switcher.select(32))
|
||||
assertFalse(switcher.select(80))
|
||||
assertFalse(switcher.select(32))
|
||||
assertEquals(1, requests)
|
||||
}
|
||||
|
||||
@Test fun failedNewQualityRestoresOriginalProgressAndPausedStateOnce() {
|
||||
val checkpoint = PlaybackCheckpoint(81_300, false)
|
||||
val loaded = mutableListOf<Pair<PlaybackQuality, PlaybackCheckpoint>>()
|
||||
val switcher = PlaybackQualitySwitcher(source, { checkpoint }) { quality, at -> loaded += quality to at }
|
||||
switcher.select(32)
|
||||
assertTrue(switcher.onFailure())
|
||||
assertTrue(switcher.state.value.restoring)
|
||||
assertEquals(listOf(low to checkpoint, hd to checkpoint), loaded)
|
||||
assertTrue(switcher.onReady())
|
||||
assertEquals(hd, switcher.state.value.current)
|
||||
assertFalse(switcher.state.value.restoring)
|
||||
assertNull(switcher.state.value.switchingTo)
|
||||
assertFalse(switcher.onFailure())
|
||||
}
|
||||
|
||||
@Test fun recoveryFailureIsSurfacedWithoutRetryLoop() {
|
||||
var requests = 0
|
||||
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(30_000, true) }) { _, _ -> requests++ }
|
||||
switcher.select(32)
|
||||
assertTrue(switcher.onFailure())
|
||||
assertFalse(switcher.onFailure())
|
||||
assertEquals(2, requests)
|
||||
assertNull(switcher.state.value.switchingTo)
|
||||
}
|
||||
|
||||
@Test fun closingRejectsLateCallbacksAndNewRequests() {
|
||||
var requests = 0
|
||||
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(0, true) }) { _, _ -> requests++ }
|
||||
switcher.select(32)
|
||||
switcher.close()
|
||||
assertFalse(switcher.onReady())
|
||||
assertFalse(switcher.onFailure())
|
||||
assertFalse(switcher.select(80))
|
||||
assertEquals(hd, switcher.state.value.current)
|
||||
assertEquals(1, requests)
|
||||
}
|
||||
|
||||
@Test fun progressiveVideoHasOneHonestChoice() {
|
||||
val progressive = source.copy(qualities = emptyList())
|
||||
val switcher = PlaybackQualitySwitcher(progressive, { PlaybackCheckpoint(0, true) }) { _, _ -> error("Unexpected reload") }
|
||||
assertEquals(listOf(hd), switcher.options)
|
||||
assertFalse(switcher.select(80))
|
||||
}
|
||||
|
||||
@Test fun synchronousSourceFailureAlsoAttemptsRecovery() {
|
||||
val loaded = mutableListOf<Int>()
|
||||
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(42_000, true) }) { quality, _ ->
|
||||
loaded += quality.id
|
||||
if (quality.id == 32) throw IllegalArgumentException("invalid source")
|
||||
}
|
||||
assertTrue(switcher.select(32))
|
||||
assertEquals(listOf(32, 80), loaded)
|
||||
assertTrue(switcher.onReady())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user