feat: 本地媒体库体验优化与播放诊断/降级
媒体库:标题搜索、名称/时长/最近修改/大小排序、按文件夹过滤; 缩略图加入内存 + 磁盘持久化缓存,重扫或重启直接复用。 播放:会话结束汇总缓冲次数/时长/掉帧与卡顿率;解码失败自动切换 系统软解一次;自适应流持续卡顿限制 720p/1.5Mbps 一次;每 10 秒 采集进程 CPU、PSS、可用内存与设备温度。跨内核回退因无第二内核不实现。 同步更新 docs/app.md 与 docs/validation.md。
This commit is contained in:
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() }
|
||||
}
|
||||
+7
-4
@@ -4,7 +4,7 @@
|
||||
|
||||
## 使用
|
||||
|
||||
1. 首页「打开本地视频」调用系统文件选择器,支持多选;「播放链接」支持协议选择、请求头与 RTSP TCP。
|
||||
1. 首页「本地视频库」扫描机身存储与 U 盘中的视频,网格封面浏览,支持按标题搜索、按名称/时长/最近修改/大小排序、按文件夹过滤,点击直接播放;「打开本地视频」调用系统文件选择器,支持多选;「播放链接」支持协议选择、请求头与 RTSP TCP。
|
||||
2. 「来源」添加 WebDAV、SMB 或 Jellyfin,可先测试连接,再保存。WebDAV 地址示例 `https://nas.example/dav/`,SMB 示例 `smb://192.168.1.10/videos/`,Jellyfin 填服务根地址。反向代理的路径前缀应保留。
|
||||
3. 打开来源,浏览文件夹、筛选当前目录、加载下一页,点击视频播放,长按收藏。网盘通过其 WebDAV 接口或 OpenList 等网关接入;没有实现各商业网盘的独立登录 SDK。
|
||||
4. 播放页支持拖动、前后跳转、上一部/下一部、全屏、音轨、字幕、外部字幕、倍速、画面适配、Surface/Texture、硬软解策略。双击画面左右区域跳转 10 秒。
|
||||
@@ -16,6 +16,7 @@
|
||||
| 功能 | 实现 |
|
||||
| --- | --- |
|
||||
| 本地文件 | SAF 持久授权,多个视频组成当前进程的播放队列 |
|
||||
| 本地媒体库 | MediaStore 扫描机身与可插拔卷(U 盘),网格封面 + 标题搜索 + 排序 + 文件夹过滤;缩略图内存/磁盘缓存 |
|
||||
| 在线 | HTTP(S) 文件、HLS、DASH、SmoothStreaming、HTTP-FLV、RTMP、RTSP |
|
||||
| WebDAV | 匿名/Basic,来源根目录内浏览、同名字幕、带鉴权播放 |
|
||||
| SMB/NAS | SMB2/3 浏览与随机读取;不支持 SMB1 |
|
||||
@@ -23,7 +24,9 @@
|
||||
| 字幕 | 文本字幕状态进入平台无关接口,UI 显示文本;支持选择轨道和 SAF 外挂 SRT/VTT/ASS/SSA;不完整保留 ASS 特效或位图字幕 |
|
||||
| 续播 | 本机历史保存稳定来源身份,重新解析临时链接;Jellyfin 同步服务端进度 |
|
||||
| 缓存 | 普通文件按需缓存,256 MB LRU;不缓存自适应流,不提供完整离线下载 |
|
||||
| 解码 | 系统 MediaCodec 硬解/系统软件解码筛选;无 FFmpeg 通用视频软解,无跨内核回退 |
|
||||
| 解码 | 系统 MediaCodec 硬解/系统软件解码筛选;解码失败自动切换系统软解一次;无 FFmpeg 通用视频软解,无跨内核回退 |
|
||||
| 自适应与降级 | HLS/DASH 由内核自适应;持续卡顿时对自适应流限制 720p/1.5Mbps 一次 |
|
||||
| 诊断 | 会话结束汇总卡顿次数/时长与卡顿率、掉帧;每 10 秒采集进程 CPU、PSS、可用内存与设备温度(经日志埋点,不上传地址) |
|
||||
| DLNA | SSDP 发现、加载/暂停/播放/seek/停止,前台服务与媒体通知 |
|
||||
| Google Cast | Media3 CastPlayer + MediaSessionService,路由选择及回切 |
|
||||
|
||||
@@ -32,7 +35,7 @@ SRT/RIST、WebRTC、DRM、AirPlay、网盘专有认证和 Emby/Plex 等独立服
|
||||
## 所有权与生命周期
|
||||
|
||||
- `PlayerModel`(AndroidViewModel)持有内核、进度协调器和日志采集器;`PlayerActivity` 只持有渲染绑定与 UI。旋转或全屏只重绑输出,不重建播放内核。
|
||||
- 本机播放进入后台暂停,手动暂停后返回前台不自动播放;销毁 ViewModel 最终释放内核。进程重建从加密记录恢复当前条目,队列不跨进程保存。
|
||||
- 本机播放按 Home/切走时进入画中画继续播放(API 26+),API 23-25 改用前台媒体服务 + 通知栏续播;返回键或退出播放页、进入画中画失败时立即暂停,手动暂停后返回前台不自动播放;销毁 ViewModel 最终释放内核。进程重建从加密记录恢复当前条目,队列不跨进程保存。
|
||||
- DLNA 的设备会话、进度上报和 token 代理交给 `DlnaPlaybackService`,页面退出不会关闭代理。释放期间阻止开启新会话;系统杀进程后不伪造远端连接恢复。
|
||||
- Google Cast 资源由应用级持有器和媒体服务管理。接收端继续播放/停止、返回本机的路径由 Cast 会话驱动。
|
||||
- Jellyfin HLS 从转码起点重新计时,界面/历史使用原片绝对时间,服务端会话按适配层偏移换算。
|
||||
@@ -41,7 +44,7 @@ SRT/RIST、WebRTC、DRM、AirPlay、网盘专有认证和 Emby/Plex 等独立服
|
||||
|
||||
账户由 `library-storage` 使用 Android Keystore 加密。完整历史(含用户输入的 token URL、请求头、外部字幕 URI)也使用 AES-GCM 加密,不提供明文回退;页面 Intent 只传记录 ID。来源文件记录账户 ID、路径与版本,不持久化 Jellyfin 临时 URL。应用关闭备份/设备迁移,避免密文脱离设备密钥;设备密钥失效时需重新配置。
|
||||
|
||||
日志埋点不记录地址和凭证。缓存中媒体片段未单独加密,存放于应用私有缓存目录,可以清理或被系统回收。投屏 HTTP relay 使用随机 token,仍应使用受信任的家庭局域网。测试源脚本只绑定本机回环,用虚构账号,不适合生产部署。
|
||||
日志埋点不记录地址和凭证。缓存中媒体片段未单独加密,存放于应用私有缓存目录,可以清理或被系统回收。本地媒体缩略图缓存于应用私有缓存目录(video-thumbs),以 URI、修改时间与大小派生 key,文件变化会自动失效,可被系统回收。投屏 HTTP relay 使用随机 token,仍应使用受信任的家庭局域网。测试源脚本只绑定本机回环,用虚构账号,不适合生产部署。
|
||||
|
||||
## 构建与后续接入
|
||||
|
||||
|
||||
@@ -1,5 +1,28 @@
|
||||
# 验证与设备矩阵
|
||||
|
||||
## 当前版本:本地媒体库与画中画 / 后台续播(2026-12-01)
|
||||
|
||||
对应提交 `b638ec5`(功能)至 `e651b1c`(修复),界面迁移到 Jetpack Compose。
|
||||
|
||||
新增能力:
|
||||
|
||||
- 本地媒体库:MediaStore 扫描机身存储与可插拔卷(U 盘);API 29+ 用 `getExternalVolumeNames` 遍历多卷,23-28 回退主卷;结果排序后持久化,无权限时回退缓存。列表支持标题搜索、按名称/时长/最近修改/大小排序、按文件夹(`BUCKET_DISPLAY_NAME`)过滤。缩略图内存 LruCache + 私有目录磁盘缓存,key 由 URI、修改时间与大小派生,重扫或重启复用。
|
||||
- 画中画与后台续播:API 26+ 播放中按 Home 进入画中画继续播放;API 23-25 由 `LocalPlaybackService` 前台媒体服务 + MediaSession 通知栏续播,命令转发全局引擎,暂停或结束自动停止。返回键、退出播放页、进入画中画失败时立即暂停。
|
||||
- 字幕与音轨:Matroska 默认字幕未映射时自动选首条文本轨(用户关闭后不再自动开启);普通文件无视频轨 1.5 秒、READY 后 8 秒无首帧分别报 `NO_VIDEO_TRACK` / `NO_FIRST_FRAME`;音轨带 `supported/mimeType`,AC3/DTS passthrough 在无常规编码时自动避开并提示。
|
||||
- 卡顿与掉帧统计:Ended/换源/释放时汇总缓冲次数、缓冲时长、播放时长与掉帧数(`JankSummary`),telemetry 记录 `jankRate = bufferingMs / playbackMs`。
|
||||
- 运行中自动软解回退:解码类错误(初始化/解码/格式不支持/超出能力)时自动切换到 `SOFTWARE_ONLY` 一次,恢复进度与播放意图(`AutoFallback`)。
|
||||
- 清晰度降级:自适应流(HLS/DASH/SmoothStreaming)缓冲达 3 次或累计 8 秒时,限制到 720p / 1.5Mbps 一次(`QualityDegraded`),换源时清除上限。
|
||||
- 性能采集:`PerformanceSampler` 每 10 秒记录进程 CPU 占比、PSS 内存、系统可用内存与设备温度(thermal zone 最大值,回退电池温度),经 telemetry `perf` 记录。
|
||||
- 跨内核回退:当前仅 Media3 一个内核,无第二内核可回退,按边界不实现。
|
||||
|
||||
自动检查:`.\gradlew.bat :app:assembleDebug :app:testDebugUnitTest :app:lintDebug` 通过(0 error;D8 的 Kotlin 元数据提示为已知无害告警)。未在真机或模拟器执行界面、画中画或通知栏交互测试。
|
||||
|
||||
仍需真机验收(模拟器与静态检查不能代替):
|
||||
|
||||
- 画中画进入/退出与 Surface 显示、返回键暂停、低版本通知栏控制;
|
||||
- U 盘/多卷扫描与按文件夹过滤在不同 ROM 的 MediaStore 索引差异;
|
||||
- 缩略图缓存在系统回收缓存目录后的重建。
|
||||
|
||||
## 0.3.0 来源与投屏检查结果(2026-11-30)
|
||||
|
||||
- 完整 Demo 构建与 27 项测试通过,无失败、无跳过。
|
||||
|
||||
@@ -103,4 +103,10 @@ sealed interface PlaybackEvent {
|
||||
data class VideoSize(val width: Int, val height: Int, val pixelRatio: Float) : PlaybackEvent
|
||||
/** 相对 prepare 的耗时;使用单调时钟。 */
|
||||
data class StartupTime(val elapsedMs: Long) : PlaybackEvent
|
||||
/** 播放会话(Ended/换源/释放)结束时的卡顿与掉帧汇总。卡顿率 = bufferingMs / playbackMs。 */
|
||||
data class JankSummary(val bufferingCount: Int, val bufferingMs: Long, val playbackMs: Long, val droppedFrames: Int) : PlaybackEvent
|
||||
/** 解码失败后自动切换到系统软解,每个媒体只尝试一次。 */
|
||||
data class AutoFallback(val detail: String) : PlaybackEvent
|
||||
/** 自适应流因持续卡顿限制了清晰度上限。 */
|
||||
data class QualityDegraded(val maxHeight: Int) : PlaybackEvent
|
||||
}
|
||||
@@ -46,6 +46,16 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
private var cachedTracks: List<MediaTrack> = emptyList()
|
||||
private val decoderHardware = HashMap<String, Boolean?>()
|
||||
private var subtitlePolicyApplied = false
|
||||
private var autoSoftwareFallbackUsed = false
|
||||
private var qualityDegraded = false
|
||||
// 卡顿与掉帧累计(按会话,Ended/换源/释放时汇总)
|
||||
private var statsPlaybackMs = 0L
|
||||
private var statsBufferingMs = 0L
|
||||
private var statsBufferingCount = 0
|
||||
private var statsDroppedFrames = 0
|
||||
private var statsMarkAt = 0L
|
||||
private var statsLastPlaying = false
|
||||
private var statsLastBuffering = false
|
||||
private var player: ExoPlayer
|
||||
|
||||
private val listener = object : Player.Listener {
|
||||
@@ -65,9 +75,16 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
} else handler.removeCallbacks(noVideoCheck)
|
||||
}
|
||||
override fun onPlaybackStateChanged(playbackState: Int) {
|
||||
if (playbackState == Player.STATE_ENDED) emit(PlaybackEvent.Ended)
|
||||
if (playbackState == Player.STATE_ENDED) { emit(PlaybackEvent.Ended); snapshotStats()?.let { emit(it) } }
|
||||
}
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
// 解码失败:自动尝试一次系统软解,避免直接报错退出。每个媒体只回退一次。
|
||||
if (isDecodeError(error) && !autoSoftwareFallbackUsed && !released) {
|
||||
autoSoftwareFallbackUsed = true
|
||||
val code = error.errorCodeName
|
||||
handler.post { if (!released) fallbackToSoftware(code) }
|
||||
return
|
||||
}
|
||||
// 不透传内核 message/cause:其中可能包含带 token 的媒体地址。
|
||||
val message = when (error.errorCode) {
|
||||
PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, PlaybackException.ERROR_CODE_DECODING_FAILED,
|
||||
@@ -106,6 +123,7 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
decoder(TrackType.AUDIO, decoderName)
|
||||
}
|
||||
override fun onDroppedVideoFrames(eventTime: AnalyticsListener.EventTime, droppedFrames: Int, elapsedMs: Long) {
|
||||
statsDroppedFrames += droppedFrames
|
||||
emit(PlaybackEvent.DroppedFrames(droppedFrames, elapsedMs))
|
||||
}
|
||||
}
|
||||
@@ -158,11 +176,16 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
override suspend fun prepare(request: PlaybackRequest) = command {
|
||||
SourceRouting.validate(request, Media3TransportRegistry.schemes())?.let { return@command it }
|
||||
this.request = request.copy(headers = request.headers.toMap(), subtitles = request.subtitles.toList())
|
||||
autoSoftwareFallbackUsed = false
|
||||
qualityDegraded = false
|
||||
clearQualityCap()
|
||||
load(this.request!!)
|
||||
CommandResult.Accepted
|
||||
}
|
||||
|
||||
private fun load(request: PlaybackRequest) {
|
||||
snapshotStats()?.let { emit(it) }
|
||||
resetStats()
|
||||
subtitleLines = emptyList()
|
||||
lastError = null
|
||||
firstFrame = false
|
||||
@@ -209,11 +232,17 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
PlaybackValidation.policy(policy, capabilities)?.let { return@command it }
|
||||
if (this.policy == policy) return@command CommandResult.Accepted
|
||||
val saved = request?.copy(startPositionMs = player.currentPosition.coerceAtLeast(0), autoplay = player.playWhenReady)
|
||||
this.policy = policy
|
||||
rebuild(saved)
|
||||
CommandResult.Accepted
|
||||
}
|
||||
|
||||
/** 释放并按当前 policy 重建内核,恢复进度、意图、速度、音量、轨道与 Surface。 */
|
||||
private fun rebuild(saved: PlaybackRequest?) {
|
||||
val speed = player.playbackParameters.speed
|
||||
val playWhenReady = player.playWhenReady
|
||||
val volume = player.volume
|
||||
val tracks = player.trackSelectionParameters
|
||||
this.policy = policy
|
||||
player.removeListener(listener)
|
||||
player.removeAnalyticsListener(analytics)
|
||||
player.release()
|
||||
@@ -223,8 +252,15 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
player.playWhenReady = playWhenReady
|
||||
player.trackSelectionParameters = tracks
|
||||
surface?.takeIf { it.isValid }?.let { player.setVideoSurface(it) }
|
||||
saved?.let { load(it) }
|
||||
CommandResult.Accepted
|
||||
saved?.let { load(it.copy(autoplay = true)) }
|
||||
}
|
||||
|
||||
/** 解码失败后的单次自动软解回退。 */
|
||||
private fun fallbackToSoftware(code: String) {
|
||||
val saved = request?.copy(startPositionMs = player.currentPosition.coerceAtLeast(0), autoplay = true) ?: return
|
||||
policy = DecodePolicy(video = DecodeMode.SOFTWARE_ONLY, audio = policy.audio)
|
||||
emit(PlaybackEvent.AutoFallback("解码失败($code),已切换系统软解"))
|
||||
rebuild(saved)
|
||||
}
|
||||
|
||||
override fun attachSurface(surface: Surface): CommandResult {
|
||||
@@ -242,6 +278,7 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
// 清理不能因调用方 lifecycleScope 取消而被跳过。
|
||||
override suspend fun release() = withContext(Dispatchers.Main.immediate + kotlinx.coroutines.NonCancellable) {
|
||||
if (!released) {
|
||||
snapshotStats()?.let { emit(it) }
|
||||
released = true
|
||||
handler.removeCallbacks(ticker)
|
||||
handler.removeCallbacks(firstFrameTimeout)
|
||||
@@ -337,8 +374,77 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun isAdaptive(): Boolean = request?.let {
|
||||
SourceRouting.resolve(it) in setOf(MediaSourceType.HLS, MediaSourceType.DASH, MediaSourceType.SMOOTH_STREAMING)
|
||||
} == true
|
||||
|
||||
private fun isDecodeError(error: PlaybackException) = error.errorCode in setOf(
|
||||
PlaybackException.ERROR_CODE_DECODER_INIT_FAILED,
|
||||
PlaybackException.ERROR_CODE_DECODING_FAILED,
|
||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED,
|
||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
|
||||
)
|
||||
|
||||
/** 累计播放/缓冲时长,进入缓冲时计数;自适应流持续卡顿时限制清晰度上限。 */
|
||||
private fun updateStats() {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (statsMarkAt != 0L) {
|
||||
val dt = now - statsMarkAt
|
||||
if (dt > 0) {
|
||||
if (statsLastPlaying) statsPlaybackMs += dt
|
||||
if (statsLastBuffering) statsBufferingMs += dt
|
||||
}
|
||||
}
|
||||
statsMarkAt = now
|
||||
val buffering = firstFrame && player.playbackState == Player.STATE_BUFFERING
|
||||
if (buffering && !statsLastBuffering) { statsBufferingCount++; maybeDegradeQuality() }
|
||||
statsLastBuffering = buffering
|
||||
statsLastPlaying = player.isPlaying
|
||||
}
|
||||
|
||||
/** 缓冲次数或时长达到阈值时,对自适应流限制到 720p/1.5Mbps,仅一次。 */
|
||||
private fun maybeDegradeQuality() {
|
||||
if (qualityDegraded || !isAdaptive() || !firstFrame || lastError != null) return
|
||||
if (statsBufferingCount < 3 && statsBufferingMs < 8_000) return
|
||||
qualityDegraded = true
|
||||
player.trackSelectionParameters = player.trackSelectionParameters.buildUpon()
|
||||
.setMaxVideoSize(Int.MAX_VALUE, 720)
|
||||
.setMaxVideoBitrate(1_500_000)
|
||||
.build()
|
||||
emit(PlaybackEvent.QualityDegraded(720))
|
||||
}
|
||||
|
||||
/** 换源前清除上一条媒体可能残留的清晰度上限。 */
|
||||
private fun clearQualityCap() {
|
||||
player.trackSelectionParameters = player.trackSelectionParameters.buildUpon()
|
||||
.setMaxVideoSize(Int.MAX_VALUE, Int.MAX_VALUE)
|
||||
.setMaxVideoBitrate(Int.MAX_VALUE)
|
||||
.build()
|
||||
}
|
||||
|
||||
/** 汇总当前会话并推进计时;无有效数据时返回 null。 */
|
||||
private fun snapshotStats(): PlaybackEvent.JankSummary? {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (statsMarkAt != 0L) {
|
||||
val dt = now - statsMarkAt
|
||||
if (dt > 0) {
|
||||
if (statsLastPlaying) statsPlaybackMs += dt
|
||||
if (statsLastBuffering) statsBufferingMs += dt
|
||||
}
|
||||
}
|
||||
statsMarkAt = now
|
||||
if (statsPlaybackMs == 0L && statsBufferingMs == 0L && statsBufferingCount == 0 && statsDroppedFrames == 0) return null
|
||||
return PlaybackEvent.JankSummary(statsBufferingCount, statsBufferingMs, statsPlaybackMs, statsDroppedFrames)
|
||||
}
|
||||
|
||||
private fun resetStats() {
|
||||
statsPlaybackMs = 0; statsBufferingMs = 0; statsBufferingCount = 0; statsDroppedFrames = 0
|
||||
statsLastPlaying = false; statsLastBuffering = false; statsMarkAt = SystemClock.elapsedRealtime()
|
||||
}
|
||||
|
||||
private fun publish() {
|
||||
if (released) return
|
||||
updateStats()
|
||||
val phase = if (lastError != null) PlaybackPhase.ERROR else when (player.playbackState) {
|
||||
Player.STATE_BUFFERING -> if (!firstFrame) PlaybackPhase.PREPARING else PlaybackPhase.BUFFERING
|
||||
Player.STATE_READY -> PlaybackPhase.READY
|
||||
|
||||
@@ -33,6 +33,16 @@ class PlaybackTelemetry(
|
||||
is PlaybackEvent.DroppedFrames -> record("dropped_frames", mapOf("count" to "${event.count}", "elapsedMs" to "${event.elapsedMs}"))
|
||||
is PlaybackEvent.StartupTime -> record("startup", mapOf("elapsedMs" to "${event.elapsedMs}"))
|
||||
is PlaybackEvent.VideoSize -> record("video_size", mapOf("width" to "${event.width}", "height" to "${event.height}"))
|
||||
is PlaybackEvent.JankSummary -> record("jank", mapOf(
|
||||
"bufferingCount" to "${event.bufferingCount}",
|
||||
"bufferingMs" to "${event.bufferingMs}",
|
||||
"playbackMs" to "${event.playbackMs}",
|
||||
"droppedFrames" to "${event.droppedFrames}",
|
||||
// 卡顿率:缓冲时长占播放时长的百分比;无播放时长时为 0
|
||||
"jankRate" to (if (event.playbackMs > 0) "%.3f".format(event.bufferingMs.toDouble() / event.playbackMs) else "0"),
|
||||
))
|
||||
is PlaybackEvent.AutoFallback -> record("auto_fallback", mapOf("detail" to event.detail))
|
||||
is PlaybackEvent.QualityDegraded -> record("quality_degraded", mapOf("maxHeight" to "${event.maxHeight}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user