diff --git a/AGENTS.md b/AGENTS.md index 526e05ae..e0d20679 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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+。 diff --git a/app/src/main/kotlin/dev/piko/ui/screens/player/MediampVideoPlayerScreen.kt b/app/src/main/kotlin/dev/piko/ui/screens/player/MediampVideoPlayerScreen.kt index 2a0f6891..712afc50 100644 --- a/app/src/main/kotlin/dev/piko/ui/screens/player/MediampVideoPlayerScreen.kt +++ b/app/src/main/kotlin/dev/piko/ui/screens/player/MediampVideoPlayerScreen.kt @@ -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, diff --git a/app/src/main/kotlin/dev/piko/ui/screens/player/MpvPlaybackBackend.kt b/app/src/main/kotlin/dev/piko/ui/screens/player/MpvPlaybackBackend.kt index 584fa4fd..f32a29b9 100644 --- a/app/src/main/kotlin/dev/piko/ui/screens/player/MpvPlaybackBackend.kt +++ b/app/src/main/kotlin/dev/piko/ui/screens/player/MpvPlaybackBackend.kt @@ -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 @@ -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 @@ -90,6 +95,23 @@ internal class MpvPlaybackBackend( override val aspectRatio: PlayerAspectRatio get() = currentAspectRatio private var currentCropRegion by mutableStateOf(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(null) private set private var currentVolume by mutableFloatStateOf(1f) @@ -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) { @@ -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 @@ -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?) { @@ -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) } } @@ -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 @@ -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) { @@ -641,6 +783,11 @@ internal class MpvPlaybackBackend( } } } + // 视口比例变了,平移上限与 mpv 的平移单位一起变,按新尺寸重新钳制并下发 + if (resized && currentVideoZoom.isZoomed) { + currentVideoZoom = currentVideoZoom.clampedTo(currentContentRect()) + applyVideoGeometry() + } } /** 在 [setSurfaceSize] 之后调用:等 mpv 按新尺寸交出一帧,再在主线程调用 [onShown]。见 [SurfaceRedrawGate]。 */ @@ -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 { diff --git a/app/src/main/kotlin/dev/piko/ui/screens/player/MpvVideoSurface.kt b/app/src/main/kotlin/dev/piko/ui/screens/player/MpvVideoSurface.kt index 10f1bc2c..f9bb987e 100644 --- a/app/src/main/kotlin/dev/piko/ui/screens/player/MpvVideoSurface.kt +++ b/app/src/main/kotlin/dev/piko/ui/screens/player/MpvVideoSurface.kt @@ -10,6 +10,7 @@ import android.view.View import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.FrameLayout import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.Modifier import androidx.compose.ui.viewinterop.AndroidView @@ -31,6 +32,10 @@ internal fun MpvVideoSurface( modifier = modifier, ) } else { + // 双指缩放用 SurfaceControl 合成,控件销毁时解绑,避免把已销毁的视图留在事务里 + DisposableEffect(backend) { + onDispose { backend.detachZoomSurface() } + } AndroidView( factory = { context -> val cover = View(context).apply { @@ -38,6 +43,7 @@ internal fun MpvVideoSurface( visibility = View.INVISIBLE } val surfaceView = SurfaceView(context).apply { holder.addCallback(SurfaceBridge(backend, cover)) } + backend.attachZoomSurface(surfaceView) FrameLayout(context).apply { addView(surfaceView, MATCH_PARENT, MATCH_PARENT) addView(cover, MATCH_PARENT, MATCH_PARENT) diff --git a/app/src/main/kotlin/dev/piko/ui/screens/player/VideoZoomSurfaceTransform.kt b/app/src/main/kotlin/dev/piko/ui/screens/player/VideoZoomSurfaceTransform.kt new file mode 100644 index 00000000..78788cb9 --- /dev/null +++ b/app/src/main/kotlin/dev/piko/ui/screens/player/VideoZoomSurfaceTransform.kt @@ -0,0 +1,106 @@ +package dev.piko.ui.screens.player + +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.view.SurfaceControl +import android.view.SurfaceHolder +import android.view.SurfaceView +import android.view.View +import androidx.annotation.RequiresApi +import dev.piko.shared.media.player.VideoZoom + +/** + * 把双指缩放直接作用到 SurfaceView 的 SurfaceControl 上,而不是逐帧改 mpv 的 + * `video-zoom` / `video-pan-*`。 + * + * mpv 的画面变换只在输出新视频帧时生效,播放 24fps 影片时拖动会按视频帧率一顿一顿; + * SurfaceControl 的缩放与位移由系统合成器在每次屏幕刷新时应用,和视频帧率解耦,拖动与缩放才能跟手。 + * 仅在 Android 13(API 33)及以上可用,旧系统仍回退到 [MpvPlaybackBackend] 的 mpv 属性实现。 + */ +@RequiresApi(Build.VERSION_CODES.TIRAMISU) +internal class VideoZoomSurfaceTransform { + private var surfaceView: SurfaceView? = null + private var transaction: SurfaceControl.Transaction? = null + @Volatile private var lastZoom: VideoZoom = VideoZoom.Reset + + private val handler = Handler(Looper.getMainLooper()) + private var pendingZoom: VideoZoom? = null + private var drainScheduled = false + + private val drain = Runnable { + drainScheduled = false + val next = pendingZoom + pendingZoom = null + if (next != null) applyNow(next) + } + + private val layoutListener = View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> + applyNow(lastZoom) + } + + private val surfaceCallback = object : SurfaceHolder.Callback { + override fun surfaceCreated(holder: SurfaceHolder) = applyNow(lastZoom) + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = applyNow(lastZoom) + override fun surfaceDestroyed(holder: SurfaceHolder) = Unit + } + + val isReady: Boolean + get() = surfaceView != null + + fun attach(view: SurfaceView) { + if (surfaceView === view) return + detach() + surfaceView = view + view.addOnLayoutChangeListener(layoutListener) + view.holder.addCallback(surfaceCallback) + applyNow(lastZoom) + } + + fun detach() { + val view = surfaceView ?: return + applyNow(VideoZoom.Reset) + view.removeOnLayoutChangeListener(layoutListener) + runCatching { view.holder.removeCallback(surfaceCallback) } + surfaceView = null + pendingZoom = null + handler.removeCallbacks(drain) + drainScheduled = false + transaction?.close() + transaction = null + } + + fun apply(zoom: VideoZoom) { + lastZoom = zoom + if (Looper.myLooper() == Looper.getMainLooper()) { + applyNow(zoom) + } else { + pendingZoom = zoom + if (!drainScheduled) { + drainScheduled = true + handler.post(drain) + } + } + } + + private fun applyNow(zoom: VideoZoom) { + val view = surfaceView ?: return + val width = view.width.toFloat() + val height = view.height.toFloat() + if (width <= 0f || height <= 0f) return + // Surface 正在销毁/重建的瞬间可能拿不到句柄,或事务已失效;下一帧布局或 surfaceCreated 会再补一次 + runCatching { + val surfaceControl = view.surfaceControl ?: return + val location = IntArray(2) + view.getLocationInWindow(location) + val scale = zoom.scale + // setScale 以图层左上角为原点,按图层中心缩放需要同步修正位置,再叠加以视口为 1 的平移量 + val left = location[0] + width * (1f - scale) * 0.5f + zoom.panX * width + val top = location[1] + height * (1f - scale) * 0.5f + zoom.panY * height + val current = transaction ?: SurfaceControl.Transaction().also { transaction = it } + current.setScale(surfaceControl, scale, scale) + current.setPosition(surfaceControl, left, top) + current.apply() + } + } +} diff --git a/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlaybackBackend.kt b/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlaybackBackend.kt index 6e9e6d88..2f929fb5 100644 --- a/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlaybackBackend.kt +++ b/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlaybackBackend.kt @@ -99,6 +99,18 @@ interface PlaybackBackend { val cropRegion: VideoCropRegion? get() = null fun setCropRegion(region: VideoCropRegion?) = Unit + /** 为 false 时手势层不接受双指缩放,控件也不显示缩放还原入口。 */ + val supportsVideoZoom: Boolean get() = false + + /** 当前双指缩放状态,后端不支持时始终为原始画面。 */ + val videoZoom: VideoZoom get() = VideoZoom() + + /** 是否已偏离原始画面。界面只订阅这一个粗粒度状态,避免逐帧手势刷新整块控件。 */ + val isVideoZoomed: Boolean get() = false + + /** 应用双指缩放;缩放与平移按当前画面比例模式换算到后端。 */ + fun setVideoZoom(zoom: VideoZoom) = Unit + /** * 读一个 mpv 属性的字符串值,播放详细信息面板用,见 readPlaybackStats。两端都是 libmpv,属性名通用; * 读不到(还没加载、后端不是 mpv、已释放)时为 null。 diff --git a/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlayerScreenState.kt b/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlayerScreenState.kt index 0392f010..884b03d8 100644 --- a/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlayerScreenState.kt +++ b/shared/src/commonMain/kotlin/dev/piko/shared/media/player/PlayerScreenState.kt @@ -875,6 +875,15 @@ class PlayerScreenState( fun setCropRegion(region: VideoCropRegion?) = backend.setCropRegion(region) + val supportsVideoZoom: Boolean get() = backend.supportsVideoZoom + + val videoZoom: VideoZoom get() = backend.videoZoom + + val isVideoZoomed: Boolean get() = backend.isVideoZoomed + + fun setVideoZoom(zoom: VideoZoom) = backend.setVideoZoom(zoom) + + /** 播放详细信息面板的内容:从哪里读、哪一档,再加 mpv 读得到的编码与缓冲。面板开着时每秒取一次。 */ fun stats(): List { // 走不走本机代理是实现细节,看的人只关心是不是在用流量 diff --git a/shared/src/commonMain/kotlin/dev/piko/shared/media/player/VideoZoom.kt b/shared/src/commonMain/kotlin/dev/piko/shared/media/player/VideoZoom.kt new file mode 100644 index 00000000..458d02b2 --- /dev/null +++ b/shared/src/commonMain/kotlin/dev/piko/shared/media/player/VideoZoom.kt @@ -0,0 +1,127 @@ +package dev.piko.shared.media.player + +import androidx.compose.runtime.Immutable + +/** + * 双指缩放后的画面状态。 + * + * [scale] 以「适应屏幕」时的画面大小为 1;[panX]/[panY] 是画面相对视口中心的位移, + * 以视口宽高为 1,正值表示画面向右、向下移动。平移量按画面基础尺寸与缩放倍数钳制, + * 缩放到 1 倍时强制归零,避免画面在原始状态下被拖出黑边。 + */ +@Immutable +data class VideoZoom( + val scale: Float = MIN_SCALE, + val panX: Float = 0f, + val panY: Float = 0f, +) { + /** 是否已偏离原始画面,控件据此显示还原入口。 */ + val isZoomed: Boolean + get() = scale > MIN_SCALE + EPSILON || panX != 0f || panY != 0f + + fun sanitized(): VideoZoom = VideoZoom( + scale = scale.takeIf { it.isFinite() }?.coerceIn(MIN_SCALE, MAX_SCALE) ?: MIN_SCALE, + panX = panX.takeIf { it.isFinite() } ?: 0f, + panY = panY.takeIf { it.isFinite() } ?: 0f, + ) + + /** + * 把平移量钳制在画面仍能盖住视口的范围内。画面在某个方向仍小于视口时(如竖屏播放横屏视频), + * 该方向不允许平移,始终居中。 + */ + fun clampedTo(content: VideoContentRect?): VideoZoom { + val safe = sanitized() + if (content == null || safe.scale <= MIN_SCALE + EPSILON) { + return VideoZoom(safe.scale) + } + val maxPanX = ((content.widthFraction * safe.scale - 1f) * 0.5f).coerceAtLeast(0f) + val maxPanY = ((content.heightFraction * safe.scale - 1f) * 0.5f).coerceAtLeast(0f) + return VideoZoom( + scale = safe.scale, + panX = safe.panX.coerceIn(-maxPanX, maxPanX), + panY = safe.panY.coerceIn(-maxPanY, maxPanY), + ) + } + + /** + * 双指变换的一步:按住两指的中点缩放,同时跟随两指整体拖动。 + * 传入的坐标都已换算成相对视口中心的归一化位移。 + */ + fun transformedBy( + previousCentroidX: Float, + previousCentroidY: Float, + centroidX: Float, + centroidY: Float, + scaleRatio: Float, + content: VideoContentRect, + ): VideoZoom { + val ratio = scaleRatio.takeIf { it.isFinite() && it > 0f } ?: 1f + val nextScale = (scale * ratio).coerceIn(MIN_SCALE, MAX_SCALE) + val applied = if (scale > 0f) nextScale / scale else 1f + return VideoZoom( + scale = nextScale, + panX = centroidX - applied * (previousCentroidX - panX), + panY = centroidY - applied * (previousCentroidY - panY), + ).clampedTo(content) + } + + /** 单指拖动平移的一步,[dx]/[dy] 以视口宽高为 1。 */ + fun pannedBy(dx: Float, dy: Float, content: VideoContentRect): VideoZoom = + VideoZoom(scale = scale, panX = panX + dx, panY = panY + dy).clampedTo(content) + + companion object { + const val MIN_SCALE = 1f + const val MAX_SCALE = 4f + + private const val EPSILON = 0.001f + + val Reset = VideoZoom() + } +} + +/** + * 画面在视口中的基础尺寸(相对视口),由画面比例模式与视频宽高比决定,用来计算平移边界与缩放锚点。 + * 宽或高大于 1 表示该方向有画面被裁掉;小于 1 表示该方向留有黑边。 + */ +@Immutable +data class VideoContentRect( + val widthFraction: Float, + val heightFraction: Float, +) + +/** + * 计算当前画面比例模式下画面相对视口的尺寸。 + * + * [PlayerAspectRatio.Stretch] 禁用平移(mpv 在 `keepaspect=no` 时不做缩放平移),返回 null 表示不支持双指缩放。 + */ +fun videoContentRect( + aspectRatio: PlayerAspectRatio?, + videoAspect: Float?, + viewportWidth: Float, + viewportHeight: Float, + cropRegion: VideoCropRegion? = null, +): VideoContentRect? { + if (!(viewportWidth > 0f) || !(viewportHeight > 0f)) return null + val video = videoAspect?.takeIf { it.isFinite() && it > 0f } ?: return null + val viewport = viewportWidth / viewportHeight + return when (aspectRatio) { + PlayerAspectRatio.Crop -> if (video >= viewport) { + VideoContentRect(widthFraction = video / viewport, heightFraction = 1f) + } else { + VideoContentRect(widthFraction = 1f, heightFraction = viewport / video) + } + PlayerAspectRatio.Stretch -> null + PlayerAspectRatio.RegionCrop -> { + val region = cropRegion ?: return null + VideoContentRect( + widthFraction = 1f / region.width, + heightFraction = 1f / region.height, + ) + } + PlayerAspectRatio.Fit, null -> if (video >= viewport) { + VideoContentRect(widthFraction = 1f, heightFraction = viewport / video) + } else { + VideoContentRect(widthFraction = video / viewport, heightFraction = 1f) + } + } +} diff --git a/shared/src/desktopTest/kotlin/dev/piko/shared/media/player/VideoZoomTest.kt b/shared/src/desktopTest/kotlin/dev/piko/shared/media/player/VideoZoomTest.kt new file mode 100644 index 00000000..83d5a080 --- /dev/null +++ b/shared/src/desktopTest/kotlin/dev/piko/shared/media/player/VideoZoomTest.kt @@ -0,0 +1,134 @@ +package dev.piko.shared.media.player + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class VideoZoomTest { + @Test + fun fitContentKeepsLetterboxInViewportDirection() { + // 竖屏窗口(1080x2400)播放 16:9:宽度铺满,上下留黑边 + val rect = videoContentRect( + aspectRatio = PlayerAspectRatio.Fit, + videoAspect = 16f / 9f, + viewportWidth = 1080f, + viewportHeight = 2400f, + ) + assertEquals(1f, rect?.widthFraction) + assertEquals((1080f / 2400f) / (16f / 9f), rect?.heightFraction) + } + + @Test + fun cropContentFillsViewportAndCropsTheOtherAxis() { + val rect = videoContentRect( + aspectRatio = PlayerAspectRatio.Crop, + videoAspect = 16f / 9f, + viewportWidth = 1080f, + viewportHeight = 2400f, + ) + assertEquals(1f, rect?.heightFraction) + assertEquals((16f / 9f) / (1080f / 2400f), rect?.widthFraction) + } + + @Test + fun regionCropContentUsesInverseOfRegionSize() { + val rect = videoContentRect( + aspectRatio = PlayerAspectRatio.RegionCrop, + videoAspect = 16f / 9f, + viewportWidth = 1000f, + viewportHeight = 500f, + cropRegion = VideoCropRegion(left = 0.2f, top = 0.25f, right = 0.7f, bottom = 0.75f), + ) + assertEquals(2f, rect?.widthFraction) + assertEquals(2f, rect?.heightFraction) + } + + @Test + fun stretchAndUnknownAspectDisableZoom() { + assertNull( + videoContentRect( + aspectRatio = PlayerAspectRatio.Stretch, + videoAspect = 16f / 9f, + viewportWidth = 1000f, + viewportHeight = 500f, + ), + ) + assertNull( + videoContentRect( + aspectRatio = PlayerAspectRatio.Fit, + videoAspect = null, + viewportWidth = 1000f, + viewportHeight = 500f, + ), + ) + } + + @Test + fun pinchKeepsTheFocusedPointUnderTheFingers() { + val content = VideoContentRect(1f, 1f) + val zoom = VideoZoom(scale = 1f).transformedBy( + previousCentroidX = 0.2f, + previousCentroidY = -0.1f, + centroidX = 0.2f, + centroidY = -0.1f, + scaleRatio = 2f, + content = content, + ) + assertEquals(2f, zoom.scale) + // 焦点处的画面点两次变换后仍落在同一屏幕位置:point = pan + scale * u + val ux = (0.2f - 0f) / 1f + val uy = (-0.1f - 0f) / 1f + assertEquals(0.2f, zoom.panX + zoom.scale * ux, 0.0001f) + assertEquals(-0.1f, zoom.panY + zoom.scale * uy, 0.0001f) + } + + @Test + fun twoFingerDragPansWithoutChangingScale() { + val zoom = VideoZoom(scale = 2f).transformedBy( + previousCentroidX = 0f, + previousCentroidY = 0f, + centroidX = 0.1f, + centroidY = 0.05f, + scaleRatio = 1f, + content = VideoContentRect(1f, 1f), + ) + assertEquals(2f, zoom.scale) + assertEquals(0.1f, zoom.panX, 0.0001f) + assertEquals(0.05f, zoom.panY, 0.0001f) + } + + @Test + fun panIsClampedToKeepContentCoveringTheViewport() { + val content = VideoContentRect(1f, 1f) + val zoom = VideoZoom(scale = 1.5f).pannedBy(dx = 1f, dy = -1f, content = content) + assertEquals(0.25f, zoom.panX, 0.0001f) + assertEquals(-0.25f, zoom.panY, 0.0001f) + } + + @Test + fun letterboxedAxisStaysCentered() { + // 4:3 画面放进 16:9 视口:高度铺满,宽度留黑边;放大不足以填满宽度前不许横向平移 + val content = VideoContentRect(widthFraction = 0.75f, heightFraction = 1f) + val zoom = VideoZoom(scale = 1.2f).pannedBy(dx = 1f, dy = 1f, content = content) + assertEquals(0f, zoom.panX, 0.0001f) + assertEquals(0.1f, zoom.panY, 0.0001f) + } + + @Test + fun resetZoomCannotPan() { + val zoom = VideoZoom(scale = 1f).pannedBy(dx = 0.4f, dy = -0.4f, content = VideoContentRect(1f, 1f)) + assertTrue(!zoom.isZoomed) + assertEquals(0f, zoom.panX) + assertEquals(0f, zoom.panY) + } + + @Test + fun invalidInputIsSanitized() { + val zoom = VideoZoom(scale = Float.NaN, panX = Float.POSITIVE_INFINITY).sanitized() + assertEquals(VideoZoom.MIN_SCALE, zoom.scale) + assertEquals(0f, zoom.panX) + assertEquals(0f, zoom.panY) + assertEquals(VideoZoom.MAX_SCALE, VideoZoom(scale = 100f).sanitized().scale) + } +} diff --git a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerControlsOverlay.kt b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerControlsOverlay.kt index 2f1c3504..79af406b 100644 --- a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerControlsOverlay.kt +++ b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerControlsOverlay.kt @@ -77,6 +77,7 @@ import dev.piko.shared.media.player.PlayerControlId import dev.piko.shared.media.player.PlaylistEntry import dev.piko.shared.media.player.SubtitleStylePrefs import dev.piko.shared.media.player.VideoCropRegion +import dev.piko.shared.media.player.VideoZoom import dev.piko.ui.components.LocalPointerSource import dev.piko.ui.components.SheetAction import dev.piko.ui.components.isKeyboardModality @@ -118,6 +119,10 @@ fun MobilePlayerControls( onSpeedChange: (Float) -> Unit, onAspectRatioChange: (PlayerAspectRatio) -> Unit, onCropRegionChange: (VideoCropRegion?) -> Unit = {}, + isVideoZoomed: Boolean = false, + supportsVideoZoom: Boolean = false, + videoZoomProvider: () -> VideoZoom = { VideoZoom.Reset }, + onVideoZoomChange: ((VideoZoom) -> Unit)? = null, onQualityChange: (String) -> Unit, onRetry: () -> Unit, onRestartFromBeginning: () -> Unit, @@ -560,6 +565,12 @@ fun MobilePlayerControls( ui.interacted() }, seekTapActive = { ui.doubleTapVisible && ui.tapSeekRound && pointerSource.isTouchLike }, + supportsVideoZoom = supportsVideoZoom && onVideoZoomChange != null, + videoZoomProvider = videoZoomProvider, + onVideoZoomChange = onVideoZoomChange, + videoAspect = videoAspect, + aspectRatio = aspectRatio, + cropRegion = cropRegion, modifier = Modifier.pointerInput(ui.isLocked, modalOverlayOpen, speedController) { if (ui.isLocked || modalOverlayOpen) return@pointerInput awaitPointerEventScope { @@ -597,12 +608,15 @@ fun MobilePlayerControls( errorMessage == null && !modalOverlayOpen && !isSeeking && !speedOverlayActive, onClick = onToggleFullscreen, ) - RestoreCropPromptButton( - visible = chromeVisible && !isSeeking && !speedOverlayActive && - aspectRatio == PlayerAspectRatio.RegionCrop && errorMessage == null, + RestoreViewPromptButton( + // 放大后控件收起也留着,否则还原入口会跟着底栏一起消失 + visible = !ui.isLocked && !modalOverlayOpen && !isSeeking && !speedOverlayActive && + errorMessage == null && + (isVideoZoomed || aspectRatio == PlayerAspectRatio.RegionCrop), onClick = { ui.interacted() - onCropRegionChange(null) + if (isVideoZoomed) onVideoZoomChange?.invoke(VideoZoom.Reset) + if (aspectRatio == PlayerAspectRatio.RegionCrop) onCropRegionChange(null) }, ) } @@ -848,6 +862,15 @@ fun MobilePlayerControls( .then(hudVerticalPadding), ) + PlayerZoomHud( + zoom = if (modalOverlayOpen) null else (ui.activeGesture as? PlayerGesture.Zoom)?.zoom, + showBackground = showIndicatorBackground, + modifier = Modifier + .align(hudAlignment) + .windowInsetsPadding(WindowInsets.safeDrawing) + .then(hudVerticalPadding), + ) + PlayerLevelEdgeBar( adjust = if (modalOverlayOpen) null else activeLevel, dockEnd = levelDockEnd, diff --git a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerGestures.kt b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerGestures.kt index 5fac04ad..b3425432 100644 --- a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerGestures.kt +++ b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerGestures.kt @@ -39,9 +39,15 @@ import dev.piko.shared.media.player.MAX_DOUBLE_TAP_ZONE_FRACTION import dev.piko.shared.media.player.MAX_VERTICAL_ZONE_FRACTION import dev.piko.shared.media.player.MIN_DOUBLE_TAP_ZONE_FRACTION import dev.piko.shared.media.player.MIN_VERTICAL_ZONE_FRACTION +import dev.piko.shared.media.player.PlayerAspectRatio import dev.piko.shared.media.player.PlayerGestureConfig import dev.piko.shared.media.player.VerticalSwipeAction +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 kotlin.math.abs +import kotlin.math.roundToInt /** * 竖滑手势与上下方向键调节的一路电平,取值 0 到 1。由平台实现:Android 的亮度是窗口属性、 @@ -87,11 +93,18 @@ internal sealed interface PlayerGesture { val direction: Int, val armed: Boolean, ) : PlayerGesture + + /** + * 双指缩放与平移。放大后单指拖动也走这一路,避免横划进退把放大后的查看打断。 + * [zoom] 每次变化都是完整状态,调用方直接下发给播放后端。 + */ + data class Zoom(val zoom: VideoZoom) : PlayerGesture } private sealed interface SurfaceGestureRace { data object Ended : SurfaceGestureRace data class DragStarted(val change: PointerInputChange) : SurfaceGestureRace + data class SecondPointer(val changes: List) : SurfaceGestureRace } /** @@ -126,6 +139,13 @@ internal fun PlayerGestureLayer( modifier: Modifier = Modifier, // 为 true 时两侧的单点也交给 onDoubleTap,不等第二下:双击进退之后,读数还在就接着点 seekTapActive: () -> Boolean = { false }, + supportsVideoZoom: Boolean = false, + // 读取当前缩放状态而不是经组合参数传入:逐帧手势不应该让整个控件层重组 + videoZoomProvider: () -> VideoZoom = { VideoZoom.Reset }, + onVideoZoomChange: ((VideoZoom) -> Unit)? = null, + videoAspect: Float? = null, + aspectRatio: PlayerAspectRatio? = null, + cropRegion: VideoCropRegion? = null, ) { val haptic = LocalHapticFeedback.current val density = LocalDensity.current @@ -149,6 +169,12 @@ internal fun PlayerGestureLayer( val currentSpeedSupported by rememberUpdatedState(speedSupported) val currentCanPrevious by rememberUpdatedState(canPrevious) val currentCanNext by rememberUpdatedState(canNext) + val currentSupportsZoom by rememberUpdatedState(supportsVideoZoom) + val currentVideoZoomProvider by rememberUpdatedState(videoZoomProvider) + val zoomChanged by rememberUpdatedState(onVideoZoomChange) + val currentVideoAspect by rememberUpdatedState(videoAspect) + val currentAspectRatio by rememberUpdatedState(aspectRatio) + val currentCropRegion by rememberUpdatedState(cropRegion) val gestureInsets = WindowInsets.systemGestures val edgeLeft by rememberUpdatedState(gestureInsets.getLeft(density, layoutDirection)) @@ -220,6 +246,67 @@ internal fun PlayerGestureLayer( if (isLocked) return@pointerInput var speedOwned = false var dragActive = false + + /** + * 双指变换期间吞掉全部指针事件:单指状态机与点按/双击状态机都收不到干净事件, + * 松手后只留下缩放结果,不会误触发进退、亮度或暂停。 + */ + suspend fun AwaitPointerEventScope.awaitZoomTransform( + initial: List, + width: Float, + height: Float, + content: VideoContentRect, + ) { + if (initial.size < 2) return + var previousCentroid = initial.centroid() + var previousRadius = initial.averageRadius(previousCentroid) + var current = currentVideoZoomProvider().clampedTo(content) + var lastHudTenths = -1 + + // 后端每帧都要拿到最新倍率;HUD 只在整十倍率变化时更新,避免每帧重组整块控件 + fun publishZoom(zoom: VideoZoom) { + zoomChanged?.invoke(zoom) + val tenths = (zoom.scale * 10f).roundToInt() + if (tenths == lastHudTenths) return + lastHudTenths = tenths + publish(PlayerGesture.Zoom(zoom)) + } + + publishZoom(current) + haptic.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate) + initial.forEach { it.consume() } + try { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Main) + val pressed = event.changes.filter { it.pressed } + // 少于两指即结束:抬起的那一下也消费掉,避免外层把它当成单击 + if (pressed.size < 2) { + event.changes.forEach { it.consume() } + return + } + val centroid = pressed.centroid() + val radius = pressed.averageRadius(centroid) + if (previousRadius > 0.5f && radius > 0.5f) { + current = current.transformedBy( + previousCentroidX = previousCentroid.x / width - 0.5f, + previousCentroidY = previousCentroid.y / height - 0.5f, + centroidX = centroid.x / width - 0.5f, + centroidY = centroid.y / height - 0.5f, + scaleRatio = radius / previousRadius, + content = content, + ) + publishZoom(current) + } + previousCentroid = centroid + previousRadius = radius + event.changes.forEach { it.consume() } + } + } finally { + // 正常抬指或指针被系统取消都收口,HUD 与手势状态不残留 + publish(null) + } + } + try { awaitEachGesture { val down = awaitFirstDown(requireUnconsumed = true) @@ -233,6 +320,20 @@ internal fun PlayerGestureLayer( val canSpeedDial = currentGestures.longPressSpeedEnabled && currentSpeedSupported && speedController != null + val viewportWidth = size.width.toFloat().coerceAtLeast(1f) + val viewportHeight = size.height.toFloat().coerceAtLeast(1f) + // 画面比例模式不支持(Stretch)或视频宽高比还没读到时不参与双指缩放 + val zoomContent = if (currentSupportsZoom) { + videoContentRect( + aspectRatio = currentAspectRatio, + videoAspect = currentVideoAspect, + viewportWidth = viewportWidth, + viewportHeight = viewportHeight, + cropRegion = currentCropRegion, + ) + } else { + null + } var dragStartChange: PointerInputChange? = null var enterSpeedDial = false @@ -242,6 +343,10 @@ internal fun PlayerGestureLayer( var result: SurfaceGestureRace = SurfaceGestureRace.Ended while (true) { val event = awaitPointerEvent(PointerEventPass.Main) + if (zoomContent != null && event.changes.count { it.pressed } > 1) { + result = SurfaceGestureRace.SecondPointer(event.changes.filter { it.pressed }) + break + } val change = event.changes.firstOrNull { it.id == pointerId } ?: break if (change.isConsumed || !change.pressed) break lastPosition = change.position @@ -256,10 +361,23 @@ internal fun PlayerGestureLayer( null -> enterSpeedDial = true SurfaceGestureRace.Ended -> return@awaitEachGesture is SurfaceGestureRace.DragStarted -> dragStartChange = outcome.change + is SurfaceGestureRace.SecondPointer -> { + awaitZoomTransform(outcome.changes, viewportWidth, viewportHeight, zoomContent!!) + return@awaitEachGesture + } } } else { while (true) { val event = awaitPointerEvent(PointerEventPass.Main) + if (zoomContent != null && event.changes.count { it.pressed } > 1) { + awaitZoomTransform( + event.changes.filter { it.pressed }, + viewportWidth, + viewportHeight, + zoomContent, + ) + return@awaitEachGesture + } val change = event.changes.firstOrNull { it.id == pointerId } ?: return@awaitEachGesture if (change.isConsumed || !change.pressed) { @@ -373,8 +491,18 @@ internal fun PlayerGestureLayer( dragActive = true firstChange.consume() + // 已经放大时,单指拖动改为平移画面;缩放回原始大小后横划进退照旧。 + // 平移不写 ui.activeGesture:它只改播放后端,不应为每一帧重组控件层,也不显示倍率 HUD。 + val panStartZoom = zoomContent + ?.takeIf { currentVideoZoomProvider().scale > VideoZoom.MIN_SCALE + 0.001f } + ?.let { currentVideoZoomProvider().clampedTo(it) } + if (panStartZoom != null) { + zoomChanged?.invoke(panStartZoom) + } val horizontal = abs(accumulated.x) >= abs(accumulated.y) - val started: PlayerGesture? = if (horizontal) { + val started: PlayerGesture? = if (panStartZoom != null) { + null + } else if (horizontal) { if (currentGestures.swipeSeekEnabled && duration > 0L) { PlayerGesture.Seek(readPosition(), 0L, cancelled = false) } else { @@ -424,6 +552,19 @@ internal fun PlayerGestureLayer( } seekCancelArmed = inZone } + // 始终从手势起点 + 累计位移算平移。若拿上一帧状态再加累计位移,位移会被反复叠加, + // 几下就冲到边界,看起来像只有左右两个刻度。 + if (panStartZoom != null && zoomContent != null) { + val next = PlayerGesture.Zoom( + panStartZoom.pannedBy( + dx = accumulated.x / w, + dy = accumulated.y / h, + content = zoomContent, + ), + ) + zoomChanged?.invoke(next.zoom) + return + } when (val current = activeGesture) { is PlayerGesture.Seek -> { val dur = duration @@ -472,6 +613,10 @@ internal fun PlayerGestureLayer( publish(PlayerGesture.EpisodeSwipe(direction = dir, armed = armed)) } + is PlayerGesture.Zoom -> { + // 双指变换不走这里;单指平移在上面提前返回 + } + null -> Unit } } @@ -559,6 +704,20 @@ private fun inSeekCancelZone(point: Offset, width: Float, height: Float): Boolea return inTop && nearSide } +/** 多个按下指针的中点。 */ +private fun List.centroid(): Offset { + var sum = Offset.Zero + forEach { sum += it.position } + return sum / size.toFloat() +} + +/** 各指针到中点的平均距离,双指捏合时作为缩放基准。 */ +private fun List.averageRadius(centroid: Offset): Float { + var sum = 0f + forEach { sum += (it.position - centroid).getDistance() } + return sum / size.toFloat() +} + private const val SEEK_CANCEL_ZONE_FRACTION = 0.15f private const val EPISODE_SWIPE_THRESHOLD_FRACTION = 0.14f private const val ADJUST_TRAVEL_RATIO = 0.75f diff --git a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerHud.kt b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerHud.kt index b6faccb0..cd20acf9 100644 --- a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerHud.kt +++ b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerHud.kt @@ -29,6 +29,7 @@ import androidx.compose.material.icons.filled.FastForward import androidx.compose.material.icons.filled.FastRewind import androidx.compose.material.icons.filled.SkipNext import androidx.compose.material.icons.filled.SkipPrevious +import androidx.compose.material.icons.filled.ZoomIn import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme @@ -61,6 +62,7 @@ import dev.piko.ui.resources.player_gesture_episode_swipe_up import dev.piko.ui.resources.player_seek_backward_seconds import dev.piko.ui.resources.player_seek_forward_seconds import dev.piko.ui.resources.player_seek_release_to_cancel +import dev.piko.shared.media.player.VideoZoom import dev.piko.ui.theme.LocalFixedColors import dev.piko.ui.theme.LocalPikoMotion import dev.piko.ui.theme.tabular @@ -301,6 +303,70 @@ internal fun SeekHudOverlay( } } +/** + * 双指缩放中央轻量胶囊:显示当前倍率,手势结束后随读数一起淡出。 + */ +@Composable +internal fun PlayerZoomHud( + zoom: VideoZoom?, + showBackground: Boolean = true, + modifier: Modifier = Modifier, +) { + val retained = remember { mutableStateOf(null) } + if (zoom != null) SideEffect { retained.value = zoom } + val shown = zoom ?: retained.value + val motion = MaterialTheme.motionScheme + val fixed = LocalFixedColors.current + + AnimatedVisibility( + visible = zoom != null, + enter = fadeIn(motion.fastEffectsSpec()), + exit = fadeOut(motion.fastEffectsSpec()), + modifier = modifier, + ) { + val current = shown ?: return@AnimatedVisibility + val tenths = (current.scale * 10f).roundToInt() + val label = "${tenths / 10}.${tenths % 10}×" + val desc = tr("缩放 $label", "Zoom $label", "ズーム $label", "확대 $label", "縮放 $label") + val labelStyle = MaterialTheme.typography.titleSmall.tabular.let { + if (showBackground) it else it.copy(shadow = PlayerTextShadow) + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier + .then( + if (showBackground) { + Modifier + .clip(CircleShape) + .background(fixed.ScrimOnMedia) + .border(1.dp, fixed.HudSpecularBorder, CircleShape) + .padding(horizontal = 12.dp, vertical = 7.dp) + } else { + Modifier.padding(horizontal = 6.dp, vertical = 4.dp) + }, + ) + .semantics { + liveRegion = LiveRegionMode.Polite + contentDescription = desc + }, + ) { + Icon( + imageVector = Icons.Filled.ZoomIn, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(LevelEdgeIconSize), + ) + Text( + text = label, + style = labelStyle, + color = fixed.OnMedia, + maxLines = 1, + ) + } + } +} + /** * 双击与方向键快进/快退贴边胶囊(移植自 Bilby `DoubleTapSeekHint`): * 贴合触发那一侧边缘轻滑进出,与音量/亮度边栏统一视觉语言。 diff --git a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerOverlays.kt b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerOverlays.kt index b435076e..a85d8c3f 100644 --- a/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerOverlays.kt +++ b/ui-player/src/commonMain/kotlin/dev/piko/ui/screens/player/PlayerOverlays.kt @@ -127,11 +127,12 @@ internal fun FullscreenPromptButtonContent( } /** - * 框选填充生效时的「还原」浮窗胶囊按钮,随控件栏显隐浮在画面底部,一键还原回适应屏幕。 + * 双指放大或框选填充生效时的「还原画面」浮窗胶囊按钮,随控件栏显隐浮在画面底部, + * 一键回到原始画面与适应屏幕。 */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun RestoreCropPromptButton( +internal fun RestoreViewPromptButton( visible: Boolean, onClick: () -> Unit, ) { @@ -149,7 +150,7 @@ internal fun RestoreCropPromptButton( contentColor = MaterialTheme.colorScheme.onSurface, ), ) { - Text(stringResource(Res.string.text_reset)) + Text(tr("还原画面", "Reset view", "表示をリセット", "화면 초기화", "重設畫面")) } } } diff --git a/ui-player/src/desktopTest/kotlin/dev/piko/ui/screens/player/PlayerGesturesTest.kt b/ui-player/src/desktopTest/kotlin/dev/piko/ui/screens/player/PlayerGesturesTest.kt index 7624fb65..67af4c8e 100644 --- a/ui-player/src/desktopTest/kotlin/dev/piko/ui/screens/player/PlayerGesturesTest.kt +++ b/ui-player/src/desktopTest/kotlin/dev/piko/ui/screens/player/PlayerGesturesTest.kt @@ -33,6 +33,7 @@ import dev.piko.shared.i18n.PikoLocale import dev.piko.shared.media.player.PlayerAspectRatio import dev.piko.shared.media.player.PlayerGestureConfig import dev.piko.shared.media.player.VerticalSwipeAction +import dev.piko.shared.media.player.VideoZoom import dev.piko.ui.adaptive.FormFactor import dev.piko.ui.components.LocalPointerSource import dev.piko.ui.components.PointerSource @@ -986,6 +987,83 @@ class PlayerGesturesTest { } } + /** + * 双指放大后单指拖动改为平移画面:不再提交进退,也不调节亮度/音量。 + */ + @Test + fun zoomedSurfacePansWithOneFingerInsteadOfSeeking() = withSingleThreadScene { ctx, motionScale -> + var zoom by mutableStateOf(VideoZoom(scale = 2f)) + var activeGesture by mutableStateOf(null) + val seeks = mutableListOf() + var eventTimeMs = 100L + var virtualNano = 1_000_000L + val scene = ImageComposeScene(width = 600, height = 360, coroutineContext = ctx) { + ProvideTestPlayerEnvironment(motionScale) { + PlayerGestureLayer( + isLocked = false, + durationMillis = 240_000L, + positionProvider = { 60_000L }, + brightness = null, + volume = null, + speedController = null, + speedSupported = false, + gestureConfig = PlayerGestureConfig.Default, + canPrevious = false, + canNext = false, + onGestureChange = { activeGesture = it }, + onVideoZoomChange = { zoom = it }, + onToggleControls = {}, + onSeekTo = { seeks += it }, + onDoubleTap = {}, + onPrevious = {}, + onNext = {}, + onSpeedStart = {}, + supportsVideoZoom = true, + videoZoomProvider = { zoom }, + videoAspect = 16f / 9f, + aspectRatio = PlayerAspectRatio.Fit, + ) + } + } + + suspend fun pumpFrames(count: Int = 3) { + repeat(count) { + virtualNano += 16_000_000L + scene.render(virtualNano).close() + delay(5) + } + } + + fun touch(type: PointerEventType, x: Float, y: Float) { + eventTimeMs += 15L + scene.sendPointerEvent(type, Offset(x, y), timeMillis = eventTimeMs, type = PointerType.Touch) + } + + try { + pumpFrames() + touch(PointerEventType.Press, 300f, 180f) + touch(PointerEventType.Move, 380f, 180f) + pumpFrames() + + assertEquals(2f, zoom.scale, "平移不应改变缩放倍数") + assertEquals(80f / 600f, zoom.panX, 0.002f, "平移量应等于手指位移,不能反复累加") + // 平移不发 HUD 手势,避免倍率读数一直挂在画面上 + assertNull(activeGesture) + + // 再移动一段:仍按起点到当前点的总位移计算,而不是把上一帧的平移再加一遍 + touch(PointerEventType.Move, 420f, 180f) + pumpFrames() + assertEquals(120f / 600f, zoom.panX, 0.002f, "连续移动不得叠加上一帧的平移") + + touch(PointerEventType.Release, 380f, 180f) + pumpFrames() + assertNull(activeGesture) + assertTrue(seeks.isEmpty(), "放大后的单指拖动不得提交进退") + } finally { + scene.close() + } + } + private fun collectContentDescriptions(node: SemanticsNode): List { val result = mutableListOf() if (SemanticsProperties.ContentDescription in node.config) {