feat: 本地媒体库体验优化与播放诊断/降级

媒体库:标题搜索、名称/时长/最近修改/大小排序、按文件夹过滤;
缩略图加入内存 + 磁盘持久化缓存,重扫或重启直接复用。

播放:会话结束汇总缓冲次数/时长/掉帧与卡顿率;解码失败自动切换
系统软解一次;自适应流持续卡顿限制 720p/1.5Mbps 一次;每 10 秒
采集进程 CPU、PSS、可用内存与设备温度。跨内核回退因无第二内核不实现。

同步更新 docs/app.md 与 docs/validation.md。
This commit is contained in:
tongtong committed 2026-12-01 20:01:02 +08:00
1 parent e651b1c4b4
commit 71a5d5f72e
10 files changed
+366 -22

No files matched your search

@@ -19,14 +19,19 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -36,6 +41,8 @@ import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
class LocalLibraryActivity : AppCompatActivity() {
private enum class SortMode(val label: String) { NAME("名称"), DURATION("时长"), MODIFIED("最近"), SIZE("大小") }
private lateinit var store: LocalMediaStore
private val videos = mutableStateOf<List<LocalVideo>>(emptyList())
private val loading = mutableStateOf(false)
@@ -91,6 +98,23 @@ class LocalLibraryActivity : AppCompatActivity() {
val granted = permissionGranted.value
val isLoading = loading.value
val gate = remember { Semaphore(4) }
var query by rememberSaveable { mutableStateOf("") }
var sortName by rememberSaveable { mutableStateOf(SortMode.NAME.name) }
var folderFilter by rememberSaveable { mutableStateOf<String?>(null) }
var dialog by remember { mutableStateOf<String?>(null) }
val sort = SortMode.valueOf(sortName)
val folders = remember(list) { list.map { it.folder }.distinct().sorted() }
val visible = remember(list, query, sort, folderFilter) {
list.asSequence()
.filter { (query.isBlank() || it.title.contains(query, ignoreCase = true)) && (folderFilter == null || it.folder == folderFilter) }
.toList()
.sortedWith(when (sort) {
SortMode.NAME -> compareBy { it.title.lowercase() }
SortMode.DURATION -> compareByDescending { it.durationMs }
SortMode.MODIFIED -> compareByDescending { it.dateModified }
SortMode.SIZE -> compareByDescending { it.size }
})
}
Column(Modifier.fillMaxSize().background(AppBg).windowInsetsPadding(WindowInsets.systemBars)) {
TopBar("本地视频", onBack = { finish() }, actions = {
TextButton(onClick = { reload() }) { Text("刷新", color = AppAccent) }
@@ -103,7 +127,7 @@ class LocalLibraryActivity : AppCompatActivity() {
}
if (list.isEmpty()) {
if (isLoading) {
Box(Modifier.fillMaxSize(), contentAlignment = androidx.compose.ui.Alignment.Center) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text("正在扫描设备与 U 盘…", color = AppMuted)
}
} else {
@@ -111,13 +135,37 @@ class LocalLibraryActivity : AppCompatActivity() {
}
return@Column
}
// 搜索 / 排序 / 文件夹过滤
Row(
Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
OutlinedTextField(
value = query,
onValueChange = { query = it },
singleLine = true,
placeholder = { Text("搜索影片", color = AppMuted) },
textStyle = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = AppAccent, unfocusedBorderColor = AppRaised,
focusedTextColor = AppInk, unfocusedTextColor = AppInk, cursorColor = AppAccent,
),
)
TextButton(onClick = { dialog = "sort" }) { Text(sort.label, color = AppAccent) }
TextButton(onClick = { dialog = "folder" }) { Text(folderFilter ?: "全部", color = AppAccent) }
}
Text(
"共 ${list.size} 部影片",
if (visible.size == list.size) "共 ${list.size} 部影片" else "共 ${list.size} 部 · 匹配 ${visible.size} 部",
style = MaterialTheme.typography.labelSmall,
color = AppMuted,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
)
if (isLoading) LinearProgressIndicator(modifier = Modifier.fillMaxWidth(), color = AppAccent, trackColor = AppPanel)
if (visible.isEmpty()) {
EmptyState("没有匹配的影片", "换个关键词或清除文件夹筛选。")
return@Column
}
val columns = if (LocalConfiguration.current.screenWidthDp >= 720) 5 else 3
LazyVerticalGrid(
columns = GridCells.Fixed(columns),
@@ -126,16 +174,27 @@ class LocalLibraryActivity : AppCompatActivity() {
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
items(list, key = { it.uri }) { item -> LocalVideoCard(item, gate) }
items(visible, key = { it.uri }) { item -> LocalVideoCard(item, gate) }
}
when (dialog) {
"sort" -> ChoiceDialog("排序方式", SortMode.entries.map { it.label }, { dialog = null }) { i ->
sortName = SortMode.entries[i].name; dialog = null
}
"folder" -> ChoiceDialog("按文件夹筛选", listOf("全部") + folders, { dialog = null }) { i ->
folderFilter = if (i == 0) null else folders[i - 1]; dialog = null
}
}
}
}
@Composable
private fun LocalVideoCard(item: LocalVideo, gate: Semaphore) {
val thumb by produceState<Bitmap?>(initialValue = null, item.uri) {
val context = LocalContext.current
val thumb by produceState<Bitmap?>(initialValue = null, "${item.uri}|${item.dateModified}|${item.size}") {
value = withContext(Dispatchers.IO) {
gate.withPermit { runCatching { loadThumbnail(item) }.getOrNull() }
gate.withPermit {
ThumbCache.get(context, item) ?: runCatching { loadThumbnail(item) }.getOrNull()?.also { ThumbCache.put(context, item, it) }
}
}
}
Column(
@@ -170,7 +229,7 @@ class LocalLibraryActivity : AppCompatActivity() {
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 6.dp),
)
Text(formatTime(item.durationMs), fontSize = 11.sp, color = AppMuted)
Text("${item.folder} · ${formatTime(item.durationMs)}", fontSize = 11.sp, color = AppMuted)
}
}
@@ -185,4 +244,4 @@ class LocalLibraryActivity : AppCompatActivity() {
}
}.getOrNull()
}
}
}
@@ -17,6 +17,7 @@ data class LocalVideo(
val size: Long,
val volumeName: String, // 内部卷名,区分机身/U盘
val dateModified: Long,
val folder: String = "其他", // 文件夹(BUCKET_DISPLAY_NAME),用于分组过滤
)
/** 本地媒体库:扫描 MediaStore(机身 + U 盘可插拔卷)+ JSON 缓存。
@@ -64,6 +65,7 @@ class LocalMediaStore(context: Context) {
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATE_MODIFIED,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
),
"${MediaStore.Video.Media.SIZE} > 0",
null, null,
@@ -74,13 +76,15 @@ class LocalMediaStore(context: Context) {
val durCol = c.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)
val sizeCol = c.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)
val modCol = c.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED)
val folderCol = c.getColumnIndex(MediaStore.Video.Media.BUCKET_DISPLAY_NAME)
val out = mutableListOf<LocalVideo>()
while (c.moveToNext()) {
val name = c.getString(nameCol)
if (name.isNullOrBlank()) continue
val uri = Uri.withAppendedPath(collection, c.getLong(idCol).toString()).toString()
val folder = (if (folderCol >= 0) c.getString(folderCol) else null).takeUnless { it.isNullOrBlank() } ?: "其他"
out += LocalVideo(uri, name, c.getLong(durCol).coerceAtLeast(0), c.getLong(sizeCol),
volume, c.getLong(modCol) * 1000) // DATE_MODIFIED 为秒
volume, c.getLong(modCol) * 1000, folder) // DATE_MODIFIED 为秒
}
out
}
@@ -89,7 +93,8 @@ class LocalMediaStore(context: Context) {
@Synchronized private fun save(items: List<LocalVideo>) {
val array = JSONArray(); for (item in items) {
array.put(org.json.JSONObject().put("u", item.uri).put("t", item.title)
.put("d", item.durationMs).put("s", item.size).put("v", item.volumeName).put("m", item.dateModified))
.put("d", item.durationMs).put("s", item.size).put("v", item.volumeName)
.put("m", item.dateModified).put("f", item.folder))
}
appContext.getSharedPreferences("local-media-cache", Context.MODE_PRIVATE).edit()
.putString("items", array.toString()).apply()
@@ -101,7 +106,8 @@ class LocalMediaStore(context: Context) {
val array = JSONArray(raw)
(0 until array.length()).map { index ->
val o = array.getJSONObject(index)
LocalVideo(o.getString("u"), o.getString("t"), o.getLong("d"), o.getLong("s"), o.optString("v", ""), o.getLong("m"))
LocalVideo(o.getString("u"), o.getString("t"), o.getLong("d"), o.getLong("s"),
o.optString("v", ""), o.getLong("m"), o.optString("f", "其他").ifBlank { "其他" })
}
}.getOrDefault(emptyList())
}
@@ -0,0 +1,77 @@
package com.ttstd.player.app
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Debug
import kotlinx.coroutines.*
/** 周期采集进程 CPU 占用、PSS 内存与设备温度,经 TelemetrySink 记录。
* 只采集数值,不含媒体地址或凭证;读取系统文件失败时跳过该项,不影响播放。
*/
class PerformanceSampler(
context: Context,
private val scope: CoroutineScope,
private val record: (String, Map<String, String>) -> Unit,
) : AutoCloseable {
private val appContext = context.applicationContext
private val activityManager = appContext.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
private var lastCpuMs = 0L
private var lastWallMs = 0L
private var job: Job? = null
fun start(intervalMs: Long = 10_000) {
if (job != null) return
lastCpuMs = runCatching { android.os.Process.getElapsedCpuTime() }.getOrDefault(0)
lastWallMs = System.currentTimeMillis()
job = scope.launch(Dispatchers.IO) {
while (isActive) {
delay(intervalMs)
sample()
}
}
}
private fun sample() {
val attrs = HashMap<String, String>()
runCatching {
val cpuMs = android.os.Process.getElapsedCpuTime()
val wallMs = System.currentTimeMillis()
val dCpu = (cpuMs - lastCpuMs).coerceAtLeast(0)
val dWall = (wallMs - lastWallMs).coerceAtLeast(1)
lastCpuMs = cpuMs; lastWallMs = wallMs
attrs["cpuPct"] = "%.0f".format(dCpu * 100.0 / dWall)
}
runCatching {
val info = Debug.MemoryInfo()
Debug.getMemoryInfo(info)
attrs["pssMb"] = "%.1f".format(info.totalPss / 1024.0)
}
runCatching {
activityManager?.let { am ->
val mi = ActivityManager.MemoryInfo(); am.getMemoryInfo(mi)
attrs["availMb"] = "%.0f".format(mi.availMem / (1024.0 * 1024))
}
}
runCatching { deviceTempC()?.let { attrs["tempC"] = "%.1f".format(it) } }
if (attrs.isNotEmpty()) runCatching { record("perf", attrs) }
}
/** 优先 thermal zone 最大值,读不到回退电池温度。 */
private fun deviceTempC(): Double? {
val zones = java.io.File("/sys/class/thermal").listFiles { _, name -> name.startsWith("thermal_zone") }
var maxMilli = Long.MIN_VALUE
if (zones != null) for (zone in zones) {
val value = runCatching { java.io.File(zone, "temp").readText().trim().toLong() }.getOrNull() ?: continue
if (value > maxMilli) maxMilli = value
}
if (maxMilli != Long.MIN_VALUE) return maxMilli / 1000.0
val intent = appContext.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) ?: return null
val tenths = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Int.MIN_VALUE)
return if (tenths != Int.MIN_VALUE) tenths / 10.0 else null
}
override fun close() { job?.cancel(); job = null }
}
@@ -38,8 +38,9 @@ class PlayerModel(application: Application) : AndroidViewModel(application) {
val engine = Media3Engine(application)
private val repo = AppRepository(application)
private val tracker = LibraryPlaybackTracker(application, engine, viewModelScope)
private val telemetry = PlaybackTelemetry(engine, viewModelScope, java.util.UUID.randomUUID().toString(),
TelemetrySink { name, attributes -> android.util.Log.d("TTVideoPlayer", "$name $attributes") })
private val sink = TelemetrySink { name, attributes -> android.util.Log.d("TTVideoPlayer", "$name $attributes") }
private val telemetry = PlaybackTelemetry(engine, viewModelScope, java.util.UUID.randomUUID().toString(), sink)
private val perf = PerformanceSampler(application, viewModelScope, sink::record).also { it.start() }
val current = MutableStateFlow<RecentMedia?>(null)
val error = MutableStateFlow<String?>(null)
val notices = MutableSharedFlow<String>(extraBufferCapacity = 16)
@@ -56,7 +57,12 @@ class PlayerModel(application: Application) : AndroidViewModel(application) {
AppPlaybackRuntime.acquireLocal()
AppPlaybackRuntime.engine = engine
viewModelScope.launch { engine.events.collect { event ->
if (event is PlaybackEvent.VideoSize && event.height > 0) videoRatio.value = event.width * event.pixelRatio / event.height
when (event) {
is PlaybackEvent.VideoSize -> if (event.height > 0) videoRatio.value = event.width * event.pixelRatio / event.height
is PlaybackEvent.AutoFallback -> notices.tryEmit(event.detail)
is PlaybackEvent.QualityDegraded -> notices.tryEmit("网络卡顿,清晰度已限制为 ${event.maxHeight}p")
else -> Unit
}
} }
viewModelScope.launch { current.collect { AppPlaybackRuntime.currentTitle = it?.ref?.title.orEmpty() } }
viewModelScope.launch { engine.state.collect { state ->
@@ -244,7 +250,7 @@ class PlayerModel(application: Application) : AndroidViewModel(application) {
}
}
override fun onCleared() {
tracker.close(); telemetry.close(); AppPlaybackRuntime.releaseLocal()
tracker.close(); telemetry.close(); perf.close(); AppPlaybackRuntime.releaseLocal()
AppPlaybackRuntime.engine = null; AppPlaybackRuntime.currentTitle = ""
CoroutineScope(Dispatchers.Main.immediate).launch { engine.release() }
super.onCleared()
@@ -0,0 +1,48 @@
package com.ttstd.player.app
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.LruCache
import java.io.File
import java.security.MessageDigest
/** 缩略图缓存:内存 LruCache + 磁盘 JPEG,key 由 uri+修改时间+大小派生。
* 重扫或进程重启后直接复用,不必重新向 MediaStore 请求缩略图;文件变化会自动换 key。
* 仅存应用私有缓存目录,可被系统回收。
*/
object ThumbCache {
private const val DIR = "video-thumbs"
private const val MAX_BYTES = 16L * 1024 * 1024 // 内存:约 16 MB
private val memory = object : LruCache<String, Bitmap>(MAX_BYTES.toInt()) {
override fun sizeOf(key: String, value: Bitmap) = value.byteCount
}
private fun key(item: LocalVideo): String {
val digest = MessageDigest.getInstance("SHA-256")
.digest("${item.uri}|${item.dateModified}|${item.size}".toByteArray())
return digest.joinToString("") { "%02x".format(it) }
}
@Synchronized fun get(context: Context, item: LocalVideo): Bitmap? {
val key = key(item)
memory.get(key)?.let { return it }
val file = File(dir(context), "$key.jpg")
if (!file.isFile) return null
val bitmap = runCatching { BitmapFactory.decodeFile(file.path) }.getOrNull() ?: return null
memory.put(key, bitmap)
return bitmap
}
@Synchronized fun put(context: Context, item: LocalVideo, bitmap: Bitmap) {
val key = key(item)
memory.put(key, bitmap)
runCatching {
val file = File(dir(context), "$key.jpg")
if (!file.isFile) file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, 80, it) }
}
}
private fun dir(context: Context): File = File(context.applicationContext.cacheDir, DIR).apply { mkdirs() }
}