perf: 优化媒体库与播放状态并修复画中画显示

This commit is contained in:
tongtong committed 2026-11-30 22:53:06 +08:00
1 parent b638ec5408
commit 1614bf5a89
6 files changed
+297 -81

No files matched your search

@@ -2,6 +2,9 @@ package com.ttstd.player.app
import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
@@ -39,42 +42,97 @@ data class MediaRef(
data class RecentMedia(val ref: MediaRef, val positionMs: Long = 0, val durationMs: Long? = null,
val updatedAt: Long = System.currentTimeMillis(), val favorite: Boolean = false)
/** 历史中可能含用户输入的签名 URL/请求头,整份记录 AES-GCM 加密,不做明文回退。 */
/** 历史中可能含用户输入的签名 URL/请求头,整份记录 AES-GCM 加密,不做明文回退。
* 进程内缓存与密钥复用,避免播放时每 5 秒全量解密;进度写入合并后延迟落盘。
*/
class RecentStore(context: Context) {
private val prefs = context.getSharedPreferences("app-recent-media", Context.MODE_PRIVATE)
private val prefs = context.applicationContext.getSharedPreferences("app-recent-media", Context.MODE_PRIVATE)
private var keyCache: SecretKey? = null
private var cache: MutableList<RecentMedia>? = null
private var dirty = false
private var writeScheduled = false
private var lastWriteAt = 0L
private val writerThread = HandlerThread("tt-recent-store").apply { start() }
private val writer = Handler(writerThread.looper)
private val writeTask = Runnable {
synchronized(this) {
writeScheduled = false
if (dirty) {
writeNow()
lastWriteAt = SystemClock.elapsedRealtime()
}
}
}
private fun key(): SecretKey {
keyCache?.let { return it }
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey("tt-video-history-v1", null) as? SecretKey)?.let { return it }
(store.getKey("tt-video-history-v1", null) as? SecretKey)?.let { keyCache = it; return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder("tt-video-history-v1", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}.generateKey().also { keyCache = it }
}
@Synchronized fun all(): List<RecentMedia> {
private fun entries(): MutableList<RecentMedia> = cache ?: load().toMutableList().also { cache = it }
private fun load(): List<RecentMedia> {
val encoded = prefs.getString("records", null) ?: return emptyList()
val bytes = Base64.decode(encoded, Base64.NO_WRAP)
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12))) }
val array = JSONArray(String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8))
return (0 until array.length()).map { decode(array.getJSONObject(it)) }.sortedByDescending { it.updatedAt }
return (0 until array.length()).map { decode(array.getJSONObject(it)) }
}
@Synchronized fun find(id: String): RecentMedia? = all().firstOrNull { it.ref.id == id }
@Synchronized fun all(): List<RecentMedia> = entries().sortedByDescending { it.updatedAt }
@Synchronized fun find(id: String): RecentMedia? = entries().firstOrNull { it.ref.id == id }
@Synchronized fun save(ref: MediaRef, position: Long, duration: Long?): RecentMedia {
val entries = all()
val entries = entries()
val old = entries.firstOrNull { it.ref.id == ref.id }
val value = RecentMedia(ref, position.coerceAtLeast(0), duration, favorite = old?.favorite ?: false)
write((listOf(value) + entries.filterNot { it.ref.id == ref.id }).take(150))
cache = (listOf(value) + entries.filterNot { it.ref.id == ref.id }).take(150).toMutableList()
scheduleWrite()
return value
}
@Synchronized fun favorite(id: String) { write(all().map { if (it.ref.id == id) it.copy(favorite = !it.favorite) else it }) }
@Synchronized fun remove(id: String) { write(all().filterNot { it.ref.id == id }) }
@Synchronized fun clear() { prefs.edit().remove("records").apply() }
private fun write(items: List<RecentMedia>) {
@Synchronized fun favorite(id: String) {
cache = entries().map { if (it.ref.id == id) it.copy(favorite = !it.favorite) else it }.toMutableList()
writeNow()
lastWriteAt = SystemClock.elapsedRealtime()
}
@Synchronized fun remove(id: String) {
cache = entries().filterNot { it.ref.id == id }.toMutableList()
writeNow()
lastWriteAt = SystemClock.elapsedRealtime()
}
@Synchronized fun clear() {
cache = mutableListOf()
dirty = false
writer.removeCallbacks(writeTask)
writeScheduled = false
prefs.edit().remove("records").apply()
}
/** 停止播放或退出页面时调用,保证最后一次进度立即落盘。 */
@Synchronized fun flush() {
if (!dirty) return
writer.removeCallbacks(writeTask)
writeScheduled = false
writeNow()
lastWriteAt = SystemClock.elapsedRealtime()
}
private fun scheduleWrite() {
dirty = true
if (writeScheduled) return
writeScheduled = true
val since = if (lastWriteAt == 0L) Long.MAX_VALUE else SystemClock.elapsedRealtime() - lastWriteAt
writer.postDelayed(writeTask, (WRITE_INTERVAL_MS - since).coerceAtLeast(0))
}
private fun writeNow() {
val items = cache ?: return
val array = JSONArray(); for (item in items) array.put(encode(item))
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) }
val encrypted = cipher.doFinal(array.toString().toByteArray())
prefs.edit().putString("records", Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)).apply()
dirty = false
}
companion object {
private const val WRITE_INTERVAL_MS = 15_000L
/** JSON 编解码独立于 Keystore,便于验证迁移与不丢失来源身份。 */
fun encode(item: RecentMedia): JSONObject {
val r = item.ref
@@ -1,5 +1,6 @@
package com.ttstd.player.app
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
@@ -8,17 +9,23 @@ import android.os.Bundle
import android.provider.MediaStore
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.ttstd.player.app.Ui.dp
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
class LocalLibraryActivity : AppCompatActivity() {
private lateinit var content: LinearLayout
private lateinit var store: LocalMediaStore
private var videos: List<LocalVideo> = emptyList()
private var reloadJob: Job? = null
private var generation = 0
private val thumbGate = Semaphore(4)
private val permission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) reload() else render()
}
@@ -27,7 +34,8 @@ class LocalLibraryActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
store = LocalMediaStore(applicationContext)
build()
if (LocalMediaStore.hasPermission(this)) { videos = store.cached(); reload() }
// 缓存解析与 MediaStore 扫描都放到 IO,避免首帧在主线程读大 JSON。
if (LocalMediaStore.hasPermission(this)) reload()
else permission.launch(LocalMediaStore.requiredPermission())
}
@@ -40,16 +48,19 @@ class LocalLibraryActivity : AppCompatActivity() {
toolbar.addView(Ui.button(this, "刷新") { reload() })
root.addView(toolbar)
content = Ui.column(this)
val scroll = ScrollView(this).apply { isFillViewport = true }; scroll.addView(content)
root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
root.addView(content, LinearLayout.LayoutParams(-1, 0, 1f))
setContentView(root)
}
private fun reload() {
if (!LocalMediaStore.hasPermission(this)) { render(); return }
reloadJob?.cancel()
content.removeAllViews()
content.addView(Ui.label(this, "正在扫描设备与 U 盘…", 14f, Ui.muted).apply { setPadding(0, dp(16), 0, 0) })
lifecycleScope.launch(Dispatchers.IO) {
reloadJob = lifecycleScope.launch(Dispatchers.IO) {
// 先展示上次缓存,缩短首屏等待;扫描仍在后台继续。
val cached = store.cached()
if (cached.isNotEmpty()) withContext(Dispatchers.Main) { videos = cached; render() }
val list = store.refresh()
withContext(Dispatchers.Main) { videos = list; render() }
}
@@ -57,56 +68,93 @@ class LocalLibraryActivity : AppCompatActivity() {
private fun render() {
content.removeAllViews()
generation++
if (!LocalMediaStore.hasPermission(this)) {
content.addView(Ui.empty(this, "需要存储权限", "允许访问视频后才能发现本机与 U 盘中的影片。"))
content.addView(Ui.empty(this, "需要存储权限", "允许访问视频后才能发现本机与 U 盘中的影片。"), LinearLayout.LayoutParams(-1, 0, 1f))
content.addView(Ui.button(this, "授予权限", true) { permission.launch(LocalMediaStore.requiredPermission()) })
return
}
if (videos.isEmpty()) {
content.addView(Ui.empty(this, "还没有视频", "把影片放入设备或 U 盘,然后点右上角刷新。"))
content.addView(Ui.empty(this, "还没有视频", "把影片放入设备或 U 盘,然后点右上角刷新。"), LinearLayout.LayoutParams(-1, 0, 1f))
return
}
content.addView(Ui.label(this, "共 ${videos.size} 部影片", 13f, Ui.muted).apply { setPadding(0, dp(4), 0, dp(12)) })
// 手工网格:ScrollView 内不能嵌可滚动 GridView,按行数分块
// GridView 只创建可见行,避免一次性为几百个视频建卡;缩略图在 bind 时按需加载。
val columns = if (resources.configuration.screenWidthDp >= 720) 5 else 3
videos.chunked(columns).forEach { rowVideos ->
val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
for (item in rowVideos) {
val card = videoCard(item)
row.addView(card, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(10) })
val grid = GridView(this).apply {
numColumns = columns
horizontalSpacing = dp(10)
verticalSpacing = dp(12)
stretchMode = GridView.STRETCH_COLUMN_WIDTH
clipToPadding = false
setPadding(0, 0, 0, dp(12))
adapter = VideoAdapter()
}
content.addView(grid, LinearLayout.LayoutParams(-1, 0, 1f))
}
private fun bind(card: VideoCard, item: LocalVideo) {
card.tag = item.uri
card.title.text = item.title
card.duration.text = Ui.time(item.durationMs)
card.thumbJob?.cancel()
card.thumb.setImageDrawable(null)
card.setOnClickListener { open(item) }
val current = generation
card.thumbJob = lifecycleScope.launch(Dispatchers.IO) {
// 全程最多 4 张缩略图同时解码,低端机不会因为滚动或整库刷新而爆内存。
val bitmap = thumbGate.withPermit { runCatching { loadThumbnail(item) }.getOrNull() } ?: return@launch
withContext(Dispatchers.Main) {
if (current == generation && card.tag == item.uri) card.thumb.setImageBitmap(bitmap)
}
content.addView(row, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = dp(12) })
}
}
private fun videoCard(item: LocalVideo): View {
val card = Ui.column(this)
card.background = Ui.shape(Ui.panel, 12f)
card.gravity = Gravity.CENTER_HORIZONTAL
card.setPadding(dp(8), dp(8), dp(8), dp(6))
val thumb = ImageView(this).apply {
layoutParams = LinearLayout.LayoutParams(-1, dp(96)); scaleType = ImageView.ScaleType.CENTER_CROP
private fun open(item: LocalVideo) {
val ref = MediaRef(item.title, uri = item.uri)
lifecycleScope.launch {
withContext(Dispatchers.IO) { runCatching { AppRepository(applicationContext).recent.save(ref, 0, item.durationMs) } }
PlaybackQueue.set(listOf(ref))
startActivity(Intent(this@LocalLibraryActivity, PlayerActivity::class.java).putExtra("media", ref.id))
}
}
private inner class VideoAdapter : BaseAdapter() {
override fun getCount() = videos.size
override fun getItem(position: Int): Any = videos[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val card = (convertView as? VideoCard) ?: VideoCard(this@LocalLibraryActivity)
bind(card, videos[position])
return card
}
}
private inner class VideoCard(context: Context) : LinearLayout(context) {
val thumb = ImageView(context).apply {
layoutParams = LinearLayout.LayoutParams(-1, dp(96))
scaleType = ImageView.ScaleType.CENTER_CROP
setBackgroundColor(0xFF1E2935.toInt())
}
card.addView(thumb)
card.addView(Ui.label(this, item.title, 13f).apply {
maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END
val title = Ui.label(context, "", 13f).apply {
maxLines = 2
ellipsize = android.text.TextUtils.TruncateAt.END
layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(4) }
})
card.addView(Ui.label(this, Ui.time(item.durationMs), 11f, Ui.muted))
card.isFocusable = true; card.isClickable = true
card.setOnClickListener {
val ref = MediaRef(item.title, uri = item.uri)
lifecycleScope.launch {
withContext(Dispatchers.IO) { runCatching { AppRepository(applicationContext).recent.save(ref, 0, item.durationMs) } }
PlaybackQueue.set(listOf(ref)); startActivity(Intent(this@LocalLibraryActivity, PlayerActivity::class.java).putExtra("media", ref.id))
}
}
lifecycleScope.launch(Dispatchers.IO) {
val bitmap = runCatching { loadThumbnail(item) }.getOrNull()
if (bitmap != null) withContext(Dispatchers.Main) { thumb.setImageBitmap(bitmap) }
val duration = Ui.label(context, "", 11f, Ui.muted)
var thumbJob: Job? = null
init {
orientation = VERTICAL
gravity = Gravity.CENTER_HORIZONTAL
background = Ui.shape(Ui.panel, dp(12).toFloat())
setPadding(dp(8), dp(8), dp(8), dp(6))
addView(thumb)
addView(title)
addView(duration)
isFocusable = true
isClickable = true
}
return card
}
private fun loadThumbnail(item: LocalVideo): Bitmap? {
@@ -120,4 +168,4 @@ class LocalLibraryActivity : AppCompatActivity() {
}
}.getOrNull()
}
}
}
@@ -36,7 +36,7 @@ class LocalMediaStore(context: Context) {
/** 重新扫描 MediaStore(含可插拔卷),结果排序后持久化返回。 */
fun refresh(): List<LocalVideo> {
val list = runCatching { scanVolumes() }.getOrDefault(cache ?: emptyList())
val list = runCatching { scanVolumes() }.getOrElse { cached() }
val sorted = list.sortedWith(compareBy({ it.title.lowercase() }, { -it.dateModified }))
cache = sorted
save(sorted)
@@ -26,6 +26,11 @@ class PlayerActivity : AppCompatActivity() {
private val repo by lazy { AppRepository(applicationContext) }
private var surfaceBinding: AutoCloseable? = null
private lateinit var video: FrameLayout
private lateinit var toolbar: LinearLayout
private lateinit var controls: LinearLayout
private var controlScroll: ScrollView? = null
private var pipMode = false
private var lastAutoEnter: Boolean? = null
private lateinit var subtitle: TextView
private lateinit var center: TextView
private lateinit var title: TextView
@@ -35,6 +40,8 @@ class PlayerActivity : AppCompatActivity() {
private lateinit var information: TextView
private var dragging = false
private var crop = false
private var keepScreenOn = false
private val bufferingPhases = setOf(PlaybackPhase.PREPARING, PlaybackPhase.BUFFERING)
private val google = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
model.googleReturned(it.data?.getLongExtra("position", model.engine.state.value.positionMs) ?: model.engine.state.value.positionMs,
it.data?.getBooleanExtra("playing", true) ?: true)
@@ -63,12 +70,13 @@ class PlayerActivity : AppCompatActivity() {
launch { model.error.collect { render() } }
launch { model.remote.collect { render() } }
launch { model.notices.collect { Toast.makeText(this@PlayerActivity, it, Toast.LENGTH_LONG).show() } }
launch { model.videoRatio.collect { fitVideo() } }
launch { model.videoRatio.collect { fitVideo(); updatePipParams() } }
launch { DlnaSession.state.collect { render() } }
} }
model.open(intent.getStringExtra("media").orEmpty())
}
private fun build() {
pipMode = false
surfaceBinding?.close()
val landscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
val root = FrameLayout(this)
@@ -81,6 +89,7 @@ class PlayerActivity : AppCompatActivity() {
toolbar.addView(title, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12); marginEnd = dp(12) })
toolbar.addView(Ui.button(this, "投屏") { castDialog() })
toolbar.addView(Ui.button(this, "⋮") { menu() })
this.toolbar = toolbar
video = FrameLayout(this).apply { setBackgroundColor(android.graphics.Color.BLACK); clipChildren = true }
subtitle = Ui.label(this, "", 20f).apply {
gravity = Gravity.CENTER; setPadding(dp(20), dp(4), dp(20), dp(16))
@@ -93,6 +102,7 @@ class PlayerActivity : AppCompatActivity() {
video.addView(subtitle, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM))
video.addView(center, FrameLayout.LayoutParams(-1, -1))
val controls = Ui.column(this, 16).apply { setBackgroundColor(0xee101822.toInt()) }
this.controls = controls
time = Ui.label(this, "0:00 / --:--", 13f, Ui.muted)
controls.addView(time)
seek = SeekBar(this).apply { max = 1000 }
@@ -131,11 +141,13 @@ class PlayerActivity : AppCompatActivity() {
root.addView(toolbar, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
root.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM))
subtitle.setPadding(dp(24), dp(4), dp(24), dp(240))
controlScroll = null
} else {
stack.addView(toolbar)
stack.addView(video, LinearLayout.LayoutParams(-1, (resources.displayMetrics.widthPixels * 9 / 16).coerceAtLeast(dp(180))))
val scroll = ScrollView(this).apply { addView(controls) }
stack.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
controlScroll = scroll
}
val gesture = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: android.view.MotionEvent) = true
@@ -157,30 +169,44 @@ class PlayerActivity : AppCompatActivity() {
render()
}
private fun currentDuration(): Long? = if (model.remote.value == "dlna") DlnaSession.state.value.playback.durationMs else model.duration()
/** 播放中每秒都会 render;文本未变化时不触发 TextView 重排。 */
private fun TextView.setTextIfChanged(value: String) {
if (text?.toString() != value) text = value
}
private fun render() {
if (!::center.isInitialized) return
val state = model.engine.state.value
val remote = model.remote.value
val error = model.error.value ?: state.error?.message
title.text = model.current.value?.ref?.title ?: "正在准备视频"
title.setTextIfChanged(model.current.value?.ref?.title ?: "正在准备视频")
val pos = if (remote == "dlna") DlnaSession.state.value.playback.positionMs else model.absolutePosition()
val duration = currentDuration()
time.text = "${Ui.time(pos)} / ${duration?.let(Ui::time) ?: "--:--"}"
time.setTextIfChanged("${Ui.time(pos)} / ${duration?.let(Ui::time) ?: "--:--"}")
if (!dragging && duration != null && duration > 0) seek.progress = (pos * 1000 / duration).coerceIn(0, 1000).toInt()
seek.isEnabled = duration != null && duration > 0
val playing = if (remote == "dlna") DlnaSession.state.value.playback.playing else state.playWhenReady
playButton.text = if (playing) "暂停" else "播放"
subtitle.text = if (remote == null) state.subtitleLines.joinToString("\n") else ""
center.text = when {
playButton.setTextIfChanged(if (playing) "暂停" else "播放")
subtitle.setTextIfChanged(if (remote == null) state.subtitleLines.joinToString("\n") else "")
val centerText = when {
remote == "dlna" -> "正在 ${DlnaSession.state.value.device} 播放\n${DlnaSession.state.value.error ?: "可关闭页面,投屏会继续"}"
model.loading.value || state.phase in setOf(PlaybackPhase.PREPARING, PlaybackPhase.BUFFERING) -> "正在缓冲…"
model.loading.value || state.phase in bufferingPhases -> "正在缓冲…"
error != null -> "$error\n点击重试"
state.phase == PlaybackPhase.ENDED -> "播放结束"
else -> ""
}
center.visibility = if (center.text.isEmpty()) View.GONE else View.VISIBLE
information.text = if (remote != null) "投屏中 · 点击右上角投屏管理连接" else "${if (model.current.value?.ref?.accountId != null) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中"
if (state.isPlaying && remote == null) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
center.setTextIfChanged(centerText)
center.visibility = if (centerText.isEmpty()) View.GONE else View.VISIBLE
information.setTextIfChanged(if (remote != null) "投屏中 · 点击右上角投屏管理连接" else "${if (model.current.value?.ref?.accountId != null) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中")
val keepOn = state.isPlaying && remote == null
if (keepOn != keepScreenOn) {
keepScreenOn = keepOn
if (keepOn) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
val autoEnter = Build.VERSION.SDK_INT >= 31 && state.playWhenReady && remote == null
if (autoEnter != lastAutoEnter) {
lastAutoEnter = autoEnter
updatePipParams()
}
}
private fun seekBy(delta: Long) {
if (model.remote.value == "dlna") startService(Intent(this, DlnaPlaybackService::class.java).setAction("seek")
@@ -238,21 +264,90 @@ class PlayerActivity : AppCompatActivity() {
}
}.show()
}
override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig); build() }
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// 画中画里整页重建会重新创建 Surface,部分设备会短暂或持续黑屏;改为保持现有视频视图。
if (pipMode || (Build.VERSION.SDK_INT >= 24 && isInPictureInPictureMode)) applyPipLayout(true) else build()
}
override fun onUserLeaveHint() { super.onUserLeaveHint(); enterPipIfPossible() }
/** 播放中按 Home/切走时进入画中画;暂停或非视频不进入。 */
private fun enterPipIfPossible() {
if (Build.VERSION.SDK_INT < 26 || model.remote.value != null) return
if (!model.engine.state.value.playWhenReady) return
runCatching {
if (!isInPictureInPictureMode) enterPictureInPictureMode(android.app.PictureInPictureParams.Builder().build())
if (!model.engine.state.value.playWhenReady || isInPictureInPictureMode) return
// 先切成纯视频布局,避免 PiP 动画期间工具栏/控制区占据窗口。
applyPipLayout(true)
val entered = runCatching { enterPictureInPictureMode(pipParams()) }.getOrDefault(false)
if (!entered) applyPipLayout(false)
}
/** 画中画只显示视频;宽高比跟随当前视频,系统据此选择尽量宽的窗口。 */
private fun applyPipLayout(inPip: Boolean) {
if (!::toolbar.isInitialized || !::controls.isInitialized) return
pipMode = inPip
if (inPip) {
toolbar.visibility = View.GONE
controls.visibility = View.GONE
controlScroll?.visibility = View.GONE
val lp = video.layoutParams
if (lp is LinearLayout.LayoutParams) {
lp.height = 0
lp.weight = 1f
video.layoutParams = lp
}
subtitle.setPadding(dp(8), dp(4), dp(8), dp(8))
} else {
toolbar.visibility = View.VISIBLE
controls.visibility = View.VISIBLE
controlScroll?.visibility = View.VISIBLE
val lp = video.layoutParams
if (lp is LinearLayout.LayoutParams) {
lp.height = (resources.displayMetrics.widthPixels * 9 / 16).coerceAtLeast(dp(180))
lp.weight = 0f
video.layoutParams = lp
}
val landscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
subtitle.setPadding(dp(if (landscape) 24 else 20), dp(4), dp(if (landscape) 24 else 20), dp(if (landscape) 240 else 16))
}
video.post { fitVideo() }
}
@androidx.annotation.RequiresApi(26)
private fun pipParams(): android.app.PictureInPictureParams {
val ratio = model.videoRatio.value.takeIf { it.isFinite() && it > 0f } ?: 16f / 9f
val clamped = ratio.coerceIn(1f / 2.39f, 2.39f)
val rational = if (clamped >= 1f) android.util.Rational((clamped * 1000).toInt(), 1000)
else android.util.Rational(1000, (1000 / clamped).toInt())
val builder = android.app.PictureInPictureParams.Builder().setAspectRatio(rational)
if (Build.VERSION.SDK_INT >= 31) {
builder.setAutoEnterEnabled(model.engine.state.value.playWhenReady && model.remote.value == null)
// SurfaceView 在 PiP 缩放时直接重设 buffer 容易闪黑,交给系统做淡入淡出。
builder.setSeamlessResizeEnabled(false)
}
if (::video.isInitialized) {
val rect = android.graphics.Rect()
if (video.getGlobalVisibleRect(rect)) builder.setSourceRectHint(rect)
}
return builder.build()
}
private fun updatePipParams() {
if (Build.VERSION.SDK_INT < 26 || isFinishing || isDestroyed) return
runCatching { setPictureInPictureParams(pipParams()) }
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
if (isInPictureInPictureMode) model.onPipEntered() else model.onPipExited()
if (isInPictureInPictureMode) {
model.onPipEntered()
applyPipLayout(true)
} else {
model.onPipExited()
// 退出 PiP 时按当前方向重建一次,恢复工具栏和控制区。
if (pipMode) build() else render()
}
}
override fun onStart() { super.onStart(); model.onVisible() }
override fun onResume() {
super.onResume()
// 系统未接受 PiP 或未回调时,避免页面停留在纯视频布局。
if (pipMode && (Build.VERSION.SDK_INT < 24 || !isInPictureInPictureMode)) build()
}
override fun onStop() {
// onHidden 内决定:进入 PIP / 低版本后台续播时继续播放,否则暂停。
val inPip = Build.VERSION.SDK_INT >= 24 && isInPictureInPictureMode
@@ -150,8 +150,11 @@ class PlayerModel(application: Application) : AndroidViewModel(application) {
/** PlayerActivity.onStop 调用:决定暂停或由后台载体继续播放。 */
fun onHidden(changingConfiguration: Boolean, inPip: Boolean = false) {
if (!changingConfiguration) visible = false
tracker.checkpoint()
checkpointHistory(engine.state.value, android.os.SystemClock.elapsedRealtime(), force = true)
// 投屏时本机引擎停在投屏起点,进度由 castObserver 回写,不能用旧位置覆盖。
if (remote.value == null) {
tracker.checkpoint()
checkpointHistory(engine.state.value, android.os.SystemClock.elapsedRealtime(), force = true)
}
if (changingConfiguration || remote.value != null) return
val playing = engine.state.value.playWhenReady
val continueInBackground = inPip || (playing && Build.VERSION.SDK_INT < 26)
@@ -171,6 +174,8 @@ class PlayerModel(application: Application) : AndroidViewModel(application) {
val d = playback?.originalDurationMs ?: state.durationMs?.plus(playback?.positionOffsetMs ?: 0)
viewModelScope.launch(Dispatchers.IO) {
runCatching { repo.recent.save(item.ref, if (d != null && d - p < 3_000) 0 else p, d) }
// 暂停/退出时的强制检查点立即落盘;日常 5 秒检查点由 RecentStore 合并写入。
if (force) runCatching { repo.recent.flush() }
}
}
fun absolutePosition() = engine.state.value.positionMs + (playback?.positionOffsetMs ?: 0)