初始化 TTVideoPlayer 工程:模块化播放框架、同同影音 App 与文档

Media3 内核播放框架(player-api/core/media3/source/render/lifecycle/telemetry)、
WebDAV/SMB/Jellyfin 来源、DLNA/Google Cast 投屏、RTMP 原生库与完整 App。
This commit is contained in:
tongtong committed 2026-11-30 18:13:40 +08:00
commit 922ec80bcc
147 files changed
+20169

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
plugins {
id("com.android.application")
kotlin("android")
}
android {
namespace = "com.ttstd.player.app"
compileSdk = 37
testOptions { unitTests.isIncludeAndroidResources = true }
defaultConfig {
minSdk = 23
targetSdk = 37
applicationId = "com.ttstd.player.demo"
versionCode = 4
versionName = "1.0.0"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
kotlin { jvmToolchain(17) }
dependencies {
implementation("androidx.appcompat:appcompat:1.7.1")
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.1")
implementation("androidx.core:core-ktx:1.16.0")
testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.14.1")
implementation(project(":library-api"))
implementation(project(":library-webdav"))
implementation(project(":library-smb"))
implementation(project(":library-jellyfin"))
implementation(project(":library-storage"))
implementation(project(":library-media3"))
implementation(project(":player-media3-source"))
implementation(project(":player-cast-api"))
implementation(project(":player-cast-dlna"))
implementation(project(":player-cast-relay"))
implementation(project(":player-cast-google"))
implementation(project(":player-core"))
implementation(project(":player-media3"))
implementation(project(":player-render-android"))
implementation(project(":player-lifecycle"))
implementation(project(":player-telemetry"))
}
+16
View File
@@ -0,0 +1,16 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<application android:name=".VideoApplication" android:label="@string/app_name" android:icon="@drawable/ic_app"
android:theme="@style/Theme.TTVideo" android:allowBackup="false" android:fullBackupContent="false"
android:dataExtractionRules="@xml/data_extraction_rules" android:usesCleartextTraffic="true" android:supportsRtl="true">
<activity android:name=".HomeActivity" android:exported="true">
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
<intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="video/*" /></intent-filter>
</activity>
<activity android:name=".BrowserActivity" android:exported="false" />
<activity android:name=".PlayerActivity" android:exported="false" android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout" />
<service android:name=".DlnaPlaybackService" android:exported="false" android:foregroundServiceType="mediaPlayback" />
</application>
</manifest>
@@ -0,0 +1,156 @@
package com.ttstd.player.app
import android.app.Application
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import com.ttstd.player.api.*
import com.ttstd.player.library.*
import com.ttstd.player.library.jellyfin.JellyfinLibrary
import com.ttstd.player.library.media3.SmbSourceInstaller
import com.ttstd.player.library.smb.SmbLibrary
import com.ttstd.player.library.storage.LibraryAccounts
import com.ttstd.player.library.webdav.WebDavLibrary
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.security.KeyStore
import javax.crypto.*
import javax.crypto.spec.GCMParameterSpec
/** 可持久化媒体身份。来源文件只保存账户 ID/条目,不保存短效播放链接。 */
data class MediaRef(
val title: String,
val accountId: String? = null,
val entry: LibraryEntry? = null,
val uri: String? = null,
val headers: Map<String, String> = emptyMap(),
val sourceType: MediaSourceType = MediaSourceType.AUTO,
val network: NetworkOptions = NetworkOptions(),
val extraSubtitles: List<ExternalSubtitle> = emptyList(),
) {
val id: String get() = java.security.MessageDigest.getInstance("SHA-256")
.digest((accountId?.let { "$it:${entry?.id}" } ?: uri.orEmpty()).toByteArray())
.joinToString("") { "%02x".format(it) }
override fun toString() = "MediaRef(id=$id, uri=REDACTED)"
}
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 加密,不做明文回退。 */
class RecentStore(context: Context) {
private val prefs = context.getSharedPreferences("app-recent-media", Context.MODE_PRIVATE)
private fun key(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey("tt-video-history-v1", null) as? SecretKey)?.let { 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()
}
@Synchronized fun all(): 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 }
}
@Synchronized fun find(id: String): RecentMedia? = all().firstOrNull { it.ref.id == id }
@Synchronized fun save(ref: MediaRef, position: Long, duration: Long?): RecentMedia {
val entries = all()
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))
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>) {
val array = JSONArray(); items.forEach { array.put(encode(it)) }
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()
}
companion object {
/** JSON 编解码独立于 Keystore,便于验证迁移与不丢失来源身份。 */
fun encode(item: RecentMedia): JSONObject {
val r = item.ref
val headers = JSONObject(); r.headers.forEach { (k, v) -> headers.put(k, v) }
val subtitles = JSONArray(); r.extraSubtitles.forEach { subtitles.put(JSONObject().put("uri", it.uri).put("mime", it.mimeType).put("language", it.language).put("default", it.isDefault)) }
return JSONObject().put("title", r.title).put("account", r.accountId).put("uri", r.uri)
.put("entry", r.entry?.let { JSONObject().put("id", it.id).put("name", it.name).put("size", it.size).put("version", it.version).put("resume", it.resumeMs) })
.put("headers", headers).put("type", r.sourceType.name).put("tcp", r.network.rtspTransport.name)
.put("connectTimeout", r.network.connectTimeoutMs).put("readTimeout", r.network.readTimeoutMs).put("rtspTimeout", r.network.rtspTimeoutMs)
.put("subtitles", subtitles).put("position", item.positionMs).put("duration", item.durationMs)
.put("updated", item.updatedAt).put("favorite", item.favorite)
}
fun decode(json: JSONObject): RecentMedia {
val entry = json.optJSONObject("entry")?.let { LibraryEntry(it.getString("id"), it.getString("name"), false,
it.optLong("size").takeIf { size -> size > 0 }, it.optString("version"), it.optLong("resume")) }
val headers = json.optJSONObject("headers") ?: JSONObject()
val map = headers.keys().asSequence().associateWith { headers.getString(it) }
val subtitles = json.optJSONArray("subtitles") ?: JSONArray()
val ref = MediaRef(json.getString("title"), json.optString("account").takeUnless { it.isBlank() || it == "null" }, entry,
json.optString("uri").takeUnless { it.isBlank() || it == "null" }, map,
runCatching { MediaSourceType.valueOf(json.optString("type")) }.getOrDefault(MediaSourceType.AUTO),
NetworkOptions(json.optInt("connectTimeout", 8000), json.optInt("readTimeout", 8000), json.optLong("rtspTimeout", 8000),
runCatching { RtspTransport.valueOf(json.optString("tcp")) }.getOrDefault(RtspTransport.AUTO)),
(0 until subtitles.length()).map { subtitles.getJSONObject(it).let { s -> ExternalSubtitle(s.getString("uri"), s.getString("mime"),
s.optString("language").takeUnless { it.isBlank() || it == "null" }, s.optBoolean("default")) } })
return RecentMedia(ref, json.optLong("position"), json.optLong("duration").takeIf { it > 0 }, json.optLong("updated"), json.optBoolean("favorite"))
}
}
}
class AppPreferences(context: Context) {
private val prefs = context.getSharedPreferences("app-preferences", Context.MODE_PRIVATE)
var decoder: DecodeMode
get() = runCatching { DecodeMode.valueOf(prefs.getString("decoder", "AUTO")!!) }.getOrDefault(DecodeMode.AUTO)
set(value) { prefs.edit().putString("decoder", value.name).apply() }
var texture: Boolean
get() = prefs.getBoolean("texture", false)
set(value) { prefs.edit().putBoolean("texture", value).apply() }
var autoSubtitle: Boolean
get() = prefs.getBoolean("subtitle", true)
set(value) { prefs.edit().putBoolean("subtitle", value).apply() }
}
class VideoApplication : Application() {
override fun onCreate() {
super.onCreate()
androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES)
SmbSourceInstaller.install { id -> LibraryAccounts(this).all().firstOrNull { it.id == id } }
}
}
/** 页面只传加密记录 ID;账户和播放请求不经可导出的 Intent 传递。 */
class AppRepository(private val context: Context) {
val accounts = LibraryAccounts(context.applicationContext)
val recent = sharedRecent(context.applicationContext)
val preferences = AppPreferences(context.applicationContext)
fun library(account: LibraryAccount): MediaLibrary = when (account.kind) {
LibraryKind.WEBDAV -> WebDavLibrary(account)
LibraryKind.SMB -> SmbLibrary(account)
LibraryKind.JELLYFIN -> JellyfinLibrary(account)
}
suspend fun resolve(ref: MediaRef, position: Long): LibraryPlayback = withContext(Dispatchers.IO) {
val playback = if (ref.accountId != null) {
val account = accounts.all().firstOrNull { it.id == ref.accountId } ?: throw LibraryException("来源已删除,请重新添加")
library(account).resolve(ref.entry ?: throw LibraryException("文件信息已失效"), LibraryPlaybackOptions(startPositionMs = position))
} else LibraryPlayback(PlaybackRequest(ref.uri ?: throw LibraryException("地址不存在"), ref.headers, position, true,
sourceType = ref.sourceType, network = ref.network, cacheKey = "app:${ref.id}".takeIf { ref.sourceType !in setOf(MediaSourceType.RTSP, MediaSourceType.RTMP) }),
"app:${ref.id}", ref.title)
val allSubtitles = playback.request.subtitles + ref.extraSubtitles
val selected = if (ref.extraSubtitles.isNotEmpty()) playback.request.subtitles.size else if (preferences.autoSubtitle) 0 else -1
playback.copy(request = playback.request.copy(subtitles = allSubtitles.mapIndexed { index, subtitle ->
subtitle.copy(isDefault = index == selected)
}))
}
companion object {
private var recentStore: RecentStore? = null
@Synchronized private fun sharedRecent(context: Context): RecentStore = recentStore ?: RecentStore(context).also { recentStore = it }
}
}
@@ -0,0 +1,149 @@
package com.ttstd.player.app
import android.app.AlertDialog
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import com.ttstd.player.library.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import com.ttstd.player.app.Ui.dp
class BrowserModel(application: Application) : AndroidViewModel(application) {
private val repo = AppRepository(application)
var account: LibraryAccount? = null; private set
private var library: MediaLibrary? = null
val entries = MutableStateFlow<List<LibraryEntry>>(emptyList())
val message = MutableStateFlow("")
val busy = MutableStateFlow(false)
var more: Int? = null; private set
val folders = mutableListOf<Pair<String, String>>()
private var job: Job? = null
fun open(id: String) {
if (account?.id == id) return
job = viewModelScope.launch {
try {
val selected = withContext(Dispatchers.IO) { repo.accounts.all().firstOrNull { it.id == id } }
?: throw LibraryException("来源已删除")
account = selected; library = repo.library(selected); folders.clear(); folders += "" to selected.name
load()
} catch (e: Exception) { message.value = SourceDialogs.safeError(e) }
}
}
fun enter(entry: LibraryEntry) { folders += entry.id to entry.name; load() }
fun up(): Boolean = if (folders.size > 1) { folders.removeAt(folders.lastIndex); load(); true } else false
fun load(offset: Int = 0) {
job?.cancel()
val source = library ?: return
val folder = folders.lastOrNull()?.first.orEmpty()
job = viewModelScope.launch {
busy.value = true; message.value = "正在连接来源…"
try {
val page = source.list(folder, offset)
entries.value = (if (offset == 0) page.entries else entries.value + page.entries).distinctBy { it.id }
more = page.nextOffset
message.value = "${entries.value.size} 个条目"
} catch (cancelled: CancellationException) { throw cancelled }
catch (e: Exception) { message.value = SourceDialogs.safeError(e) }
finally { busy.value = false }
}
}
}
/** 目录浏览保留在 ViewModel 中,转屏不会重新登录、丢失路径或重复发起网络请求。 */
class BrowserActivity : AppCompatActivity() {
private lateinit var model: BrowserModel
private val repo by lazy { AppRepository(applicationContext) }
private lateinit var title: TextView
private lateinit var status: TextView
private lateinit var list: ListView
private lateinit var more: TextView
private lateinit var search: EditText
private var visible = emptyList<LibraryEntry>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = ViewModelProvider(this)[BrowserModel::class.java]
val root = Ui.column(this)
Ui.inset(this, root)
val toolbar = LinearLayout(this).apply { setPadding(dp(16), dp(12), dp(16), dp(8)); gravity = android.view.Gravity.CENTER_VERTICAL }
toolbar.addView(Ui.button(this, "‹") { goBack() })
title = Ui.label(this, "媒体浏览", 22f, bold = true)
toolbar.addView(title, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12) })
toolbar.addView(Ui.button(this, "刷新") { model.load() })
root.addView(toolbar)
search = EditText(this).apply {
hint = "筛选当前目录"; setTextColor(Ui.ink); setHintTextColor(Ui.muted); setSingleLine(true)
setPadding(dp(20), 0, dp(20), 0)
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { render() }
override fun afterTextChanged(s: Editable?) = Unit
})
}
root.addView(search, LinearLayout.LayoutParams(-1, dp(52)))
status = Ui.label(this, "", 13f, Ui.muted).apply { setPadding(dp(20), dp(8), dp(20), dp(8)) }
root.addView(status)
list = ListView(this).apply { divider = null; clipToPadding = false; setPadding(dp(16), dp(4), dp(16), dp(12)) }
root.addView(list, LinearLayout.LayoutParams(-1, 0, 1f))
more = Ui.button(this, "加载更多") { model.more?.let(model::load) }
root.addView(more, LinearLayout.LayoutParams(-1, -2).apply { setMargins(dp(16), dp(4), dp(16), dp(12)) })
setContentView(root)
list.setOnItemClickListener { _, _, position, _ ->
val entry = visible[position]
if (entry.isFolder) { search.setText(""); model.enter(entry) } else play(entry)
}
list.setOnItemLongClickListener { _, _, position, _ ->
val entry = visible[position]
if (!entry.isFolder) AlertDialog.Builder(this).setTitle(entry.name).setItems(arrayOf("播放", "加入 / 取消收藏")) { _, choice ->
if (choice == 0) play(entry) else lifecycleScope.launch {
withContext(Dispatchers.IO) {
val ref = reference(entry); val old = repo.recent.find(ref.id)
if (old == null) repo.recent.save(ref, entry.resumeMs, null)
repo.recent.favorite(ref.id)
}
Toast.makeText(this@BrowserActivity, "收藏已更新", Toast.LENGTH_SHORT).show()
}
}.show()
true
}
lifecycleScope.launch { model.entries.collect { render() } }
lifecycleScope.launch { model.message.collect { status.text = it; title.text = model.folders.lastOrNull()?.second ?: "媒体浏览" } }
lifecycleScope.launch { model.busy.collect { more.isEnabled = !it && model.more != null; more.visibility = if (model.more == null) android.view.View.GONE else android.view.View.VISIBLE } }
onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) { override fun handleOnBackPressed() { goBack() } })
model.open(intent.getStringExtra("account").orEmpty())
}
private fun reference(entry: LibraryEntry) = MediaRef(entry.name, model.account?.id, entry)
private fun render() {
if (!::list.isInitialized) return
val jellyfin = model.account?.kind == LibraryKind.JELLYFIN
val query = search.text.toString()
visible = model.entries.value.filter { (it.isFolder || jellyfin || LibraryFiles.isVideo(it.name)) && it.name.contains(query, true) }
list.adapter = object : BaseAdapter() {
override fun getCount() = visible.size
override fun getItem(position: Int) = visible[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup?): android.view.View {
val entry = visible[position]
return Ui.card(this@BrowserActivity, (if (entry.isFolder) "▤ " else "▷ ") + entry.name,
if (entry.isFolder) "打开目录" else listOfNotNull(entry.size?.let(Ui::bytes), entry.resumeMs.takeIf { it > 0 }?.let { "已看 ${Ui.time(it)}" }, "点击播放 · 长按收藏").joinToString(" · "))
.apply { minimumHeight = dp(84); isFocusable = false }
}
}
}
private fun play(entry: LibraryEntry) {
val ref = reference(entry)
PlaybackQueue.set(visible.filterNot { it.isFolder }.map(::reference))
lifecycleScope.launch {
try {
withContext(Dispatchers.IO) { val old = repo.recent.find(ref.id); repo.recent.save(ref, old?.positionMs ?: entry.resumeMs, old?.durationMs) }
startActivity(Intent(this@BrowserActivity, PlayerActivity::class.java).putExtra("media", ref.id))
} catch (_: Exception) { status.text = "无法保存播放记录,请检查设备安全存储" }
}
}
private fun goBack() { if (model.up()) search.setText("") else finish() }
}
@@ -0,0 +1,130 @@
package com.ttstd.player.app
import android.app.*
import android.content.*
import android.media.MediaMetadata
import android.media.session.MediaSession
import android.media.session.PlaybackState
import android.os.Build
import android.os.IBinder
import com.ttstd.player.cast.*
import com.ttstd.player.cast.dlna.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
data class DlnaUiState(val active: Boolean = false, val connecting: Boolean = false, val title: String = "",
val device: String = "", val playback: RemotePlaybackState = RemotePlaybackState(), val error: String? = null)
data class DlnaLease(val device: DlnaDevice, val media: CastMedia, val observer: CastProgressObserver, val cleanup: () -> Unit,
val mediaId: String, val positionOffsetMs: Long)
/** 进程内会话只持有应用级资源,不持有 Activity。系统终止进程后不伪造可恢复会话。 */
object DlnaSession {
val state = MutableStateFlow(DlnaUiState())
var lease: DlnaLease? = null
var resourcesOpen = false
fun command(context: Context, action: String) { context.startService(Intent(context, DlnaPlaybackService::class.java).setAction(action)) }
}
/** DLNA 与手机 relay 由前台媒体服务持有,页面退出/旋转不再关闭投屏流。 */
class DlnaPlaybackService : Service() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val mutex = Mutex()
private lateinit var controller: DlnaController
private lateinit var session: MediaSession
private var lease: DlnaLease? = null
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
controller = DlnaController(this)
session = MediaSession(this, "TTVideoPlayer DLNA").apply {
setCallback(object : MediaSession.Callback() {
override fun onPlay() { perform("play") }
override fun onPause() { perform("pause") }
override fun onStop() { perform("stop") }
override fun onSeekTo(pos: Long) { scope.launch { runCatching { lease?.let { mutex.withLock { this@DlnaPlaybackService.controller.seek(it.device, pos) } } } } }
})
isActive = true
}
if (Build.VERSION.SDK_INT >= 26) getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel("dlna-playback", "电视投屏", NotificationManager.IMPORTANCE_LOW))
startForeground(4102, notification())
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == "seek") scope.launch { runCatching { lease?.let { mutex.withLock { controller.seek(it.device, intent.getLongExtra("position", 0)) } } } }
else if (intent?.action != null) perform(intent.action!!) else if (lease == null) {
lease = DlnaSession.lease
val current = lease
if (current == null) { stopSelf(); return START_NOT_STICKY }
DlnaSession.state.value = DlnaUiState(true, true, current.media.title, current.device.name,
RemotePlaybackState(current.media.startPositionMs))
scope.launch {
try {
mutex.withLock { controller.load(current.device, current.media) }
runCatching { current.observer.started(current.media.startPositionMs) }
var reports = 0
while (isActive) {
try {
val value = mutex.withLock { controller.state(current.device) }
DlnaSession.state.value = DlnaUiState(true, false, current.media.title, current.device.name, value)
if (reports++ % 3 == 0) runCatching { current.observer.progress(value) }
updateMediaSession(value)
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { DlnaSession.state.value = DlnaSession.state.value.copy(connecting = false, error = "暂时无法读取电视状态,可重试或结束投屏") }
delay(3000)
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { DlnaSession.state.value = DlnaSession.state.value.copy(error = "电视未接受播放请求"); stopSelf() }
}
}
return START_NOT_STICKY
}
private fun perform(action: String) {
val value = lease ?: return
if (action == "stop") { stopSelf(); return }
scope.launch {
try { mutex.withLock { when (action) {
"pause" -> controller.pause(value.device)
"play" -> controller.play(value.device)
"back" -> controller.seek(value.device, (DlnaSession.state.value.playback.positionMs - 30000).coerceAtLeast(0))
"forward" -> controller.seek(value.device, DlnaSession.state.value.playback.positionMs + 30000)
} } } catch (_: Exception) { DlnaSession.state.value = DlnaSession.state.value.copy(error = "电视未接受该操作") }
}
}
private fun updateMediaSession(value: RemotePlaybackState) {
session.setMetadata(MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_TITLE, DlnaSession.state.value.title)
.putLong(MediaMetadata.METADATA_KEY_DURATION, value.durationMs ?: -1).build())
session.setPlaybackState(PlaybackState.Builder().setActions(PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PAUSE or PlaybackState.ACTION_STOP or PlaybackState.ACTION_SEEK_TO)
.setState(if (value.playing) PlaybackState.STATE_PLAYING else PlaybackState.STATE_PAUSED, value.positionMs, 1f).build())
// 同一个前台媒体通知同时更新状态;无需另发普通通知或申请通知权限。
startForeground(4102, notification())
}
private fun notification(): Notification {
val state = DlnaSession.state.value
fun command(action: String) = PendingIntent.getService(this, action.hashCode(), Intent(this, javaClass).setAction(action), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val builder = if (Build.VERSION.SDK_INT >= 26) Notification.Builder(this, "dlna-playback") else Notification.Builder(this)
return builder.setSmallIcon(R.drawable.ic_app).setContentTitle(state.title.ifBlank { "正在连接电视" })
.setContentText(state.device.ifBlank { "同同影音投屏" }).setOngoing(true)
.setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, HomeActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
.addAction(Notification.Action.Builder(null, if (state.playback.playing) "暂停" else "播放", command(if (state.playback.playing) "pause" else "play")).build())
.addAction(Notification.Action.Builder(null, "结束", command("stop")).build())
.setStyle(Notification.MediaStyle().setMediaSession(session.sessionToken).setShowActionsInCompactView(0, 1)).build()
}
override fun onDestroy() {
val old = lease
val snapshot = DlnaSession.state.value
scope.cancel()
session.release()
DlnaSession.lease = null; lease = null
CoroutineScope(Dispatchers.IO).launch {
withTimeoutOrNull(5000) {
if (old != null) { runCatching { controller.stop(old.device) }; runCatching { old.observer.stopped(snapshot.playback.positionMs) } }
}
old?.cleanup?.invoke()
DlnaSession.resourcesOpen = false
}
DlnaSession.state.value = snapshot.copy(active = false, connecting = false)
super.onDestroy()
}
}
@@ -0,0 +1,259 @@
package com.ttstd.player.app
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.provider.OpenableColumns
import android.text.InputType
import android.view.Gravity
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.ttstd.player.api.*
import com.ttstd.player.core.HttpHeaders
import com.ttstd.player.library.*
import com.ttstd.player.media3.source.Media3FileCache
import com.ttstd.player.cast.google.GoogleCastActivity
import com.ttstd.player.cast.google.GoogleCastResources
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.first
import com.ttstd.player.app.Ui.dp
/** 正式应用入口:媒体、来源、历史、设置。宽屏使用侧边导航,手机使用底部导航。 */
class HomeActivity : AppCompatActivity() {
private val repo by lazy { AppRepository(applicationContext) }
private lateinit var content: LinearLayout
private var tab = 0
private var accounts: List<LibraryAccount> = emptyList()
private var recent: List<RecentMedia> = emptyList()
private var favoritesOnly = false
private var loadJob: Job? = null
private val googleControl = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val id = AppPlaybackRuntime.googleMediaId
if (id != null && result.data != null) lifecycleScope.launch {
withContext(Dispatchers.IO) { repo.recent.find(id)?.let { repo.recent.save(it.ref, result.data!!.getLongExtra("position", it.positionMs) + AppPlaybackRuntime.googleOffsetMs, it.durationMs) } }
startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", id))
}
}
private val pickVideo = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isNotEmpty()) lifecycleScope.launch {
val refs = withContext(Dispatchers.IO) { uris.take(150).map { uri ->
runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) }
val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0) else null
} ?: "本地视频"
MediaRef(name, uri = uri.toString())
} }
PlaybackQueue.set(refs)
open(refs.first())
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tab = savedInstanceState?.getInt("tab") ?: 0
build()
if (intent.action == Intent.ACTION_VIEW && intent.data != null) {
val uri = intent.data!!
if (uri.scheme?.lowercase() in setOf("content", "http", "https", "rtsp", "rtmp"))
lifecycleScope.launch { open(MediaRef(uri.lastPathSegment ?: "外部视频", uri = uri.toString())) }
intent.action = null
}
}
override fun onResume() { super.onResume(); refresh() }
override fun onSaveInstanceState(outState: Bundle) { outState.putInt("tab", tab); super.onSaveInstanceState(outState) }
private fun build() {
val wide = resources.configuration.screenWidthDp >= 720
val root = LinearLayout(this).apply { orientation = if (wide) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL }
Ui.inset(this, root)
val nav = LinearLayout(this).apply {
orientation = if (wide) LinearLayout.VERTICAL else LinearLayout.HORIZONTAL
gravity = Gravity.CENTER; setPadding(dp(8), dp(8), dp(8), dp(8))
}
listOf("首页", "来源", "历史", "设置").forEachIndexed { index, label ->
nav.addView(Ui.button(this, label, index == tab) { tab = index; build(); render() },
if (wide) LinearLayout.LayoutParams(dp(100), dp(64)).apply { bottomMargin = dp(12) }
else LinearLayout.LayoutParams(0, dp(52), 1f).apply { marginStart = dp(3); marginEnd = dp(3) })
}
val scroll = ScrollView(this).apply { isFillViewport = true }
content = Ui.column(this, if (wide) 32 else 20)
scroll.addView(content)
if (wide) {
root.addView(nav, LinearLayout.LayoutParams(dp(116), -1))
root.addView(scroll, LinearLayout.LayoutParams(0, -1, 1f))
} else {
root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)); root.addView(nav)
}
setContentView(root); render()
}
private fun refresh() {
loadJob?.cancel()
loadJob = lifecycleScope.launch {
try {
withContext(Dispatchers.IO) { accounts = repo.accounts.all(); recent = repo.recent.all() }
render()
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { content.removeAllViews(); content.addView(Ui.empty(this@HomeActivity, "本机数据暂不可读", "设备安全密钥可能发生变化,请在系统设置中检查应用数据。")) }
}
}
private fun heading(title: String, detail: String) {
content.addView(Ui.label(this, title, 28f, bold = true))
content.addView(Ui.label(this, detail, 14f, Ui.muted).apply { setPadding(0, dp(8), 0, dp(24)) })
}
private fun render() {
if (!::content.isInitialized) return
content.removeAllViews()
when (tab) {
0 -> home()
1 -> sources()
2 -> history()
else -> settings()
}
}
private fun home() {
heading("同同影音", "你的媒体,随处播放")
if (DlnaSession.state.value.active) content.addView(Ui.card(this, "正在投屏 · ${DlnaSession.state.value.device}", DlnaSession.state.value.title) {
AlertDialog.Builder(this).setTitle("电视投屏").setItems(arrayOf("播放", "暂停", "结束投屏", "结束并在本机继续")) { _, choice ->
val lease = DlnaSession.lease
DlnaSession.command(this, listOf("play", "pause", "stop", "stop")[choice])
if (choice == 3 && lease != null) lifecycleScope.launch {
withTimeoutOrNull(7000) { DlnaSession.state.first { !it.active } }
withContext(Dispatchers.IO) { repo.recent.find(lease.mediaId)?.let { repo.recent.save(it.ref, DlnaSession.state.value.playback.positionMs + lease.positionOffsetMs, it.durationMs) } }
startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", lease.mediaId))
}
}.show()
})
if (GoogleCastResources.observer != null && AppPlaybackRuntime.googleMedia != null) content.addView(Ui.card(this, "Google Cast 正在播放", "打开设备控制或返回本机") {
AppPlaybackRuntime.googleMedia?.let { googleControl.launch(GoogleCastActivity.intent(this, it)) }
})
content.addView(Ui.card(this, "连接你的媒体世界", "本地文件、网盘、局域网与家庭媒体库,在这里汇合。"))
val row = LinearLayout(this)
row.addView(Ui.button(this, "打开本地视频", true) { pickVideo.launch(arrayOf("video/*")) }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) })
row.addView(Ui.button(this, "播放链接") { urlDialog() }, LinearLayout.LayoutParams(0, -2, 1f))
content.addView(row)
content.addView(Ui.label(this, "继续观看", 19f, bold = true).apply { setPadding(0, dp(28), 0, dp(14)) })
if (recent.isEmpty()) content.addView(Ui.empty(this, "从一部视频开始", "打开文件、粘贴链接,或添加你的媒体来源。"))
else recent.take(4).forEach { mediaCard(it) }
content.addView(Ui.label(this, "媒体来源", 19f, bold = true).apply { setPadding(0, dp(20), 0, dp(14)) })
accounts.take(3).forEach { sourceCard(it) }
content.addView(Ui.button(this, if (accounts.isEmpty()) "+ 添加网盘或 NAS" else "管理全部来源") {
if (accounts.isEmpty()) SourceDialogs.edit(this) { refresh() } else { tab = 1; build() }
})
}
private fun sources() {
heading("媒体来源", "WebDAV 网盘 · SMB 局域网 · Jellyfin")
content.addView(Ui.button(this, "+ 添加来源", true) { SourceDialogs.edit(this) { refresh() } })
content.addView(Ui.label(this, "", 8f))
if (accounts.isEmpty()) content.addView(Ui.empty(this, "连接你的网盘或 NAS", "WebDAV 可连接支持该协议的网盘或聚合服务;SMB 连接共享文件夹。"))
accounts.forEach { sourceCard(it) }
}
private fun sourceCard(account: LibraryAccount) {
val host = runCatching { java.net.URI(account.endpoint).host }.getOrNull().orEmpty()
val card = Ui.card(this, account.name, "${account.kind} · $host") { startActivity(Intent(this, BrowserActivity::class.java).putExtra("account", account.id)) }
card.addView(Ui.button(this, "管理来源") {
AlertDialog.Builder(this).setTitle(account.name).setItems(arrayOf("编辑连接", "删除来源")) { _, index ->
if (index == 0) SourceDialogs.edit(this, account) { refresh() }
else AlertDialog.Builder(this).setMessage("删除连接配置?服务器上的文件不会被修改。")
.setPositiveButton("删除") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { repo.accounts.delete(account.id) }; refresh() } }
.setNegativeButton("取消", null).show()
}.show()
}.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(14) } })
content.addView(card)
}
private fun history() {
heading("观看记录", "记录与播放链接加密保存在本机")
val filters = LinearLayout(this)
filters.addView(Ui.button(this, "全部", !favoritesOnly) { favoritesOnly = false; render() }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) })
filters.addView(Ui.button(this, "收藏", favoritesOnly) { favoritesOnly = true; render() }, LinearLayout.LayoutParams(0, -2, 1f))
content.addView(filters); content.addView(Ui.label(this, "", 8f))
val visible = recent.filter { !favoritesOnly || it.favorite }
if (visible.isEmpty()) content.addView(Ui.empty(this, if (favoritesOnly) "还没有收藏" else "还没有观看记录", "视频卡片的更多菜单可收藏或移除记录。"))
visible.forEach { mediaCard(it) }
}
private fun mediaCard(item: RecentMedia) {
val position = if (item.positionMs > 0) "已看 ${Ui.time(item.positionMs)}" else "从头播放"
val source = item.ref.accountId?.let { id -> accounts.firstOrNull { it.id == id }?.name } ?: if (item.ref.uri?.startsWith("content:") == true) "本地文件" else "在线视频"
val card = Ui.card(this, (if (item.favorite) "★ " else "") + item.ref.title, "$source · $position") { lifecycleScope.launch { open(item.ref) } }
if (item.durationMs != null && item.durationMs > 0) card.addView(ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
max = 1000; progress = (item.positionMs * 1000 / item.durationMs).coerceIn(0, 1000).toInt()
progressTintList = android.content.res.ColorStateList.valueOf(Ui.accent)
})
card.addView(Ui.button(this, "更多") {
AlertDialog.Builder(this).setTitle(item.ref.title).setItems(arrayOf(if (item.favorite) "取消收藏" else "加入收藏", "从头播放", "移除记录")) { _, choice ->
lifecycleScope.launch {
withContext(Dispatchers.IO) {
when (choice) { 0 -> repo.recent.favorite(item.ref.id); 1 -> repo.recent.save(item.ref, 0, item.durationMs); else -> repo.recent.remove(item.ref.id) }
}
if (choice == 1) open(item.ref) else refresh()
}
}.show()
}.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) } })
content.addView(card)
}
private fun settings() {
heading("播放与存储", "为不同设备选择合适的播放方式")
val modes = DecodeMode.entries
val names = arrayOf("自动选择", "优先硬件解码", "仅硬件解码", "仅系统软件解码")
content.addView(Ui.card(this, "默认解码方式", names[modes.indexOf(repo.preferences.decoder)]) {
AlertDialog.Builder(this).setTitle("默认解码方式").setSingleChoiceItems(names, modes.indexOf(repo.preferences.decoder)) { dialog, index -> repo.preferences.decoder = modes[index]; dialog.dismiss(); render() }.show()
})
content.addView(Ui.card(this, "视频显示", if (repo.preferences.texture) "TextureView · 适合界面变换" else "SurfaceView · 默认省电路径") {
repo.preferences.texture = !repo.preferences.texture; render()
})
content.addView(Ui.card(this, "自动加载同名字幕", if (repo.preferences.autoSubtitle) "已开启" else "已关闭") { repo.preferences.autoSubtitle = !repo.preferences.autoSubtitle; render() })
content.addView(Ui.card(this, "媒体缓存", "已使用 ${Ui.bytes(cacheBytes())} · 目标上限 256 MB\n缓存可被系统回收,不是离线下载。"))
content.addView(Ui.button(this, "清理媒体缓存") {
if (AppPlaybackRuntime.localActive || DlnaSession.resourcesOpen || GoogleCastResources.observer != null) {
Toast.makeText(this, "请先结束播放和投屏,再清理缓存", Toast.LENGTH_LONG).show(); return@button
}
AlertDialog.Builder(this).setMessage("确认清理已缓存的媒体片段?投屏或播放进行中时请先停止播放。")
.setPositiveButton("清理") { _, _ -> lifecycleScope.launch {
val result = withContext(Dispatchers.IO) { runCatching { Media3FileCache.get(applicationContext); Media3FileCache.clear() } }
Toast.makeText(this@HomeActivity, if (result.isSuccess) "缓存已清理" else "缓存暂时无法清理,请结束播放后重试", Toast.LENGTH_SHORT).show(); render()
} }.setNegativeButton("取消", null).show()
})
content.addView(Ui.button(this, "清空历史与收藏") {
AlertDialog.Builder(this).setMessage("清空本机记录?媒体来源和远端文件会保留。")
.setPositiveButton("清空") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { repo.recent.clear() }; refresh() } }
.setNegativeButton("取消", null).show()
}.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) } })
content.addView(Ui.card(this, "关于同同影音", "1.0.0 · Android 6.0+\n本地 / 在线 / WebDAV / SMB / Jellyfin\n支持 DLNA 与 Google Cast;接收端需支持对应媒体格式。"))
}
private fun cacheBytes() = runCatching { Media3FileCache.bytes() }.getOrDefault(0)
private fun urlDialog() {
val form = Ui.column(this, 20)
val url = EditText(this).apply { hint = "视频地址或直播链接"; isSaveEnabled = false; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI; setSingleLine(true) }
form.addView(url)
val types = MediaSourceType.entries
val selector = Spinner(this).apply { adapter = ArrayAdapter(this@HomeActivity, android.R.layout.simple_spinner_dropdown_item, types.map { it.name }) }
form.addView(selector)
val headers = EditText(this).apply { hint = "请求头(选填,每行 Name: value)"; minLines = 2; isSaveEnabled = false; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE }
form.addView(headers)
val tcp = CheckBox(this).apply { text = "RTSP 使用 TCP" }; form.addView(tcp)
val error = Ui.label(this, "", 13f, Ui.muted); form.addView(error)
val dialog = AlertDialog.Builder(this).setTitle("播放网络链接").setView(ScrollView(this).apply { addView(form) }).setPositiveButton("播放", null).setNegativeButton("取消", null).create()
dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val parsed = runCatching {
val address = url.text.toString().trim()
require(java.net.URI(address).isAbsolute) { "请输入完整播放地址" }
MediaRef(android.net.Uri.parse(address).lastPathSegment?.takeIf(String::isNotBlank) ?: "在线视频", uri = address,
headers = HttpHeaders.parseLines(headers.text.toString()), sourceType = types[selector.selectedItemPosition],
network = NetworkOptions(rtspTransport = if (tcp.isChecked) RtspTransport.TCP else RtspTransport.AUTO))
}
parsed.onSuccess { ref -> dialog.dismiss(); lifecycleScope.launch { open(ref) } }.onFailure { error.text = "地址或请求头格式不正确" }
} }
dialog.show()
}
private suspend fun open(ref: MediaRef) {
try {
withContext(Dispatchers.IO) { val old = repo.recent.find(ref.id); repo.recent.save(ref, old?.positionMs ?: 0, old?.durationMs) }
startActivity(Intent(this, PlayerActivity::class.java).putExtra("media", ref.id))
} catch (_: Exception) { Toast.makeText(this, "无法保存播放记录,请检查设备安全存储", Toast.LENGTH_LONG).show() }
}
}
/** 播放队列只存来源身份;进程重建后至少恢复当前历史条目。 */
object PlaybackQueue {
var refs: List<MediaRef> = emptyList(); private set
fun set(values: List<MediaRef>) { refs = values.toList() }
}
@@ -0,0 +1,244 @@
package com.ttstd.player.app
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import android.provider.OpenableColumns
import android.view.*
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.*
import com.ttstd.player.api.*
import com.ttstd.player.library.LibraryFiles
import com.ttstd.player.render.*
import kotlinx.coroutines.launch
import com.ttstd.player.app.Ui.dp
/** 播放界面只拥有 Surface 与控件;内核/观看会话由 PlayerModel 管理。 */
class PlayerActivity : AppCompatActivity() {
private lateinit var model: PlayerModel
private val repo by lazy { AppRepository(applicationContext) }
private var surfaceBinding: AutoCloseable? = null
private lateinit var video: FrameLayout
private lateinit var subtitle: TextView
private lateinit var center: TextView
private lateinit var title: TextView
private lateinit var playButton: TextView
private lateinit var time: TextView
private lateinit var seek: SeekBar
private lateinit var information: TextView
private var dragging = false
private var crop = false
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)
}
private val pickSubtitle = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) {
runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) }
val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { if (it.moveToFirst()) it.getString(0) else "" }.orEmpty()
val mime = LibraryFiles.subtitleMime(name)
if (mime == null) Toast.makeText(this, "请选择 SRT、VTT、ASS 或 SSA 字幕", Toast.LENGTH_LONG).show()
else model.attachSubtitle(ExternalSubtitle(uri.toString(), mime, isDefault = true))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
model = ViewModelProvider(this)[PlayerModel::class.java]
build()
lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) {
launch { model.engine.state.collect { render() } }
launch { model.current.collect { item ->
item?.let { intent.putExtra("media", it.ref.id) }
render()
} }
launch { model.loading.collect { render() } }
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 { DlnaSession.state.collect { render() } }
} }
model.open(intent.getStringExtra("media").orEmpty())
}
private fun build() {
surfaceBinding?.close()
val landscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
val root = FrameLayout(this)
Ui.inset(this, root)
val stack = Ui.column(this)
root.addView(stack, FrameLayout.LayoutParams(-1, -1))
val toolbar = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL; setPadding(dp(12), dp(8), dp(12), dp(8)); setBackgroundColor(0xd9111822.toInt()) }
toolbar.addView(Ui.button(this, "‹") { finish() })
title = Ui.label(this, "正在准备视频", 16f, bold = true).apply { maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END }
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() })
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))
setShadowLayer(dp(2).toFloat(), 0f, 1f, android.graphics.Color.BLACK)
isClickable = false
}
center = Ui.label(this, "", 16f).apply { gravity = Gravity.CENTER; setBackgroundColor(0x77101822) }
val surface: View = if (repo.preferences.texture) TextureView(this) else SurfaceView(this)
video.addView(surface, FrameLayout.LayoutParams(-1, -1, Gravity.CENTER))
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()) }
time = Ui.label(this, "0:00 / --:--", 13f, Ui.muted)
controls.addView(time)
seek = SeekBar(this).apply { max = 1000 }
controls.addView(seek, LinearLayout.LayoutParams(-1, dp(44)))
seek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onStartTrackingTouch(seekBar: SeekBar) { dragging = true }
override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) = Unit
override fun onStopTrackingTouch(seekBar: SeekBar) {
dragging = false
val duration = currentDuration() ?: return
val target = duration * seekBar.progress / 1000
if (model.remote.value == "dlna") startService(Intent(this@PlayerActivity, DlnaPlaybackService::class.java).setAction("seek").putExtra("position", target))
else model.seek(target)
}
})
val buttons = LinearLayout(this).apply { gravity = Gravity.CENTER }
fun control(label: String, primary: Boolean = false, action: () -> Unit): TextView = Ui.button(this, label, primary, action).also {
buttons.addView(it, LinearLayout.LayoutParams(0, dp(52), 1f).apply { marginStart = dp(3); marginEnd = dp(3) })
}
control("上一部") { model.next(-1) }
control("−10s") { seekBy(-10000) }
playButton = control("播放", true) {
if (model.remote.value == "dlna") DlnaSession.command(this, if (DlnaSession.state.value.playback.playing) "pause" else "play") else model.toggle()
}
control("+10s") { seekBy(10000) }
control("下一部") { model.next(1) }
controls.addView(buttons)
information = Ui.label(this, "", 13f, Ui.muted).apply { setPadding(0, dp(14), 0, dp(8)) }
controls.addView(information)
controls.addView(Ui.button(this, if (landscape) "退出全屏" else "全屏播放") {
requestedOrientation = if (landscape) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
})
if (landscape) {
root.removeView(stack)
root.addView(video, FrameLayout.LayoutParams(-1, -1))
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))
} 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))
}
val gesture = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: android.view.MotionEvent) = true
override fun onDoubleTap(e: android.view.MotionEvent): Boolean {
if (model.remote.value == null) model.seek((model.absolutePosition() + if (e.x < video.width / 2) -10000 else 10000).coerceAtLeast(0))
return true
}
override fun onSingleTapConfirmed(e: android.view.MotionEvent): Boolean {
if (landscape) { toolbar.visibility = if (toolbar.visibility == View.VISIBLE) View.GONE else View.VISIBLE; controls.visibility = toolbar.visibility }
return true
}
})
video.setOnTouchListener { _, event -> gesture.onTouchEvent(event) }
center.setOnClickListener { if (model.error.value != null || model.engine.state.value.phase == PlaybackPhase.ERROR) model.retry() }
setContentView(root)
WindowInsetsControllerCompat(window, root).apply { if (landscape) hide(WindowInsetsCompat.Type.systemBars()) else show(WindowInsetsCompat.Type.systemBars()) }
video.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitVideo() }
surfaceBinding = if (surface is TextureView) TextureViewBinding(surface, model.engine) else SurfaceViewBinding(surface as SurfaceView, model.engine)
render()
}
private fun currentDuration(): Long? = if (model.remote.value == "dlna") DlnaSession.state.value.playback.durationMs else model.duration()
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 ?: "正在准备视频"
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) ?: "--:--"}"
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 {
remote == "dlna" -> "正在 ${DlnaSession.state.value.device} 播放\n${DlnaSession.state.value.error ?: "可关闭页面,投屏会继续"}"
model.loading.value || state.phase in setOf(PlaybackPhase.PREPARING, PlaybackPhase.BUFFERING) -> "正在缓冲…"
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)
}
private fun seekBy(delta: Long) {
if (model.remote.value == "dlna") startService(Intent(this, DlnaPlaybackService::class.java).setAction("seek")
.putExtra("position", (DlnaSession.state.value.playback.positionMs + delta).coerceAtLeast(0)))
else model.seek((model.absolutePosition() + delta).coerceAtLeast(0))
}
private fun fitVideo() {
if (!::video.isInitialized) return
val child = video.getChildAt(0) ?: return
val ratio = model.videoRatio.value
if (video.width <= 0 || video.height <= 0 || ratio <= 0) return
val width = if (crop) maxOf(video.width, (video.height * ratio).toInt()) else minOf(video.width, (video.height * ratio).toInt())
val height = if (crop) maxOf(video.height, (video.width / ratio).toInt()) else minOf(video.height, (video.width / ratio).toInt())
if (child.layoutParams.width != width || child.layoutParams.height != height) child.layoutParams = FrameLayout.LayoutParams(width, height, Gravity.CENTER)
}
private fun menu() {
if (model.remote.value == "dlna") { castDialog(); return }
val labels = arrayOf("音轨", "字幕", "加载外挂字幕", "播放速度", "显示比例:${if (crop) "填充" else "适应"}", "收藏 / 取消收藏", "视频显示方式", "解码方式")
AlertDialog.Builder(this).setTitle("播放选项").setItems(labels) { _, index -> when (index) {
0 -> tracks(TrackType.AUDIO)
1 -> tracks(TrackType.TEXT)
2 -> pickSubtitle.launch(arrayOf("*/*"))
3 -> AlertDialog.Builder(this).setTitle("播放速度").setItems(arrayOf("0.5×", "0.75×", "1×", "1.25×", "1.5×", "2×")) { _, i -> model.setSpeed(listOf(.5f, .75f, 1f, 1.25f, 1.5f, 2f)[i]) }.show()
4 -> { crop = !crop; fitVideo() }
5 -> { model.favorite(); Toast.makeText(this, "收藏已更新", Toast.LENGTH_SHORT).show() }
6 -> { repo.preferences.texture = !repo.preferences.texture; build() }
7 -> AlertDialog.Builder(this).setTitle("解码方式").setItems(arrayOf("自动选择", "优先硬解", "仅硬解", "仅系统软解")) { _, i -> model.setDecoder(DecodeMode.entries[i]) }.show()
} }.show()
}
private fun tracks(type: TrackType) {
val list = model.engine.state.value.tracks.filter { it.type == type }
val options = if (type == TrackType.TEXT) listOf("关闭字幕") else listOf("自动选择")
AlertDialog.Builder(this).setTitle(if (type == TrackType.TEXT) "字幕" else "音轨")
.setItems((options + list.map { "${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}" }).toTypedArray()) { _, index ->
model.selectTrack(if (index == 0) TrackSelection(type, disabled = type == TrackType.TEXT) else TrackSelection(type, list[index - 1].id))
}.show()
}
private fun castDialog() {
if (model.remote.value == "dlna") {
AlertDialog.Builder(this).setTitle(DlnaSession.state.value.device).setItems(arrayOf("播放", "暂停", "后退 30 秒", "前进 30 秒", "结束投屏并返回本机")) { _, index ->
DlnaSession.command(this, listOf("play", "pause", "back", "forward", "stop")[index])
}.show(); return
}
AlertDialog.Builder(this).setTitle("投屏到设备").setItems(arrayOf("DLNA · 电视 / 盒子", "Google Cast")) { _, index ->
lifecycleScope.launch {
if (index == 1) model.googleIntent()?.let(google::launch) else {
val progress = AlertDialog.Builder(this@PlayerActivity).setMessage("正在搜索同一局域网的电视…").create(); progress.show()
try {
val devices = model.devices(); progress.dismiss()
if (devices.isEmpty()) Toast.makeText(this@PlayerActivity, "未发现设备,请确认电视投屏已开启", Toast.LENGTH_LONG).show()
else AlertDialog.Builder(this@PlayerActivity).setTitle("选择电视").setItems(devices.map { it.name }.toTypedArray()) { _, i -> model.dlna(devices[i]) }.show()
} catch (cancelled: kotlinx.coroutines.CancellationException) { progress.dismiss(); throw cancelled }
catch (_: Exception) { progress.dismiss(); Toast.makeText(this@PlayerActivity, "设备搜索失败,请检查网络", Toast.LENGTH_LONG).show() }
}
}
}.show()
}
override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig); build() }
override fun onStart() { super.onStart(); model.onVisible() }
override fun onStop() { model.onHidden(isChangingConfigurations); super.onStop() }
override fun onDestroy() { surfaceBinding?.close(); surfaceBinding = null; super.onDestroy() }
}
@@ -0,0 +1,219 @@
package com.ttstd.player.app
import android.app.Application
import android.content.Intent
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.ttstd.player.api.*
import com.ttstd.player.cast.*
import com.ttstd.player.cast.dlna.*
import com.ttstd.player.cast.google.*
import com.ttstd.player.cast.relay.CastRelay
import com.ttstd.player.library.*
import com.ttstd.player.library.media3.LibraryPlaybackTracker
import com.ttstd.player.media3.Media3Engine
import com.ttstd.player.media3.source.Media3FileCache
import com.ttstd.player.telemetry.PlaybackTelemetry
import com.ttstd.player.telemetry.TelemetrySink
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
object AppPlaybackRuntime {
private var localOwners = 0
val localActive: Boolean get() = localOwners > 0
fun acquireLocal() { localOwners++ }
fun releaseLocal() { localOwners = (localOwners - 1).coerceAtLeast(0) }
var googleMedia: CastMedia? = null
var googleMediaId: String? = null
var googleOffsetMs: Long = 0
}
/** 播放器归 ViewModel 所有,Surface 和界面归 Activity 所有;旋转只重绑输出。 */
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") })
val current = MutableStateFlow<RecentMedia?>(null)
val error = MutableStateFlow<String?>(null)
val notices = MutableSharedFlow<String>(extraBufferCapacity = 16)
val loading = MutableStateFlow(false)
val remote = MutableStateFlow<String?>(null)
val videoRatio = MutableStateFlow(16f / 9f)
var playback: LibraryPlayback? = null; private set
private var loadJob: Job? = null
private var resumeOnVisible = false
private var historyAt = 0L
private var visible = false
init {
AppPlaybackRuntime.acquireLocal()
viewModelScope.launch { engine.events.collect { event ->
if (event is PlaybackEvent.VideoSize && event.height > 0) videoRatio.value = event.width * event.pixelRatio / event.height
} }
viewModelScope.launch { engine.state.collect { state ->
if (!loading.value && remote.value == null && state.phase !in setOf(PlaybackPhase.IDLE, PlaybackPhase.RELEASED, PlaybackPhase.PREPARING)) {
val now = android.os.SystemClock.elapsedRealtime()
if (now - historyAt >= 5000 || !state.playWhenReady || state.phase == PlaybackPhase.ENDED) {
checkpointHistory(state, now)
}
}
} }
// 引擎事件在厂商实现上可能不按秒分发;独立时钟保证播放中至少每五秒落盘一次。
viewModelScope.launch {
while (isActive) {
delay(5_000)
val state = engine.state.value
if (!loading.value && remote.value == null && state.phase !in setOf(PlaybackPhase.IDLE, PlaybackPhase.RELEASED, PlaybackPhase.PREPARING))
checkpointHistory(state, android.os.SystemClock.elapsedRealtime())
}
}
viewModelScope.launch { DlnaSession.state.collect { state ->
if (remote.value == "dlna" && !state.active && !loading.value) {
remote.value = null
state.error?.let { error.value = it }
resumeOnVisible = state.playback.playing && !visible
resumeLocal(state.playback.positionMs, state.playback.playing && visible)
}
} }
}
fun open(id: String) {
if (current.value?.ref?.id == id && playback != null) return
loadJob?.cancel()
loadJob = viewModelScope.launch {
loading.value = true; error.value = null
try {
tracker.close(); engine.pause()
val item = withContext(Dispatchers.IO) { repo.recent.find(id) } ?: throw LibraryException("播放记录已移除,请重新选择视频")
current.value = item
playResolved(repo.resolve(item.ref, item.positionMs), true)
} catch (cancelled: CancellationException) { throw cancelled }
catch (e: Exception) { error.value = SourceDialogs.safeError(e) }
finally { loading.value = false }
}
}
private suspend fun playResolved(value: LibraryPlayback, autoplay: Boolean) {
tracker.close()
if (value.request.cacheKey != null) withContext(Dispatchers.IO) { runCatching { Media3FileCache.get(getApplication()) } }
engine.setDecodePolicy(DecodePolicy(video = repo.preferences.decoder))
val result = engine.prepare(value.request.copy(autoplay = autoplay))
if (result != CommandResult.Accepted) throw LibraryException("媒体无法加载,请检查播放地址与设置")
playback = value; tracker.bind(value)
}
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() } }
fun seek(position: Long) { viewModelScope.launch {
val p = playback ?: return@launch
if (p.positionOffsetMs > 0) resumeLocal((position - p.positionOffsetMs).coerceAtLeast(-p.positionOffsetMs), engine.state.value.playWhenReady)
else { val result = engine.seekTo(position); if (result != CommandResult.Accepted) notices.tryEmit("此来源暂不支持拖动") }
} }
fun next(direction: Int) {
if (remote.value != null) { notices.tryEmit("请先结束投屏,再切换视频"); return }
val refs = PlaybackQueue.refs
val index = refs.indexOfFirst { it.id == current.value?.ref?.id }
val next = refs.getOrNull(index + direction) ?: run { notices.tryEmit("没有更多视频"); return }
viewModelScope.launch {
withContext(Dispatchers.IO) { val old = repo.recent.find(next.id); repo.recent.save(next, old?.positionMs ?: next.entry?.resumeMs ?: 0, old?.durationMs) }
playback = null; open(next.id)
}
}
fun favorite() { val id = current.value?.ref?.id ?: return; viewModelScope.launch {
withContext(Dispatchers.IO) { repo.recent.favorite(id) }
current.value = withContext(Dispatchers.IO) { repo.recent.find(id) }
} }
fun setSpeed(value: Float) { viewModelScope.launch { engine.setSpeed(value) } }
fun setDecoder(value: DecodeMode) { repo.preferences.decoder = value; viewModelScope.launch { engine.setDecodePolicy(DecodePolicy(video = value)) } }
fun selectTrack(selection: TrackSelection) { viewModelScope.launch { engine.selectTrack(selection) } }
fun attachSubtitle(subtitle: ExternalSubtitle) { viewModelScope.launch {
val item = current.value ?: return@launch
val ref = item.ref.copy(extraSubtitles = listOf(subtitle))
val pos = absolutePosition()
withContext(Dispatchers.IO) { repo.recent.save(ref, pos, item.durationMs) }
current.value = item.copy(ref = ref)
resumeLocal(engine.state.value.positionMs, engine.state.value.playWhenReady)
} }
fun onVisible() { visible = true; if (resumeOnVisible && remote.value == null) { resumeOnVisible = false; viewModelScope.launch { engine.play() } } }
fun onHidden(changingConfiguration: Boolean) {
if (!changingConfiguration) visible = false
tracker.checkpoint()
checkpointHistory(engine.state.value, android.os.SystemClock.elapsedRealtime(), force = true)
if (!changingConfiguration && remote.value == null) { resumeOnVisible = engine.state.value.playWhenReady; viewModelScope.launch { engine.pause() } }
}
private fun checkpointHistory(state: PlaybackState, now: Long, force: Boolean = false) {
val item = current.value ?: return
if (!force && now - historyAt < 5_000) return
historyAt = now
val p = state.positionMs + (playback?.positionOffsetMs ?: 0)
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) }
}
}
fun absolutePosition() = engine.state.value.positionMs + (playback?.positionOffsetMs ?: 0)
fun duration() = playback?.originalDurationMs ?: engine.state.value.durationMs?.plus(playback?.positionOffsetMs ?: 0)
suspend fun resumeLocal(position: Long, playing: Boolean) {
val item = current.value ?: return
loading.value = true; error.value = null
try { playResolved(repo.resolve(item.ref, (position + (playback?.positionOffsetMs ?: 0)).coerceAtLeast(0)), playing) }
catch (cancelled: CancellationException) { throw cancelled }
catch (e: Exception) { error.value = SourceDialogs.safeError(e) }
finally { loading.value = false }
}
private fun media(relay: CastRelay): CastMedia {
val p = playback ?: throw LibraryException("请先加载视频")
val request = p.receiverRequest ?: p.request
val decision = CastPolicy.assess(request)
require(decision.route != CastRoute.UNSUPPORTED) { decision.reason }
val uri = if (decision.route == CastRoute.DIRECT) request.uri else relay.publish(request, decision.mimeType, p.contentLength)
return CastMedia(uri, p.title, decision.mimeType, engine.state.value.positionMs)
}
suspend fun devices(): List<DlnaDevice> = DlnaController(getApplication()).discover()
fun dlna(device: DlnaDevice) { viewModelScope.launch {
if (DlnaSession.state.value.active || DlnaSession.resourcesOpen) { notices.tryEmit("请先结束当前电视投屏并等待连接释放"); return@launch }
val p = playback ?: return@launch
val relay = CastRelay(getApplication())
try {
val media = media(relay)
DlnaSession.lease = DlnaLease(device, media, castObserver(p), relay::close, current.value!!.ref.id, p.positionOffsetMs)
DlnaSession.resourcesOpen = true
DlnaSession.state.value = DlnaUiState(true, true, media.title, device.name, RemotePlaybackState(media.startPositionMs))
tracker.detach(); engine.pause(); remote.value = "dlna"
ContextCompat.startForegroundService(getApplication(), Intent(getApplication(), DlnaPlaybackService::class.java))
} catch (_: Exception) { relay.close(); DlnaSession.resourcesOpen = false; remote.value = null; notices.tryEmit("无法启动电视投屏"); resumeLocal(engine.state.value.positionMs, true) }
} }
suspend fun googleIntent(): Intent? {
val p = playback ?: return null
val relay = CastRelay(getApplication())
return try {
val value = media(relay)
GoogleCastResources.hold(castObserver(p), relay::close)
AppPlaybackRuntime.googleMedia = value
AppPlaybackRuntime.googleMediaId = current.value?.ref?.id
AppPlaybackRuntime.googleOffsetMs = p.positionOffsetMs
tracker.detach(); engine.pause(); remote.value = "google"
GoogleCastActivity.intent(getApplication(), value)
} catch (e: Exception) { relay.close(); notices.tryEmit(e.message ?: "该视频不能投屏"); null }
}
fun googleReturned(position: Long, playing: Boolean) { remote.value = null; viewModelScope.launch { resumeLocal(position, playing) } }
private fun castObserver(value: LibraryPlayback): CastProgressObserver {
val ref = current.value!!.ref
val store = repo.recent
return object : CastProgressObserver {
override suspend fun started(positionMs: Long) { value.session?.started(positionMs) }
override suspend fun progress(state: RemotePlaybackState) {
withContext(Dispatchers.IO) { store.save(ref, state.positionMs + value.positionOffsetMs, value.originalDurationMs ?: state.durationMs?.plus(value.positionOffsetMs)) }
value.session?.progress(state.positionMs, !state.playing)
}
override suspend fun stopped(positionMs: Long) {
withContext(Dispatchers.IO) { store.save(ref, positionMs + value.positionOffsetMs, value.originalDurationMs) }
value.session?.stopped(positionMs)
}
}
}
override fun onCleared() {
tracker.close(); telemetry.close(); AppPlaybackRuntime.releaseLocal()
CoroutineScope(Dispatchers.Main.immediate).launch { engine.release() }
super.onCleared()
}
}
@@ -0,0 +1,74 @@
package com.ttstd.player.app
import android.app.AlertDialog
import android.text.InputType
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.ttstd.player.library.*
import kotlinx.coroutines.*
import java.net.URI
import java.util.UUID
import com.ttstd.player.app.Ui.dp
/** 来源编辑与连接测试共用同一个校验边界,保存前不向服务器发起请求。 */
object SourceDialogs {
fun edit(activity: AppCompatActivity, existing: LibraryAccount? = null, saved: () -> Unit) {
val repo = AppRepository(activity.applicationContext)
val form = Ui.column(activity, 20)
val kinds = LibraryKind.entries
form.addView(Ui.label(activity, "选择连接方式", 13f, Ui.muted))
val kind = Spinner(activity).apply {
adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, listOf("WebDAV · 网盘 / NAS", "SMB · 局域网共享", "Jellyfin · 媒体服务器"))
setSelection(kinds.indexOf(existing?.kind ?: LibraryKind.WEBDAV))
}
form.addView(kind)
fun input(label: String, value: String, secret: Boolean = false): EditText {
form.addView(Ui.label(activity, label, 13f, Ui.muted).apply { setPadding(0, activity.dp(12), 0, 0) })
return EditText(activity).apply {
setSingleLine(true); isSaveEnabled = false
inputType = InputType.TYPE_CLASS_TEXT or if (secret) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
setText(value); form.addView(this)
}
}
val name = input("名称", existing?.name.orEmpty())
val endpoint = input("服务地址(SMB 需包含共享名)", existing?.endpoint.orEmpty()).apply { hint = "https://nas.example/dav/" }
val user = input("用户名", existing?.username.orEmpty())
val password = input("密码 / 应用专用密码", existing?.password.orEmpty(), true)
val domain = input("SMB 域(选填)", existing?.domain.orEmpty())
val status = Ui.label(activity, "凭证加密保存在本机。WebDAV 支持匿名与 Basic 认证。", 12f, Ui.muted)
form.addView(status)
fun account(): LibraryAccount {
val selected = kinds[kind.selectedItemPosition]
val uri = runCatching { URI(endpoint.text.toString().trim()) }.getOrNull()
require(name.text.isNotBlank() && uri?.host != null && uri.userInfo == null && uri.query == null && uri.fragment == null) { "请填写名称和正确的服务根地址" }
require(if (selected == LibraryKind.SMB) uri.scheme == "smb" && uri.path.trim('/').isNotEmpty() else uri.scheme in setOf("http", "https")) { "地址与连接方式不匹配" }
return LibraryAccount(existing?.id ?: UUID.randomUUID().toString(), name.text.toString().trim(), selected, uri.toASCIIString(),
user.text.toString(), password.text.toString(), domain.text.toString())
}
val test = Ui.button(activity, "测试连接") {
val value = runCatching { account() }.getOrElse { status.text = it.message; return@button }
status.text = "正在连接…"
activity.lifecycleScope.launch {
try { val page = withContext(Dispatchers.IO) { repo.library(value).list() }; status.text = "连接成功,当前目录 ${page.entries.size} 项" }
catch (cancelled: CancellationException) { throw cancelled }
catch (e: Exception) { status.text = safeError(e) }
}
}
form.addView(test)
val dialog = AlertDialog.Builder(activity).setTitle(if (existing == null) "添加媒体来源" else "编辑来源")
.setView(ScrollView(activity).apply { addView(form) }).setPositiveButton("保存", null).setNegativeButton("取消", null).create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { button ->
val value = runCatching { account() }.getOrElse { status.text = it.message; return@setOnClickListener }
button.isEnabled = false
activity.lifecycleScope.launch {
try { withContext(Dispatchers.IO) { repo.accounts.save(value) }; dialog.dismiss(); saved() }
catch (_: Exception) { status.text = "保存失败,请检查设备安全存储"; button.isEnabled = true }
}
}
}
dialog.show()
}
fun safeError(error: Exception) = if (error is LibraryException) error.message ?: "来源请求失败" else "连接失败,请检查地址、账户和网络"
}
@@ -0,0 +1,73 @@
package com.ttstd.player.app
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.doOnAttach
/** 轻量原生界面组件,触摸目标至少 48dp,同时支持键盘焦点与大字体。 */
object Ui {
val bg = Color.rgb(12, 18, 28)
val panel = Color.rgb(22, 32, 46)
val raised = Color.rgb(31, 44, 61)
val ink = Color.rgb(236, 243, 249)
val muted = Color.rgb(149, 168, 188)
val accent = Color.rgb(100, 227, 190)
fun Context.dp(value: Int) = (value * resources.displayMetrics.density).toInt()
fun shape(color: Int, radius: Float = 18f) = GradientDrawable().apply { setColor(color); cornerRadius = radius }
fun label(context: Context, value: String, size: Float = 15f, color: Int = ink, bold: Boolean = false) = TextView(context).apply {
text = value; textSize = size; setTextColor(color)
if (bold) setTypeface(typeface, Typeface.BOLD)
}
fun column(context: Context, padding: Int = 0) = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setPadding(context.dp(padding), context.dp(padding), context.dp(padding), context.dp(padding))
}
fun button(context: Context, title: String, primary: Boolean = false, action: () -> Unit) = TextView(context).apply {
text = title; textSize = 15f; gravity = Gravity.CENTER; minHeight = context.dp(48); minimumWidth = context.dp(48)
setPadding(context.dp(16), context.dp(8), context.dp(16), context.dp(8))
setTextColor(if (primary) bg else ink)
background = RippleDrawable(ColorStateList.valueOf(0x2264e3be), shape(if (primary) accent else raised, context.dp(14).toFloat()), null)
isFocusable = true; isClickable = true; contentDescription = title; setOnClickListener { action() }
}
fun card(context: Context, title: String, subtitle: String, action: (() -> Unit)? = null): LinearLayout = column(context, 18).apply {
background = shape(panel, context.dp(18).toFloat())
addView(label(context, title, 18f, bold = true))
addView(label(context, subtitle, 13f, muted).apply { setPadding(0, context.dp(8), 0, 0) })
layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = context.dp(12) }
if (action != null) { isFocusable = true; isClickable = true; setOnClickListener { action() } }
}
fun inset(activity: AppCompatActivity, view: View) {
view.setBackgroundColor(bg)
// API 35 的窗口在 setContentView 前尚无 DecorView,等根视图附着后再访问控制器。
view.doOnAttach {
WindowInsetsControllerCompat(activity.window, view).apply { isAppearanceLightStatusBars = false; isAppearanceLightNavigationBars = false }
ViewCompat.requestApplyInsets(view)
}
ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
v.setPadding(bars.left, bars.top, bars.right, bars.bottom); insets
}
}
fun empty(context: Context, title: String, description: String) = column(context, 28).apply {
gravity = Gravity.CENTER; minimumHeight = context.dp(220)
addView(label(context, "▷", 52f, accent))
addView(label(context, title, 20f, bold = true))
addView(label(context, description, 14f, muted).apply { gravity = Gravity.CENTER; setPadding(0, context.dp(12), 0, 0) })
}
fun time(ms: Long): String {
val s = ms.coerceAtLeast(0) / 1000
return if (s >= 3600) "%d:%02d:%02d".format(s / 3600, s / 60 % 60, s % 60) else "%d:%02d".format(s / 60, s % 60)
}
fun bytes(value: Long): String = if (value >= 1024L * 1024 * 1024) "%.1f GB".format(value / (1024.0 * 1024 * 1024)) else "%.1f MB".format(value / (1024.0 * 1024))
}
+5
View File
@@ -0,0 +1,5 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#0C121C" android:pathData="M0,0h108v108h-108z" />
<path android:fillColor="#64E3BE" android:pathData="M25,24Q25,17 32,20L84,48Q94,54 84,60L32,88Q25,91 25,84Z" />
<path android:fillColor="#0C121C" android:pathData="M36,38L66,54L36,70Z" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<resources>
<string name="app_name">同同影音</string>
<string name="app_tagline">你的媒体,随处播放</string>
</resources>
+13
View File
@@ -0,0 +1,13 @@
<resources>
<style name="Theme.TTVideo" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:statusBarColor">#0C121C</item>
<item name="android:navigationBarColor">#0C121C</item>
<item name="android:windowBackground">#0C121C</item>
<item name="colorAccent">#64E3BE</item>
<item name="android:colorAccent">#64E3BE</item>
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowSoftInputMode">adjustResize</item>
</style>
</resources>
@@ -0,0 +1,8 @@
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" path="."/><exclude domain="file" path="."/><exclude domain="database" path="."/><exclude domain="sharedpref" path="."/>
</cloud-backup>
<device-transfer>
<exclude domain="root" path="."/><exclude domain="file" path="."/><exclude domain="database" path="."/><exclude domain="sharedpref" path="."/>
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,33 @@
package com.ttstd.player.app
import com.ttstd.player.api.*
import com.ttstd.player.library.LibraryEntry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class RecentStoreTest {
@Test fun signedLinkSettingsAndSubtitlesSurviveProcessRestoration() {
val ref = MediaRef("测试视频", uri = "https://host/movie?token=secret",
headers = mapOf("Authorization" to "Bearer secret"), sourceType = MediaSourceType.HLS,
network = NetworkOptions(4000, 12000, 15000, RtspTransport.TCP),
extraSubtitles = listOf(ExternalSubtitle("content://subtitles/1", "application/x-subrip", "zh", true)))
val item = RecentMedia(ref, 43210, 99999, 123456, true)
assertEquals(item, RecentStore.decode(RecentStore.encode(item)))
assertFalse(ref.toString().contains("secret"))
assertFalse(ref.toString().contains("host"))
}
@Test fun sourceIdentityRetainsVersionAndServerResumeWithoutTemporaryUrl() {
val ref = MediaRef("影片", "account-1", LibraryEntry("/movie.mp4", "影片", false, 12345, "etag-2", 8000))
val restored = RecentStore.decode(RecentStore.encode(RecentMedia(ref, 9000)))
assertEquals(ref, restored.ref)
assertEquals(ref.id, restored.ref.id)
assertNull(restored.ref.uri)
assertNotEquals(ref.id, ref.copy(accountId = "another-account").id)
}
}