fix: 退出立即暂停并优先可解码音轨
退出播放页与进入画中画失败时立即暂停,避免退场期间继续出声; 音轨列表标出设备是否支持,存在常规编码时自动避开 AC3/DTS 等 passthrough 音频并提示。
This commit is contained in:
1 parent
4c533f31cf
commit
e651b1c4b4
4 files changed
+88
-9
No files matched your search
@@ -14,6 +14,7 @@ import android.view.TextureView
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.widget.Toast
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.RequiresApi
|
||||
@@ -54,6 +55,8 @@ import com.ttstd.player.render.TextureViewBinding
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private val PASSTHROUGH_AUDIO = setOf("audio/ac3", "audio/eac3", "audio/vnd.dts", "audio/vnd.dts.hd", "audio/truehd")
|
||||
|
||||
/** 播放界面只拥有 Surface 与控件;内核/观看会话由 PlayerModel 管理。 */
|
||||
class PlayerActivity : AppCompatActivity() {
|
||||
private lateinit var model: PlayerModel
|
||||
@@ -82,6 +85,9 @@ class PlayerActivity : AppCompatActivity() {
|
||||
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
model = androidx.lifecycle.ViewModelProvider(this)[PlayerModel::class.java]
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() { closePlayer() }
|
||||
})
|
||||
setContent { TTVideoTheme { PlayerRoot() } }
|
||||
lifecycleScope.launch {
|
||||
model.notices.collect { Toast.makeText(this@PlayerActivity, it, Toast.LENGTH_LONG).show() }
|
||||
@@ -114,6 +120,10 @@ class PlayerActivity : AppCompatActivity() {
|
||||
val duration = if (remote == "dlna") dlna.playback.durationMs else model.duration()
|
||||
val playing = if (remote == "dlna") dlna.playback.playing else state.playWhenReady
|
||||
val subtitleText = if (remote == null) state.subtitleLines.joinToString("\n") else ""
|
||||
val audioTracks = state.tracks.filter { it.type == TrackType.AUDIO }
|
||||
val selectedAudio = audioTracks.firstOrNull { it.selected } ?: audioTracks.firstOrNull()
|
||||
val audioUnsupported = selectedAudio != null && !selectedAudio.supported
|
||||
val audioWarning = audioUnsupported || selectedAudio?.mimeType in PASSTHROUGH_AUDIO
|
||||
val centerText = when {
|
||||
remote == "dlna" -> "正在 ${dlna.device} 播放\n${dlna.error ?: "可关闭页面,投屏会继续"}"
|
||||
loading || state.phase == PlaybackPhase.PREPARING || state.phase == PlaybackPhase.BUFFERING -> "正在缓冲…"
|
||||
@@ -137,6 +147,14 @@ class PlayerActivity : AppCompatActivity() {
|
||||
}
|
||||
LaunchedEffect(state.playWhenReady, ratio, remote) { updatePipParams() }
|
||||
LaunchedEffect(pip) { if (pip) controlsVisible = false else controlsVisible = true }
|
||||
LaunchedEffect(current?.ref?.id, audioWarning, audioUnsupported) {
|
||||
if (audioWarning) Toast.makeText(
|
||||
this@PlayerActivity,
|
||||
if (audioUnsupported) "当前音轨设备不支持,将静音播放;可切换音轨或使用 AAC 转码版本"
|
||||
else "当前音轨为 AC3/DTS 环绕音频,需设备/功放支持;若无声音请切换音轨或使用 AAC 转码版本",
|
||||
Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
@@ -163,7 +181,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
if (showControls) {
|
||||
TopBar(
|
||||
title = current?.ref?.title ?: "正在准备视频",
|
||||
onBack = { finish() },
|
||||
onBack = { closePlayer() },
|
||||
modifier = Modifier.align(Alignment.TopCenter),
|
||||
actions = {
|
||||
TextButton(onClick = { dialog = PlayerDialog.Cast; devices = null; castError = null }) { Text("投屏", color = AppAccent) }
|
||||
@@ -180,6 +198,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
dlna = dlna,
|
||||
landscape = true,
|
||||
fromServer = current?.ref?.accountId != null,
|
||||
audioWarning = audioWarning,
|
||||
modifier = Modifier.align(Alignment.BottomCenter),
|
||||
onSeek = ::seekTo,
|
||||
onSeekBy = ::seekBy,
|
||||
@@ -193,7 +212,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
TopBar(
|
||||
title = current?.ref?.title ?: "正在准备视频",
|
||||
onBack = { finish() },
|
||||
onBack = { closePlayer() },
|
||||
actions = {
|
||||
TextButton(onClick = { dialog = PlayerDialog.Cast; devices = null; castError = null }) { Text("投屏", color = AppAccent) }
|
||||
TextButton(onClick = { dialog = PlayerDialog.Menu }) { Text("⋮", color = AppInk, fontSize = 20.sp) }
|
||||
@@ -224,6 +243,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
dlna = dlna,
|
||||
landscape = false,
|
||||
fromServer = current?.ref?.accountId != null,
|
||||
audioWarning = audioWarning,
|
||||
onSeek = ::seekTo,
|
||||
onSeekBy = ::seekBy,
|
||||
onToggle = { togglePlayback(remote, dlna) },
|
||||
@@ -410,6 +430,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
dlna: DlnaUiState,
|
||||
landscape: Boolean,
|
||||
fromServer: Boolean,
|
||||
audioWarning: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onSeek: (Long) -> Unit,
|
||||
onSeekBy: (Long) -> Unit,
|
||||
@@ -460,8 +481,9 @@ class PlayerActivity : AppCompatActivity() {
|
||||
}
|
||||
if (!landscape) {
|
||||
Text(
|
||||
if (remote != null) "投屏中 · 点击右上角投屏管理连接"
|
||||
else "${if (fromServer) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中",
|
||||
(if (remote != null) "投屏中 · 点击右上角投屏管理连接"
|
||||
else "${if (fromServer) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中") +
|
||||
if (audioWarning) "\n当前音轨可能需要设备/功放支持,若无声可切换音轨或转码" else "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = AppMuted,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
@@ -521,7 +543,10 @@ class PlayerActivity : AppCompatActivity() {
|
||||
is PlayerDialog.Tracks -> {
|
||||
val tracks = state.tracks.filter { it.type == dialog.type }
|
||||
val prefix = if (dialog.type == TrackType.TEXT) "关闭字幕" else "自动选择"
|
||||
val labels = listOf(prefix) + tracks.map { "${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}" }
|
||||
val labels = listOf(prefix) + tracks.map {
|
||||
val note = if (!it.supported) "(设备不支持)" else if (it.mimeType in PASSTHROUGH_AUDIO) "(可能需要设备支持)" else ""
|
||||
"${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}$note"
|
||||
}
|
||||
ChoiceDialog(
|
||||
title = if (dialog.type == TrackType.TEXT) "字幕" else "音轨",
|
||||
options = labels,
|
||||
@@ -628,6 +653,16 @@ class PlayerActivity : AppCompatActivity() {
|
||||
} else model.seek((model.absolutePosition() + delta).coerceAtLeast(0))
|
||||
}
|
||||
|
||||
private fun closePlayer() {
|
||||
if (model.remote.value == null) model.pauseForExit()
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
if (isFinishing && model.remote.value == null) model.pauseForExit()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onStart() { super.onStart(); model.onVisible() }
|
||||
|
||||
override fun onResume() {
|
||||
@@ -647,7 +682,10 @@ class PlayerActivity : AppCompatActivity() {
|
||||
if (!model.engine.state.value.playWhenReady || isInPictureInPictureMode) return
|
||||
pipState.value = true
|
||||
val entered = runCatching { enterPictureInPictureMode(pipParams()) }.getOrDefault(false)
|
||||
if (!entered) pipState.value = false
|
||||
if (!entered) {
|
||||
pipState.value = false
|
||||
model.pauseForExit()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
|
||||
@@ -110,6 +110,8 @@ class PlayerModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
fun retry() { val id = current.value?.ref?.id ?: return; playback = null; open(id) }
|
||||
fun toggle() { viewModelScope.launch { if (engine.state.value.playWhenReady) engine.pause() else engine.play() } }
|
||||
/** 退出播放页时立即暂停,避免等 Activity 退场动画/onStop 才静音。 */
|
||||
fun pauseForExit() { viewModelScope.launch(Dispatchers.Main.immediate) { engine.pause() } }
|
||||
/** 播放结束后从起点重播;直播或不可 seek 时直接继续播放。 */
|
||||
fun restart() { viewModelScope.launch { if (engine.state.value.phase == PlaybackPhase.ENDED) engine.seekTo(0); engine.play() } }
|
||||
fun seek(position: Long) { viewModelScope.launch {
|
||||
|
||||
@@ -58,7 +58,7 @@ enum class DecodeMode { AUTO, PREFER_HARDWARE, HARDWARE_ONLY, SOFTWARE_ONLY }
|
||||
data class DecodePolicy(val video: DecodeMode = DecodeMode.AUTO, val audio: DecodeMode = DecodeMode.AUTO)
|
||||
enum class TrackType { VIDEO, AUDIO, TEXT }
|
||||
/** id 仅在当前媒体轨道列表内有效,不保证跨媒体或内核重建稳定。 */
|
||||
data class MediaTrack(val id: String, val type: TrackType, val label: String?, val language: String?, val selected: Boolean)
|
||||
data class MediaTrack(val id: String, val type: TrackType, val label: String?, val language: String?, val selected: Boolean, val supported: Boolean = true, val mimeType: String? = null)
|
||||
/** id=null 恢复自动选择;disabled=true 关闭该类轨道。 */
|
||||
data class TrackSelection(val type: TrackType, val id: String? = null, val disabled: Boolean = false)
|
||||
enum class PlaybackPhase { IDLE, PREPARING, BUFFERING, READY, ENDED, ERROR, RELEASED }
|
||||
|
||||
@@ -57,6 +57,7 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
override fun onTracksChanged(tracks: Tracks) {
|
||||
cachedTracks = buildTracks(tracks)
|
||||
applyDefaultSubtitle(tracks)
|
||||
applySupportedAudio(tracks)
|
||||
val progressive = request?.let { SourceRouting.resolve(it) == MediaSourceType.PROGRESSIVE } == true
|
||||
if (progressive && tracks.groups.isNotEmpty() && tracks.groups.none { it.type == C.TRACK_TYPE_VIDEO }) {
|
||||
handler.removeCallbacks(noVideoCheck)
|
||||
@@ -261,6 +262,44 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
CommandResult.Failed(error)
|
||||
}
|
||||
}
|
||||
/** 有可用音轨时优先 AAC/Opus 等常规编码;AC3/DTS 等环绕音频只在没有更好选择时保留。 */
|
||||
private fun applySupportedAudio(tracks: Tracks) {
|
||||
if (released || lastError != null) return
|
||||
val groups = tracks.groups.filter { it.type == C.TRACK_TYPE_AUDIO }
|
||||
if (groups.isEmpty()) return
|
||||
val supportedGroups = groups.filter { group -> (0 until group.length).any { group.isTrackSupported(it) } }
|
||||
if (supportedGroups.isEmpty()) return
|
||||
val selectedRank = groups.filter { group ->
|
||||
(0 until group.length).any { group.isTrackSelected(it) }
|
||||
}.minOfOrNull(::audioRank) ?: 3
|
||||
val target = supportedGroups.minByOrNull(::audioRank) ?: return
|
||||
val targetRank = audioRank(target)
|
||||
if (targetRank >= selectedRank) return
|
||||
val indices = (0 until target.length).filter { target.isTrackSupported(it) }
|
||||
if (indices.isEmpty()) return
|
||||
handler.post {
|
||||
if (released) return@post
|
||||
player.trackSelectionParameters = player.trackSelectionParameters.buildUpon()
|
||||
.clearOverridesOfType(C.TRACK_TYPE_AUDIO)
|
||||
.setOverrideForType(TrackSelectionOverride(target.mediaTrackGroup, indices))
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
/** 0=常规解码,2=通常依赖 passthrough/功放,3=无可用解码。 */
|
||||
private fun audioRank(group: Tracks.Group): Int {
|
||||
var rank = 3
|
||||
for (index in 0 until group.length) {
|
||||
if (!group.isTrackSupported(index)) continue
|
||||
rank = minOf(rank, when (group.getTrackFormat(index).sampleMimeType) {
|
||||
"audio/ac3", "audio/eac3", "audio/vnd.dts", "audio/vnd.dts.hd", "audio/truehd" -> 2
|
||||
null -> 1
|
||||
else -> 0
|
||||
})
|
||||
}
|
||||
return rank
|
||||
}
|
||||
|
||||
/** 默认字幕(DEFAULT/FORCED)自动选中一次;用户关闭后不再自动打开。 */
|
||||
private fun applyDefaultSubtitle(tracks: Tracks) {
|
||||
if (subtitlePolicyApplied || released || lastError != null) return
|
||||
@@ -274,7 +313,7 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
val flags = item.getTrackFormat(index).selectionFlags
|
||||
(flags and (C.SELECTION_FLAG_DEFAULT or C.SELECTION_FLAG_FORCED)) != 0 && item.isTrackSupported(index)
|
||||
}
|
||||
} ?: candidates.first()
|
||||
} ?: candidates.singleOrNull() ?: return
|
||||
val indices = (0 until group.length).filter { group.isTrackSupported(it) }
|
||||
if (indices.isEmpty()) return
|
||||
subtitlePolicyApplied = true
|
||||
@@ -314,7 +353,7 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
val type = when (group.type) { C.TRACK_TYPE_VIDEO -> TrackType.VIDEO; C.TRACK_TYPE_AUDIO -> TrackType.AUDIO; C.TRACK_TYPE_TEXT -> TrackType.TEXT; else -> null }
|
||||
if (type == null) emptyList() else (0 until group.length).map { t ->
|
||||
val f = group.getTrackFormat(t)
|
||||
MediaTrack("$g:$t", type, f.label, f.language, group.isTrackSelected(t))
|
||||
MediaTrack("$g:$t", type, f.label, f.language, group.isTrackSelected(t), group.isTrackSupported(t), f.sampleMimeType)
|
||||
}
|
||||
}
|
||||
private fun decoder(type: TrackType, name: String) {
|
||||
|
||||
Reference in new issue
Block a user