Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ MetaTube 地址与访问令牌经 `MetaTubeSync` 使用账号密码派生的密

双端音视频解码均基于 `libmpv`,实现 `commonMain` 的统一薄接口 `PlaybackBackend`,播放控制界面共用无状态的 `MobilePlayerControls`(支持四态 `PlayerLayoutPrefs` 自定义:`VideoLandscape`、`VideoPortrait`、`ClipsLandscape`、`ClipsPortrait` 与 `ListenLayoutConfig` / `PlayerGestureConfig` / `PlayerStatusBarConfig`,经 `LocalPlayerLayoutPrefs` 注入并跨设备同步;提供半透明微光胶囊控件簇、可按项自定义时钟/网络/电量/图标的全屏系统状态胶囊 `PlayerSystemStatusCapsule`、长按/拖拽边缘锁定的倍速转盘 `SpeedDialOverlay` 及 `∞` 快速拖览预览 `RapidScrubPreview`、绘制阶段读取的 `PlayerSeekBar` 与随倍速联动的可选 30fps 波浪轨道及悬停/拖动共享缩略图缓存 `ScrubFrameCache`、零高频重组的 `LongArray(1)` 鼠标活跃计时、统一多标签 `PlayerSideSheet` 选集/轨道/字幕外观(`PlayerSheet.SubtitleStyle`,由 `SubtitleStylePrefs` 与 `PikoPlatform.listSubtitleFonts()` 驱动并实时生效且跨设备同步)/设置/统计面板与一键复制诊断信息;遵循单一入口原则按宽窄与触屏/键鼠分流播放键与设置入口,垂直手势调节能力由平台 `PlayerLevelControl` 提供)以及面向音频文件(`isPlayableAudio()`)与「听视频」模式的 `ListenScreen`(黑胶转盘旋转拖动定位、30fps 惯性停转受 `LocalWindowVisible` 与减少动画门控、睡眠定时与双栏/抽屉队列):

- **Android 主播放器双指缩放(`VideoZoom`)**:双指捏合在 1x–4x 间缩放画面并跟随两指平移,放大后单指拖动改为平移画面(不再触发横划进退),缩放读数由 `PlayerZoomHud` 展示,底部「还原画面」胶囊与既有区域裁剪共用,一键回到 1x 与适应屏幕。缩放经 `PlaybackBackend.setVideoZoom` 下发;Android 13+ 由 `VideoZoomSurfaceTransform` 直接对 `SurfaceView` 的 `SurfaceControl` 施加 `setScale`/`setPosition`,由系统合成器按屏幕刷新率生效,与视频帧率解耦,mpv 只保留 `Fit`/`Crop`/`RegionCrop` 的基准画面;Android 12 及以下回退到 mpv `video-zoom` / `video-pan-*`(`Stretch` 下 mpv 禁用平移,不支持缩放)。换集、换画质、换画面比例与旋转时复位或按新尺寸重新钳制;iOS 与桌面后端暂未实现,默认 `supportsVideoZoom = false`。

- **Android 端**:采用预编译的 `dev.jdtech.mpv:libmpv`,适配层为 `MpvPlaybackBackend` 与 `MpvVideoSurface`,以应用内压栈页 `VideoPlayerHost.InApp` 承载,系统亮度、媒体音量、屏幕方向与系统栏控制位于 `PlayerSystemControls`,全屏电量/网络状态由 `AndroidSystemStatus` 冷流按需采集。进入音频/听视频模式时调用 `MpvPlaybackBackend.setAudioOnlyMode(true)` 切为纯音频输出(`vid=no`、`vo=null`),释放 `FLAG_KEEP_SCREEN_ON` 并在 `ON_STOP` 锁屏息屏时保持后台续播。(不使用 MediaMP 的 Android mpv 后端:其 Compose 渲染表面为空实现且未发布 `.so` 原生库。)
- **桌面端**:采用 MediaMP `0.5.3` 的 mpv 后端(`MediampPlaybackBackend`)配自研 `PikoMpvVideoSurface` 经 Skiko `0.156.1` `FrameDriver` / `Direct3DRenderer` 零拷贝渲染(含软件回退),以独立窗口 `VideoPlayerWindow`(`VideoPlayerHost.Detached`,集成最小化/最大化/置顶/关闭顶栏、macOS 无双标题栏适配、Windows `WindowsSmtcSession` 系统媒体控制与 `WindowsSystemStatus` 全屏状态采集,并受 `Main.kt` 守护 `startExitWatchdog()` 保护以防原生卸载卡死退出)承载,支持边播放边浏览网盘;悬停/拖动缩略图预览由桌面端 FFM `PreviewFrameDecoder` 解码并复用于 `ScrubFrameCache`。
- **iOS 端**:采用原生 `AVPlayerViewController`(`IosVideoPlayerHost`,接入 `AVAudioSessionCategoryPlayback`、画中画、本地+云端续播与 `PlayHistoryReporter` 上报、按有效语言自动匹配内封字幕及全屏模态信息流弹出)与 `AVPlayer` + `AVPlayerLayer`(`IosVideoPreviewSupport`)承载信息流与片段预览;`IosAvPlayerMediaBridge` 将回环代理的原始 MPEG-TS 转码/切片流包装为内存 HLS VOD(`.m3u8` + `video/mp2t`)并补全非 TS 流的精确 MIME 类型,兼容 iOS 15–27+。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,10 @@ fun MediampVideoPlayerScreen(
onSpeedChange = state::setSpeed,
onAspectRatioChange = state::setAspectRatio,
onCropRegionChange = state::setCropRegion,
videoZoomProvider = state::videoZoom,
isVideoZoomed = state.isVideoZoomed,
supportsVideoZoom = state.supportsVideoZoom,
onVideoZoomChange = state::setVideoZoom,
onQualityChange = state::selectQuality,
onRetry = state::retry,
onRestartFromBeginning = state::restartFromBeginning,
Expand Down
236 changes: 191 additions & 45 deletions app/src/main/kotlin/dev/piko/ui/screens/player/MpvPlaybackBackend.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import dev.piko.shared.i18n.tr

import android.content.Context
import android.net.Uri
import android.os.Build
import android.view.Surface
import android.view.SurfaceView
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableLongStateOf
Expand All @@ -25,7 +27,10 @@ import dev.piko.shared.media.player.PlaybackTarget
import dev.piko.shared.media.player.PlayerAspectRatio
import dev.piko.shared.media.player.SubtitleFontPreset
import dev.piko.shared.media.player.SubtitleStylePrefs
import dev.piko.shared.media.player.VideoContentRect
import dev.piko.shared.media.player.VideoCropRegion
import dev.piko.shared.media.player.VideoZoom
import dev.piko.shared.media.player.videoContentRect
import dev.piko.shared.media.player.mpvSubtitleAddCommands
import dev.piko.shared.media.player.mpvSubtitleCodepage
import dev.piko.shared.media.player.mpvSubtitleLanguages
Expand Down Expand Up @@ -90,6 +95,23 @@ internal class MpvPlaybackBackend(
override val aspectRatio: PlayerAspectRatio get() = currentAspectRatio
private var currentCropRegion by mutableStateOf<VideoCropRegion?>(null)
override val cropRegion: VideoCropRegion? get() = currentCropRegion
private var currentVideoZoom = VideoZoom.Reset
override val videoZoom: VideoZoom get() = currentVideoZoom
private var videoZoomed by mutableStateOf(false)
override val isVideoZoomed: Boolean get() = videoZoomed
override val supportsVideoZoom: Boolean = true
// Android 13+ 把双指缩放交给 SurfaceControl 合成,脱离视频帧率;旧系统仍由 mpv 属性实现
private val surfaceZoomTransform: VideoZoomSurfaceTransform? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) VideoZoomSurfaceTransform() else null
// 逐帧双指手势只更新普通字段与待写几何,不写 Compose 状态,避免每帧重组整块播放控件
private val geometryLock = Any()
private var pendingGeometry: VideoGeometry? = null
private var geometryQueued = false
// 只在 mpv 线程读写:与上一次真正写进 mpv 的值比较,未变的属性不重复下发
private var lastWrittenGeometry: VideoGeometry? = null
// 画面表面尺寸,双指缩放用它换算平移边界;在 Surface 回调与布局回调里更新
private var surfaceWidth = 0
private var surfaceHeight = 0
override var videoAspect by mutableStateOf<Float?>(null)
private set
private var currentVolume by mutableFloatStateOf(1f)
Expand Down Expand Up @@ -268,6 +290,10 @@ internal class MpvPlaybackBackend(
if (released) return
feedback.invalidate()
fileLoaded = false
// 新文件从原始画面开始;mpv 的 video-zoom / video-pan-* 是运行时设置,不随 loadfile 复位
currentVideoZoom = VideoZoom.Reset
updateVideoZoomed(false)
surfaceZoomTransform?.apply(VideoZoom.Reset)
// 段落预览与信息流片段仅关闭字幕轨(sid=no,音轨仍保留),无需挂载外挂字幕
pendingSubtitles = if (preview) emptyList() else subtitles
val rawTargetLocator = when (target) {
Expand Down Expand Up @@ -311,6 +337,12 @@ internal class MpvPlaybackBackend(
}
}
mpv.setPropertyBoolean("pause", !playWhenReady)
// 直接复位而不是走 applyVideoGeometry:换片时可能还排着上一部片的几何写入,
// 这里同时清掉比较基线,保证新文件第一帧就是原始画面
lastWrittenGeometry = null
mpv.setPropertyDouble("video-zoom", 0.0)
mpv.setPropertyDouble("video-pan-x", 0.0)
mpv.setPropertyDouble("video-pan-y", 0.0)
}
positionMillis = startMillis.coerceAtLeast(0L)
durationMillis = 0L
Expand Down Expand Up @@ -466,51 +498,16 @@ internal class MpvPlaybackBackend(

override fun setAspectRatio(mode: PlayerAspectRatio) {
if (released) return
val region = currentCropRegion ?: VideoCropRegion().also { if (mode == PlayerAspectRatio.RegionCrop) currentCropRegion = it }
onMpv {
when (mode) {
PlayerAspectRatio.Fit -> {
mpv.setPropertyString("keepaspect", "yes")
mpv.setPropertyDouble("panscan", 0.0)
mpv.setPropertyDouble("video-zoom", 0.0)
mpv.setPropertyDouble("video-pan-x", 0.0)
mpv.setPropertyDouble("video-pan-y", 0.0)
}

PlayerAspectRatio.Crop -> {
mpv.setPropertyString("keepaspect", "yes")
mpv.setPropertyDouble("panscan", 1.0)
mpv.setPropertyDouble("video-zoom", 0.0)
mpv.setPropertyDouble("video-pan-x", 0.0)
mpv.setPropertyDouble("video-pan-y", 0.0)
}

PlayerAspectRatio.Stretch -> {
mpv.setPropertyString("keepaspect", "no")
mpv.setPropertyDouble("panscan", 0.0)
mpv.setPropertyDouble("video-zoom", 0.0)
mpv.setPropertyDouble("video-pan-x", 0.0)
mpv.setPropertyDouble("video-pan-y", 0.0)
}

PlayerAspectRatio.RegionCrop -> {
val vAspect = videoAspect?.takeIf { it.isFinite() && it > 0f } ?: (16f / 9f)
val cAspect = region.safeContainerAspect.takeIf { it > 0f } ?: vAspect
val fitW = if (cAspect > vAspect) vAspect / cAspect else 1f
val fitH = if (cAspect > vAspect) 1f else cAspect / vAspect
val scale = maxOf(1f / (fitW * region.width), 1f / (fitH * region.height))
val zoom = ln(scale.toDouble()) / ln(2.0)
val panX = (0.5f - region.centerX).toDouble()
val panY = (0.5f - region.centerY).toDouble()
mpv.setPropertyString("keepaspect", "yes")
mpv.setPropertyDouble("panscan", 0.0)
mpv.setPropertyDouble("video-zoom", zoom)
mpv.setPropertyDouble("video-pan-x", panX)
mpv.setPropertyDouble("video-pan-y", panY)
}
if (mode != currentAspectRatio) {
if (mode == PlayerAspectRatio.RegionCrop && currentCropRegion == null) {
currentCropRegion = VideoCropRegion()
}
// 换画面比例时回到原始画面:不同比例的裁切基准不同,沿用旧缩放会看起来像凭空放大
currentVideoZoom = VideoZoom.Reset
updateVideoZoomed(false)
}
currentAspectRatio = mode
applyVideoGeometry()
}

override fun setCropRegion(region: VideoCropRegion?) {
Expand All @@ -523,6 +520,144 @@ internal class MpvPlaybackBackend(
}
}

override fun setVideoZoom(zoom: VideoZoom) {
if (released) return
val clamped = zoom.clampedTo(currentContentRect())
if (currentVideoZoom == clamped) return
currentVideoZoom = clamped
updateVideoZoomed(clamped.isZoomed)
applyVideoGeometry()
}

private fun updateVideoZoomed(zoomed: Boolean) {
if (videoZoomed != zoomed) videoZoomed = zoomed
}

fun attachZoomSurface(view: SurfaceView) {
if (surfaceZoomTransform == null) return
surfaceZoomTransform.attach(view)
applyVideoGeometry()
}

fun detachZoomSurface() {
val transform = surfaceZoomTransform ?: return
transform.detach()
applyVideoGeometry()
}

private fun currentContentRect(): VideoContentRect? = videoContentRect(
aspectRatio = currentAspectRatio,
videoAspect = videoAspect,
viewportWidth = surfaceWidth.toFloat(),
viewportHeight = surfaceHeight.toFloat(),
cropRegion = currentCropRegion,
)

/**
* 把画面比例模式与双指缩放一起换算成 mpv 的 `keepaspect` / `panscan` / `video-zoom` / `video-pan-*`。
*
* mpv 的 `video-pan-*` 以缩放后的画面尺寸为 1,而 [VideoZoom] 的平移量以视口为 1,
* 因此按「画面基础比例 × 缩放倍数」换算。`Stretch` 下 mpv 不做缩放平移,直接回到原始画面。
*
* 手势每帧都会调用这里:只把最新几何留在待写槽位,mpv 线程来不及消费的中间帧直接覆盖,
* 不会在调用队列里堆出几十帧延迟。
*/
private fun applyVideoGeometry() {
if (released) return
val mode = currentAspectRatio
val region = if (mode == PlayerAspectRatio.RegionCrop) currentCropRegion else null
val zoom = currentVideoZoom
val content = currentContentRect()
val baseZoom = region?.let(::regionZoom) ?: 0.0
val basePanX = region?.let { (0.5f - it.centerX).toDouble() } ?: 0.0
val basePanY = region?.let { (0.5f - it.centerY).toDouble() } ?: 0.0
val userScale = if (mode == PlayerAspectRatio.Stretch) VideoZoom.MIN_SCALE else zoom.scale
// 有 SurfaceControl 时用户缩放交给系统合成器,mpv 只负责画面比例与区域裁剪,避免两层缩放叠加
val surfaceTransform = surfaceZoomTransform?.takeIf { it.isReady }
val scale = if (surfaceTransform != null) VideoZoom.MIN_SCALE else userScale
val scaledZoom = baseZoom + ln(scale.toDouble()) / ln(2.0)
val panX = if (surfaceTransform == null && content != null && content.widthFraction > 0f) {
basePanX + zoom.panX / (content.widthFraction * scale)
} else {
basePanX
}
val panY = if (surfaceTransform == null && content != null && content.heightFraction > 0f) {
basePanY + zoom.panY / (content.heightFraction * scale)
} else {
basePanY
}
queueVideoGeometry(
VideoGeometry(
keepAspect = mode != PlayerAspectRatio.Stretch,
panscan = if (mode == PlayerAspectRatio.Crop) 1.0 else 0.0,
zoom = scaledZoom,
panX = panX,
panY = panY,
),
)
surfaceZoomTransform?.apply(
if (surfaceTransform != null && mode != PlayerAspectRatio.Stretch) {
VideoZoom(scale = userScale, panX = zoom.panX, panY = zoom.panY)
} else {
VideoZoom.Reset
},
)
}

private fun queueVideoGeometry(geometry: VideoGeometry) {
synchronized(geometryLock) {
pendingGeometry = geometry
if (geometryQueued) return
geometryQueued = true
}
onMpv {
val latest = synchronized(geometryLock) {
val next = pendingGeometry
pendingGeometry = null
geometryQueued = false
next
} ?: return@onMpv
writeVideoGeometry(latest)
}
}

private fun writeVideoGeometry(geometry: VideoGeometry) {
val previous = lastWrittenGeometry
lastWrittenGeometry = geometry
if (previous == null || previous.keepAspect != geometry.keepAspect) {
mpv.setPropertyString("keepaspect", if (geometry.keepAspect) "yes" else "no")
}
if (previous == null || previous.panscan != geometry.panscan) {
mpv.setPropertyDouble("panscan", geometry.panscan)
}
if (previous == null || previous.zoom != geometry.zoom) {
mpv.setPropertyDouble("video-zoom", geometry.zoom)
}
if (previous == null || previous.panX != geometry.panX) {
mpv.setPropertyDouble("video-pan-x", geometry.panX)
}
if (previous == null || previous.panY != geometry.panY) {
mpv.setPropertyDouble("video-pan-y", geometry.panY)
}
}

private data class VideoGeometry(
val keepAspect: Boolean,
val panscan: Double,
val zoom: Double,
val panX: Double,
val panY: Double,
)

private fun regionZoom(region: VideoCropRegion): Double {
val vAspect = videoAspect?.takeIf { it.isFinite() && it > 0f } ?: (16f / 9f)
val cAspect = region.safeContainerAspect.takeIf { it > 0f } ?: vAspect
val fitW = if (cAspect > vAspect) vAspect / cAspect else 1f
val fitH = if (cAspect > vAspect) 1f else cAspect / vAspect
val scale = maxOf(1f / (fitW * region.width), 1f / (fitH * region.height))
return ln(scale.toDouble()) / ln(2.0)
}

override fun setVolume(volume: Float) {
onMpv { mpv.setPropertyDouble("volume", volume.coerceIn(0f, 1f) * 100.0) }
}
Expand Down Expand Up @@ -605,6 +740,10 @@ internal class MpvPlaybackBackend(
fun attachSurface(surface: Surface, initialWidth: Int = 0, initialHeight: Int = 0) {
if (released) return
attachedSurface = surface
if (initialWidth > 0 && initialHeight > 0) {
surfaceWidth = initialWidth
surfaceHeight = initialHeight
}
val restoreVideoOutput = videoOutputDisabled
surfaceAttached = true
videoOutputDisabled = false
Expand All @@ -631,6 +770,9 @@ internal class MpvPlaybackBackend(

fun setSurfaceSize(width: Int, height: Int) {
if (released || !surfaceAttached) return
val resized = width != surfaceWidth || height != surfaceHeight
surfaceWidth = width
surfaceHeight = height
onMpv {
mpv.setPropertyString("android-surface-size", "${width}x$height")
if (needsPausedRedrawOnResize) {
Expand All @@ -641,6 +783,11 @@ internal class MpvPlaybackBackend(
}
}
}
// 视口比例变了,平移上限与 mpv 的平移单位一起变,按新尺寸重新钳制并下发
if (resized && currentVideoZoom.isZoomed) {
currentVideoZoom = currentVideoZoom.clampedTo(currentContentRect())
applyVideoGeometry()
}
}

/** 在 [setSurfaceSize] 之后调用:等 mpv 按新尺寸交出一帧,再在主线程调用 [onShown]。见 [SurfaceRedrawGate]。 */
Expand Down Expand Up @@ -970,9 +1117,8 @@ internal class MpvPlaybackBackend(
private fun updateVideoAspect() {
val aspect = rawAspect?.takeIf { it > 0.0 } ?: return
videoAspect = if (rotateDegrees % 180L == 0L) aspect.toFloat() else (1.0 / aspect).toFloat()
if (currentAspectRatio == PlayerAspectRatio.RegionCrop) {
setAspectRatio(PlayerAspectRatio.RegionCrop)
}
// 画面宽高比变了,裁切基准与平移换算都要跟着重算;区域裁剪的缩放也在这里重新叠加
applyVideoGeometry()
}

private companion object {
Expand Down
Loading
Loading