初始化 TTVideoPlayer 工程:模块化播放框架、同同影音 App 与文档
Media3 内核播放框架(player-api/core/media3/source/render/lifecycle/telemetry)、 WebDAV/SMB/Jellyfin 来源、DLNA/Google Cast 投屏、RTMP 原生库与完整 App。
This commit is contained in:
commit
922ec80bcc
147 files changed
+20169
No files matched your search
@@ -0,0 +1 @@
|
||||
<manifest />
|
||||
@@ -0,0 +1,265 @@
|
||||
@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||
|
||||
package com.ttstd.player.media3
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.Surface
|
||||
import androidx.media3.common.*
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.analytics.AnalyticsListener
|
||||
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
|
||||
import com.ttstd.player.api.*
|
||||
import com.ttstd.player.android.AndroidVideoOutput
|
||||
import com.ttstd.player.core.PlaybackValidation
|
||||
import com.ttstd.player.core.SourceRouting
|
||||
import com.ttstd.player.media3.source.Media3Sources
|
||||
import com.ttstd.player.media3.source.Media3TransportRegistry
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** Android 主线程创建;命令自动切回主线程串行执行。
|
||||
* 仅持有 Application Context。位置每秒采样,避免低端机频繁唤醒。
|
||||
* 不集成通用 FFmpeg 视频软解;强制软解仅筛选系统已提供的软件 MediaCodec。
|
||||
*/
|
||||
class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
private val context = context.applicationContext
|
||||
private val mutableState = MutableStateFlow(PlaybackState())
|
||||
private val mutableEvents = MutableSharedFlow<PlaybackEvent>(extraBufferCapacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST)
|
||||
override val state = mutableState.asStateFlow()
|
||||
override val events = mutableEvents.asSharedFlow()
|
||||
override val capabilities = PlayerCapabilities("Media3", DecodeMode.entries.toSet(), DecodeMode.entries.toSet(), sourceTypes = MediaSourceType.entries.toSet())
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var released = false
|
||||
private var request: PlaybackRequest? = null
|
||||
private var policy = DecodePolicy()
|
||||
private var surface: Surface? = null
|
||||
private var startedAt = 0L
|
||||
private var firstFrame = false
|
||||
private var lastError: PlaybackError? = null
|
||||
private var subtitleLines: List<String> = emptyList()
|
||||
private var player: ExoPlayer
|
||||
|
||||
private val listener = object : Player.Listener {
|
||||
override fun onEvents(player: Player, events: Player.Events) {
|
||||
publish()
|
||||
handler.removeCallbacks(ticker)
|
||||
if (player.isPlaying) handler.postDelayed(ticker, 1000)
|
||||
}
|
||||
override fun onPlaybackStateChanged(playbackState: Int) {
|
||||
if (playbackState == Player.STATE_ENDED) emit(PlaybackEvent.Ended)
|
||||
}
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
// 不透传内核 message/cause:其中可能包含带 token 的媒体地址。
|
||||
val message = when (error.errorCode) {
|
||||
PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, PlaybackException.ERROR_CODE_DECODING_FAILED,
|
||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED, PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES ->
|
||||
"设备无法解码此视频,可更换解码方式或使用媒体服务转码"
|
||||
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
|
||||
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT -> "媒体连接失败,请检查网络或重新打开来源"
|
||||
else -> "播放失败,请检查媒体、来源和设备解码能力"
|
||||
}
|
||||
lastError = PlaybackError(error.errorCodeName, message)
|
||||
emit(PlaybackEvent.Error(lastError!!))
|
||||
publish()
|
||||
}
|
||||
override fun onVideoSizeChanged(size: VideoSize) {
|
||||
emit(PlaybackEvent.VideoSize(size.width, size.height, size.pixelWidthHeightRatio))
|
||||
}
|
||||
override fun onCues(cueGroup: androidx.media3.common.text.CueGroup) {
|
||||
subtitleLines = cueGroup.cues.mapNotNull { it.text?.toString() }
|
||||
publish()
|
||||
}
|
||||
}
|
||||
private val analytics = object : AnalyticsListener {
|
||||
override fun onRenderedFirstFrame(eventTime: AnalyticsListener.EventTime, output: Any, renderTimeMs: Long) {
|
||||
if (!firstFrame) {
|
||||
firstFrame = true
|
||||
emit(PlaybackEvent.FirstFrame)
|
||||
emit(PlaybackEvent.StartupTime(SystemClock.elapsedRealtime() - startedAt))
|
||||
}
|
||||
}
|
||||
override fun onVideoDecoderInitialized(eventTime: AnalyticsListener.EventTime, decoderName: String, initializedTimestampMs: Long, initializationDurationMs: Long) {
|
||||
decoder(TrackType.VIDEO, decoderName)
|
||||
}
|
||||
override fun onAudioDecoderInitialized(eventTime: AnalyticsListener.EventTime, decoderName: String, initializedTimestampMs: Long, initializationDurationMs: Long) {
|
||||
decoder(TrackType.AUDIO, decoderName)
|
||||
}
|
||||
override fun onDroppedVideoFrames(eventTime: AnalyticsListener.EventTime, droppedFrames: Int, elapsedMs: Long) {
|
||||
emit(PlaybackEvent.DroppedFrames(droppedFrames, elapsedMs))
|
||||
}
|
||||
}
|
||||
|
||||
private val ticker: Runnable = object : Runnable {
|
||||
override fun run() {
|
||||
if (!released && player.isPlaying) { publish(); handler.postDelayed(this, 1000) }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
checkMain()
|
||||
player = buildPlayer()
|
||||
}
|
||||
|
||||
private fun buildPlayer(): ExoPlayer {
|
||||
val selector = MediaCodecSelector { mime, secure, tunneling ->
|
||||
val mode = if (mime.startsWith("video/")) policy.video else policy.audio
|
||||
val codecs = MediaCodecSelector.DEFAULT.getDecoderInfos(mime, secure, tunneling)
|
||||
when (mode) {
|
||||
DecodeMode.AUTO -> codecs
|
||||
DecodeMode.PREFER_HARDWARE -> codecs.sortedByDescending { it.hardwareAccelerated }
|
||||
DecodeMode.HARDWARE_ONLY -> codecs.filter { it.hardwareAccelerated }
|
||||
DecodeMode.SOFTWARE_ONLY -> codecs.filter { it.softwareOnly }
|
||||
}
|
||||
}
|
||||
// fallback 仅处理可用解码器初始化回退,不承诺运行中错误自动软解。
|
||||
val renderers = DefaultRenderersFactory(context).setMediaCodecSelector(selector).setEnableDecoderFallback(true)
|
||||
return ExoPlayer.Builder(context, renderers).build().also {
|
||||
it.setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
|
||||
it.setHandleAudioBecomingNoisy(true)
|
||||
it.addListener(listener)
|
||||
it.addAnalyticsListener(analytics)
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
load(this.request!!)
|
||||
CommandResult.Accepted
|
||||
}
|
||||
|
||||
private fun load(request: PlaybackRequest) {
|
||||
subtitleLines = emptyList()
|
||||
lastError = null
|
||||
firstFrame = false
|
||||
startedAt = SystemClock.elapsedRealtime()
|
||||
player.setMediaSource(Media3Sources(context).create(request), request.startPositionMs)
|
||||
player.playWhenReady = request.autoplay
|
||||
player.prepare()
|
||||
}
|
||||
|
||||
override suspend fun play() = command { player.play(); CommandResult.Accepted }
|
||||
override suspend fun pause() = command { player.pause(); CommandResult.Accepted }
|
||||
override suspend fun seekTo(positionMs: Long) = command {
|
||||
if (positionMs < 0) CommandResult.InvalidArgument("位置不能为负")
|
||||
else if (!player.isCurrentMediaItemSeekable) CommandResult.Unsupported("当前媒体不可 seek")
|
||||
else { player.seekTo(positionMs); CommandResult.Accepted }
|
||||
}
|
||||
override suspend fun setSpeed(speed: Float) = command {
|
||||
if (!speed.isFinite() || speed !in 0.25f..4f) CommandResult.InvalidArgument("倍速范围为 0.25–4")
|
||||
else { player.setPlaybackSpeed(speed); CommandResult.Accepted }
|
||||
}
|
||||
override suspend fun setVolume(volume: Float) = command {
|
||||
if (!volume.isFinite() || volume !in 0f..1f) CommandResult.InvalidArgument("音量范围为 0–1")
|
||||
else { player.volume = volume; CommandResult.Accepted }
|
||||
}
|
||||
override suspend fun selectTrack(selection: TrackSelection) = command {
|
||||
val type = selection.type.media3Type()
|
||||
val builder = player.trackSelectionParameters.buildUpon().clearOverridesOfType(type).setTrackTypeDisabled(type, selection.disabled)
|
||||
if (!selection.disabled && selection.id != null) {
|
||||
val target = player.currentTracks.groups.withIndex().firstNotNullOfOrNull { (groupIndex, group) ->
|
||||
(0 until group.length).firstOrNull { "$groupIndex:$it" == selection.id && group.type == type && group.isTrackSupported(it) }
|
||||
?.let { TrackSelectionOverride(group.mediaTrackGroup, listOf(it)) }
|
||||
} ?: return@command CommandResult.InvalidArgument("轨道不存在或设备不支持")
|
||||
builder.setOverrideForType(target)
|
||||
}
|
||||
player.trackSelectionParameters = builder.build()
|
||||
CommandResult.Accepted
|
||||
}
|
||||
override suspend fun setDecodePolicy(policy: DecodePolicy) = command {
|
||||
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)
|
||||
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()
|
||||
player = buildPlayer()
|
||||
player.setPlaybackSpeed(speed)
|
||||
player.volume = volume
|
||||
player.playWhenReady = playWhenReady
|
||||
player.trackSelectionParameters = tracks
|
||||
surface?.takeIf { it.isValid }?.let { player.setVideoSurface(it) }
|
||||
saved?.let { load(it) }
|
||||
CommandResult.Accepted
|
||||
}
|
||||
|
||||
override fun attachSurface(surface: Surface): CommandResult {
|
||||
checkMain()
|
||||
if (released) return CommandResult.Released
|
||||
if (!surface.isValid) return CommandResult.InvalidArgument("Surface 已失效")
|
||||
this.surface = surface
|
||||
player.setVideoSurface(surface)
|
||||
return CommandResult.Accepted
|
||||
}
|
||||
override fun detachSurface(surface: Surface) {
|
||||
checkMain()
|
||||
if (!released && this.surface === surface) { player.clearVideoSurface(surface); this.surface = null }
|
||||
}
|
||||
// 清理不能因调用方 lifecycleScope 取消而被跳过。
|
||||
override suspend fun release() = withContext(Dispatchers.Main.immediate + kotlinx.coroutines.NonCancellable) {
|
||||
if (!released) {
|
||||
released = true
|
||||
handler.removeCallbacks(ticker)
|
||||
player.removeListener(listener)
|
||||
player.removeAnalyticsListener(analytics)
|
||||
player.release()
|
||||
surface = null
|
||||
mutableState.value = PlaybackState(phase = PlaybackPhase.RELEASED)
|
||||
}
|
||||
}
|
||||
private suspend fun command(block: () -> CommandResult): CommandResult = withContext(Dispatchers.Main.immediate) {
|
||||
if (released) return@withContext CommandResult.Released
|
||||
try { block().also { publish() } }
|
||||
catch (_: Exception) {
|
||||
val error = PlaybackError("COMMAND_FAILED", "播放命令执行失败")
|
||||
emit(PlaybackEvent.Error(error))
|
||||
CommandResult.Failed(error)
|
||||
}
|
||||
}
|
||||
private fun publish() {
|
||||
if (released) return
|
||||
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
|
||||
Player.STATE_ENDED -> PlaybackPhase.ENDED
|
||||
else -> PlaybackPhase.IDLE
|
||||
}
|
||||
val tracks = player.currentTracks.groups.flatMapIndexed { g, group ->
|
||||
val type = when (group.type) { C.TRACK_TYPE_VIDEO -> TrackType.VIDEO; C.TRACK_TYPE_AUDIO -> TrackType.AUDIO; C.TRACK_TYPE_TEXT -> TrackType.TEXT; else -> null }
|
||||
if (type == null) emptyList() else (0 until group.length).map { t ->
|
||||
val f = group.getTrackFormat(t)
|
||||
MediaTrack("$g:$t", type, f.label, f.language, group.isTrackSelected(t))
|
||||
}
|
||||
}
|
||||
mutableState.value = PlaybackState(phase, player.playWhenReady, player.isPlaying, player.currentPosition.coerceAtLeast(0),
|
||||
player.duration.takeIf { it != C.TIME_UNSET && it >= 0 }, player.bufferedPosition.coerceAtLeast(0), tracks, lastError, subtitleLines)
|
||||
}
|
||||
private fun decoder(type: TrackType, name: String) {
|
||||
// API 29 起使用平台分类;旧系统不能可靠从名字推断,保留 unknown。
|
||||
val hardware = if (android.os.Build.VERSION.SDK_INT >= 29) runCatching {
|
||||
android.media.MediaCodecList(android.media.MediaCodecList.ALL_CODECS)
|
||||
.codecInfos.firstOrNull { it.name == name }?.isHardwareAccelerated
|
||||
}.getOrNull() else null
|
||||
emit(PlaybackEvent.DecoderChanged(type, name, hardware))
|
||||
}
|
||||
private fun emit(event: PlaybackEvent) { mutableEvents.tryEmit(event) }
|
||||
private fun checkMain() { check(Looper.myLooper() == Looper.getMainLooper()) { "必须在主线程创建或绑定输出" } }
|
||||
private fun TrackType.media3Type() = when (this) { TrackType.VIDEO -> C.TRACK_TYPE_VIDEO; TrackType.AUDIO -> C.TRACK_TYPE_AUDIO; TrackType.TEXT -> C.TRACK_TYPE_TEXT }
|
||||
}
|
||||
|
||||
/** 应在主线程调用 create;工厂不会复用播放器实例。 */
|
||||
class Media3EngineFactory(context: Context) : PlayerEngineFactory {
|
||||
private val applicationContext = context.applicationContext
|
||||
override fun create(): PlayerEngine = Media3Engine(applicationContext)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ttstd.player.media3
|
||||
|
||||
import com.ttstd.player.api.*
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/** 不加载网络或媒体,验证真实适配器命令边界与资源释放;解码能力仍需真机。 */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class Media3EngineTest {
|
||||
@Test fun invalidRequestDoesNotStartPlayback() = runBlocking {
|
||||
val engine = Media3Engine(RuntimeEnvironment.getApplication())
|
||||
try {
|
||||
assertTrue(engine.prepare(PlaybackRequest("relative.mp4")) is CommandResult.InvalidArgument)
|
||||
assertEquals(PlaybackPhase.IDLE, engine.state.value.phase)
|
||||
assertTrue(engine.setSpeed(Float.NaN) is CommandResult.InvalidArgument)
|
||||
assertTrue(engine.setVolume(2f) is CommandResult.InvalidArgument)
|
||||
assertTrue(engine.prepare(PlaybackRequest("srt://host:9000")) is CommandResult.Unsupported)
|
||||
assertEquals(PlaybackPhase.IDLE, engine.state.value.phase)
|
||||
} finally { engine.release() }
|
||||
}
|
||||
@Test fun rebuildPreservesPlaybackIntent() = runBlocking {
|
||||
val engine = Media3Engine(RuntimeEnvironment.getApplication())
|
||||
try {
|
||||
engine.play()
|
||||
assertTrue(engine.state.value.playWhenReady)
|
||||
assertEquals(CommandResult.Accepted, engine.setDecodePolicy(DecodePolicy(video = DecodeMode.SOFTWARE_ONLY)))
|
||||
assertTrue(engine.state.value.playWhenReady)
|
||||
engine.pause()
|
||||
assertFalse(engine.state.value.playWhenReady)
|
||||
} finally { engine.release() }
|
||||
}
|
||||
@Test fun releaseIsIdempotentAndRejectsFurtherCommands() = runBlocking {
|
||||
val engine = Media3Engine(RuntimeEnvironment.getApplication())
|
||||
engine.release()
|
||||
engine.release()
|
||||
assertEquals(PlaybackPhase.RELEASED, engine.state.value.phase)
|
||||
assertEquals(CommandResult.Released, engine.play())
|
||||
assertEquals(CommandResult.Released, engine.prepare(PlaybackRequest("https://example.com/a.mp4")))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user