fix(webui): scrub video using the 180p preview

This commit is contained in:
yiling
2026-11-27 10:50:46 +08:00
parent 90f076f3ba
commit 4b7b273f2e
12 changed files with 583 additions and 162 deletions
+1
View File
@@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed ### Fixed
- **video**: Pause playback while dragging the seekbar and show a lightweight preview in the player until the selected frame is ready.
- **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing. - **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing.
- **security**: Security improvements. - **security**: Security improvements.
@@ -42,6 +42,7 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
totalFrames, totalFrames,
currentFrame, currentFrame,
seekToFrame, seekToFrame,
scrub,
floatOverlayInFullScreen = true, floatOverlayInFullScreen = true,
onMouseEnter, onMouseEnter,
onMouseLeave, onMouseLeave,
@@ -95,6 +96,7 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
buffered={buffered} buffered={buffered}
previewUrl={data.media.videoPreview?.url} previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame} onSeek={seekToFrame}
scrub={scrub}
metadata={{ metadata={{
...data.media.metadata, ...data.media.metadata,
frameRate: frameRate, frameRate: frameRate,
@@ -2,18 +2,20 @@
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import React from 'react' import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import ProgressBar from './progress-bar' import ProgressBar, { type SeekbarScrubHandlers } from './progress-bar'
const TOTAL_FRAMES = 1000 const TOTAL_FRAMES = 1000
function renderBar(onSeek = vi.fn()) { function renderBar(scrub?: SeekbarScrubHandlers) {
render( const onSeek = vi.fn()
const { unmount } = render(
<ProgressBar <ProgressBar
totalFrames={TOTAL_FRAMES} totalFrames={TOTAL_FRAMES}
currentFrame={0} currentFrame={0}
fps={25} fps={25}
previewUrl="https://example.test/preview.mp4" previewUrl="https://example.test/preview.mp4"
onSeek={onSeek} onSeek={onSeek}
scrub={scrub}
/>, />,
) )
const bar = screen.getByTestId('seekbar') const bar = screen.getByTestId('seekbar')
@@ -28,7 +30,7 @@ function renderBar(onSeek = vi.fn()) {
y: 0, y: 0,
toJSON: () => ({}), toJSON: () => ({}),
} as DOMRect) } as DOMRect)
return { bar, onSeek } return { bar, onSeek, unmount }
} }
function touchEvent(type: string, clientX: number, list: 'touches' | 'changedTouches') { function touchEvent(type: string, clientX: number, list: 'touches' | 'changedTouches') {
@@ -135,4 +137,66 @@ describe('ProgressBar seeking', () => {
expect(preview).not.toBeNull() expect(preview).not.toBeNull()
expect(preview?.getAttribute('preload')).toBe('metadata') expect(preview?.getAttribute('preload')).toBe('metadata')
}) })
describe('with in-player scrubbing', () => {
const scrub = { onStart: vi.fn(), onMove: vi.fn(), onEnd: vi.fn(), onCancel: vi.fn() }
beforeEach(() => {
vi.clearAllMocks()
})
it('starts after movement and commits at the release position outside the track', () => {
const { bar, onSeek } = renderBar(scrub)
fireEvent.mouseDown(bar, { button: 0, clientX: 20 })
fireEvent.mouseMove(window, { clientX: 21 })
expect(scrub.onStart).not.toHaveBeenCalled()
expect(onSeek).not.toHaveBeenCalled()
fireEvent.mouseMove(window, { clientX: 40 })
fireEvent.mouseMove(window, { clientX: 60 })
expect(scrub.onStart).toHaveBeenCalledExactlyOnceWith(400)
expect(scrub.onMove).toHaveBeenCalledExactlyOnceWith(600)
expect(scrub.onEnd).not.toHaveBeenCalled()
expect(onSeek).not.toHaveBeenCalled()
expect(bar.querySelectorAll('video')).toHaveLength(1)
fireEvent.mouseUp(window, { button: 0, clientX: 120, clientY: 20 })
expect(scrub.onEnd).toHaveBeenCalledExactlyOnceWith(TOTAL_FRAMES)
expect(onSeek).not.toHaveBeenCalled()
})
it('seeks once on touch release when the user taps', () => {
const { bar, onSeek } = renderBar(scrub)
fireEvent(bar, touchEvent('touchstart', 30, 'touches'))
expect(onSeek).not.toHaveBeenCalled()
fireEvent(window, touchEvent('touchend', 30, 'changedTouches'))
fireEvent.mouseDown(bar, { button: 0, clientX: 30 })
expect(onSeek).toHaveBeenCalledExactlyOnceWith(300)
expect(scrub.onStart).not.toHaveBeenCalled()
})
it('cancels an interrupted touch drag without committing the frame', () => {
const { bar, onSeek } = renderBar(scrub)
fireEvent(bar, touchEvent('touchstart', 30, 'touches'))
fireEvent(window, touchEvent('touchmove', 50, 'touches'))
fireEvent(window, new Event('touchcancel'))
fireEvent(window, touchEvent('touchend', 60, 'changedTouches'))
expect(scrub.onStart).toHaveBeenCalledExactlyOnceWith(500)
expect(scrub.onCancel).toHaveBeenCalledTimes(1)
expect(scrub.onEnd).not.toHaveBeenCalled()
expect(onSeek).not.toHaveBeenCalled()
})
it('cancels an active drag when the controls unmount', () => {
const { bar, unmount } = renderBar(scrub)
fireEvent.mouseDown(bar, { button: 0, clientX: 20 })
fireEvent.mouseMove(window, { clientX: 40 })
unmount()
expect(scrub.onStart).toHaveBeenCalledExactlyOnceWith(400)
expect(scrub.onCancel).toHaveBeenCalledTimes(1)
expect(scrub.onEnd).not.toHaveBeenCalled()
})
})
}) })
@@ -14,12 +14,20 @@ const formatTime = (seconds: number): string => {
return `${mm}:${ss}` return `${mm}:${ss}`
} }
export interface SeekbarScrubHandlers {
onStart: (frame: number) => void
onMove: (frame: number) => void
onEnd: (frame: number) => void
onCancel: () => void
}
interface ProgressBarProps { interface ProgressBarProps {
totalFrames: number totalFrames: number
currentFrame: number currentFrame: number
fps: number fps: number
previewUrl?: string previewUrl?: string
onSeek: (frame: number) => void onSeek: (frame: number) => void
scrub?: SeekbarScrubHandlers
buffered?: number buffered?: number
metadata?: MediaMetadata metadata?: MediaMetadata
} }
@@ -30,6 +38,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
fps, fps,
previewUrl, previewUrl,
onSeek, onSeek,
scrub,
buffered = 0, buffered = 0,
metadata, metadata,
}) => { }) => {
@@ -48,10 +57,17 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
// trigger a second seek through the mouse path. // trigger a second seek through the mouse path.
const lastTouchEndAtRef = useRef(0) const lastTouchEndAtRef = useRef(0)
const onSeekRef = useRef(onSeek) const handlersRef = useRef({ onSeek, scrub })
useEffect(() => { useEffect(() => {
onSeekRef.current = onSeek handlersRef.current = { onSeek, scrub }
}, [onSeek]) }, [onSeek, scrub])
useEffect(
() => () => {
if (didDragMoveRef.current) handlersRef.current.scrub?.onCancel()
},
[],
)
// Load the preview video in background // Load the preview video in background
useEffect(() => { useEffect(() => {
@@ -61,35 +77,32 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
}, [previewUrl]) }, [previewUrl])
const getPercentageFromEvent = useCallback((clientX: number) => { const getPercentageFromEvent = useCallback((clientX: number) => {
if (!containerRef.current) return 0 const rect = containerRef.current?.getBoundingClientRect()
const rect = containerRef.current.getBoundingClientRect() if (!rect?.width) return 0
const x = Math.max(0, Math.min(clientX - rect.left, rect.width)) const x = Math.max(0, Math.min(clientX - rect.left, rect.width))
return x / rect.width return x / rect.width
}, []) }, [])
const seekPreview = useCallback(
(percentage: number) => {
const video = previewVideoRef.current
const seekTime = (percentage * totalFrames + 0.5) / fps
if (video && totalFrames > 0 && Number.isFinite(seekTime)) {
video.currentTime = seekTime
}
},
[totalFrames, fps],
)
const handleMouseMove = useCallback( const handleMouseMove = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => { (e: React.MouseEvent<HTMLDivElement>) => {
if (isDragging) return if (isDragging) return
if (!containerRef.current) return const percentage = getPercentageFromEvent(e.clientX)
const rect = containerRef.current.getBoundingClientRect()
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width))
const percentage = x / rect.width
setHoverPosition(percentage) setHoverPosition(percentage)
setIsHovering(true) setIsHovering(true)
seekPreview(percentage)
if (previewVideoRef.current && totalFrames) {
const targetFrame = percentage * totalFrames
const frameDuration = 1 / fps
const seekTime = targetFrame * frameDuration + frameDuration / 2
const vid = previewVideoRef.current
if (Number.isFinite(seekTime)) {
vid.currentTime = seekTime
}
}
}, },
[totalFrames, fps, isDragging], [getPercentageFromEvent, isDragging, seekPreview],
) )
const handleMouseLeave = () => { const handleMouseLeave = () => {
@@ -99,154 +112,108 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
} }
} }
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => { const startInteraction = (clientX: number) => {
if (e.button !== 0) return if (isDragging || totalFrames <= 0) return
if (Date.now() - lastTouchEndAtRef.current < 700) return
e.preventDefault()
setIsDragging(true) setIsDragging(true)
didDragMoveRef.current = false didDragMoveRef.current = false
lastSeekPosRef.current = e.clientX lastSeekPosRef.current = clientX
const percentage = getPercentageFromEvent(e.clientX) const percentage = getPercentageFromEvent(clientX)
setHoverPosition(percentage) setHoverPosition(percentage)
setIsHovering(true) setIsHovering(true)
onSeekRef.current(percentage * totalFrames) if (!scrub) onSeek(percentage * totalFrames)
}
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
if (e.button !== 0 || Date.now() - lastTouchEndAtRef.current < 700) return
e.preventDefault()
startInteraction(e.clientX)
} }
const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => { const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
setIsDragging(true) if (e.touches.length === 1) startInteraction(e.touches[0].clientX)
didDragMoveRef.current = false
lastSeekPosRef.current = e.touches[0].clientX
const percentage = getPercentageFromEvent(e.touches[0].clientX)
setHoverPosition(percentage)
setIsHovering(true)
onSeekRef.current(percentage * totalFrames)
} }
useEffect(() => { useEffect(() => {
if (!isDragging) return if (!isDragging) return
const handleWindowMouseMove = (e: MouseEvent) => { const moveInteraction = (clientX: number) => {
if (lastSeekPosRef.current !== null && Math.abs(e.clientX - lastSeekPosRef.current) >= 2) { const start = lastSeekPosRef.current
didDragMoveRef.current = true if (start === null) return
lastSeekPosRef.current = e.clientX const alreadyMoved = didDragMoveRef.current
} else if (!didDragMoveRef.current) { if (!alreadyMoved && Math.abs(clientX - start) < 2) return
return didDragMoveRef.current = true
} const percentage = getPercentageFromEvent(clientX)
const percentage = getPercentageFromEvent(e.clientX)
setHoverPosition(percentage) setHoverPosition(percentage)
setIsHovering(true) setIsHovering(true)
if (previewVideoRef.current && totalFrames) { const { onSeek, scrub } = handlersRef.current
const targetFrame = percentage * totalFrames const frame = percentage * totalFrames
const frameDuration = 1 / fps if (scrub) {
const seekTime = targetFrame * frameDuration + frameDuration / 2 if (alreadyMoved) scrub.onMove(frame)
const vid = previewVideoRef.current else scrub.onStart(frame)
if (Number.isFinite(seekTime)) { } else {
vid.currentTime = seekTime seekPreview(percentage)
} onSeek(frame)
} }
onSeekRef.current(percentage * totalFrames)
} }
const handleWindowMouseUp = (e: MouseEvent) => { const finishInteraction = (clientX: number, clientY: number, isTouch = false) => {
setIsDragging(false) if (lastSeekPosRef.current === null) return
const { onSeek, scrub } = handlersRef.current
let stillHovering = false const moved = didDragMoveRef.current
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect()
stillHovering =
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom
}
if (!stillHovering) {
setIsHovering(false)
setHoverPosition(null)
}
// A plain click already seeked on mousedown; only seek again if the
// pointer actually moved (drag release position differs from start).
if (didDragMoveRef.current) {
const percentage = getPercentageFromEvent(e.clientX)
onSeekRef.current(percentage * totalFrames)
}
didDragMoveRef.current = false didDragMoveRef.current = false
lastSeekPosRef.current = null lastSeekPosRef.current = null
} setIsDragging(false)
const percentage = getPercentageFromEvent(clientX)
const handleWindowTouchMove = (e: TouchEvent) => { const rect = containerRef.current?.getBoundingClientRect()
if (e.touches.length === 0) return
if ( if (
lastSeekPosRef.current !== null && !rect ||
Math.abs(e.touches[0].clientX - lastSeekPosRef.current) >= 2 (isTouch && scrub) ||
clientX < rect.left ||
clientX > rect.right ||
clientY < rect.top ||
clientY > rect.bottom
) { ) {
didDragMoveRef.current = true
lastSeekPosRef.current = e.touches[0].clientX
} else if (!didDragMoveRef.current) {
return
}
const percentage = getPercentageFromEvent(e.touches[0].clientX)
setHoverPosition(percentage)
setIsHovering(true)
if (previewVideoRef.current && totalFrames) {
const targetFrame = percentage * totalFrames
const frameDuration = 1 / fps
const seekTime = targetFrame * frameDuration + frameDuration / 2
const vid = previewVideoRef.current
if (Number.isFinite(seekTime)) {
vid.currentTime = seekTime
}
}
onSeekRef.current(percentage * totalFrames)
}
const handleWindowTouchEnd = (e: TouchEvent) => {
setIsDragging(false)
lastTouchEndAtRef.current = Date.now()
const clientX = e.changedTouches.length > 0 ? e.changedTouches[0].clientX : null
const clientY = e.changedTouches.length > 0 ? e.changedTouches[0].clientY : null
let stillHovering = false
if (clientX !== null && clientY !== null && containerRef.current) {
const rect = containerRef.current.getBoundingClientRect()
stillHovering =
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
}
if (!stillHovering) {
setIsHovering(false) setIsHovering(false)
setHoverPosition(null) setHoverPosition(null)
} else if (scrub) {
setHoverPosition(percentage)
seekPreview(percentage)
} }
if (clientX !== null && didDragMoveRef.current) { const frame = percentage * totalFrames
// A plain tap already seeked on touchstart; only seek again after a if (scrub && moved) {
// real drag so a single tap doesn't restart the seek and stall. scrub.onEnd(frame)
const percentage = getPercentageFromEvent(clientX) } else if (scrub || moved) {
onSeekRef.current(percentage * totalFrames) // Compare and audio already seek on press, so only commit moved gestures here.
onSeek(frame)
} }
didDragMoveRef.current = false
lastSeekPosRef.current = null
} }
const handleWindowTouchCancel = () => { const cancelInteraction = () => {
// OS gestures (app switch, palm rejection, notification pull) cancel if (didDragMoveRef.current) handlersRef.current.scrub?.onCancel()
// the touch. Reset drag state without seeking so the bar doesn't stay didDragMoveRef.current = false
// stuck in dragging/hover mode. lastSeekPosRef.current = null
setIsDragging(false) setIsDragging(false)
setIsHovering(false) setIsHovering(false)
setHoverPosition(null) setHoverPosition(null)
didDragMoveRef.current = false }
lastSeekPosRef.current = null
const handleWindowMouseMove = (e: MouseEvent) => moveInteraction(e.clientX)
const handleWindowMouseUp = (e: MouseEvent) => finishInteraction(e.clientX, e.clientY)
const handleWindowTouchMove = (e: TouchEvent) => {
if (e.touches.length === 1) moveInteraction(e.touches[0].clientX)
}
const handleWindowTouchEnd = (e: TouchEvent) => {
if (e.touches.length > 0) return
lastTouchEndAtRef.current = Date.now() lastTouchEndAtRef.current = Date.now()
const touch = e.changedTouches[0]
if (touch) finishInteraction(touch.clientX, touch.clientY, true)
else cancelInteraction()
}
const handleWindowTouchCancel = () => {
lastTouchEndAtRef.current = Date.now()
cancelInteraction()
} }
window.addEventListener('mousemove', handleWindowMouseMove) window.addEventListener('mousemove', handleWindowMouseMove)
@@ -254,6 +221,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
window.addEventListener('touchmove', handleWindowTouchMove, { passive: true }) window.addEventListener('touchmove', handleWindowTouchMove, { passive: true })
window.addEventListener('touchend', handleWindowTouchEnd) window.addEventListener('touchend', handleWindowTouchEnd)
window.addEventListener('touchcancel', handleWindowTouchCancel) window.addEventListener('touchcancel', handleWindowTouchCancel)
window.addEventListener('blur', cancelInteraction)
return () => { return () => {
window.removeEventListener('mousemove', handleWindowMouseMove) window.removeEventListener('mousemove', handleWindowMouseMove)
@@ -261,8 +229,9 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
window.removeEventListener('touchmove', handleWindowTouchMove) window.removeEventListener('touchmove', handleWindowTouchMove)
window.removeEventListener('touchend', handleWindowTouchEnd) window.removeEventListener('touchend', handleWindowTouchEnd)
window.removeEventListener('touchcancel', handleWindowTouchCancel) window.removeEventListener('touchcancel', handleWindowTouchCancel)
window.removeEventListener('blur', cancelInteraction)
} }
}, [isDragging, totalFrames, fps, getPercentageFromEvent]) }, [isDragging, totalFrames, getPercentageFromEvent, seekPreview])
const progressPercent = const progressPercent =
isDragging && hoverPosition !== null isDragging && hoverPosition !== null
@@ -329,7 +298,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
/> />
{/* Hover Preview Tooltip */} {/* Hover Preview Tooltip */}
{isHovering && totalFrames > 0 && ( {isHovering && totalFrames > 0 && !(scrub && isDragging) && (
<div <div
className="pointer-events-none absolute bottom-full z-50 mb-3 flex w-max flex-col" className="pointer-events-none absolute bottom-full z-50 mb-3 flex w-max flex-col"
style={getTooltipStyle()} style={getTooltipStyle()}
@@ -0,0 +1,52 @@
import { cn } from '@/ui/lib/utils'
import { useCallback, useEffect, useRef, useState } from 'react'
export function ScrubPreview({ url, time }: { url: string; time: number | null }) {
const videoRef = useRef<HTMLVideoElement>(null)
const requestedTimeRef = useRef<number | null>(null)
const [hasFrame, setHasFrame] = useState(false)
const seekPreview = useCallback(() => {
const video = videoRef.current
if (time === null || !video || !Number.isFinite(video.duration) || video.seeking) return
const targetTime = Math.min(time, Math.max(0, video.duration - 0.001))
if (requestedTimeRef.current !== targetTime) {
requestedTimeRef.current = targetTime
if (Math.abs(video.currentTime - targetTime) > 0.001) {
video.currentTime = targetTime
return
}
}
if (video.readyState >= 2) setHasFrame(true)
}, [time])
useEffect(() => {
if (time === null) setHasFrame(false)
else seekPreview()
}, [time, seekPreview])
return (
<video
ref={videoRef}
src={url}
className={cn(
'absolute inset-0 h-full w-full bg-black object-contain',
(time === null || !hasFrame) && 'invisible',
)}
aria-hidden="true"
data-testid="scrub-preview"
muted
playsInline
preload="metadata"
onLoadedMetadata={seekPreview}
onLoadedData={seekPreview}
onSeeked={() => {
if (time === null) return
setHasFrame(true)
// Consume the latest pointer position after the current seek finishes.
seekPreview()
}}
onError={() => setHasFrame(false)}
/>
)
}
@@ -5,6 +5,7 @@ export interface UseFramePlayerResult {
currentFrame: number currentFrame: number
setCurrentFrame: React.Dispatch<React.SetStateAction<number>> setCurrentFrame: React.Dispatch<React.SetStateAction<number>>
seekToFrame: (targetFrame: number) => Promise<void> seekToFrame: (targetFrame: number) => Promise<void>
pauseForScrub: () => void
isSeeking: React.RefObject<boolean> isSeeking: React.RefObject<boolean>
} }
@@ -28,8 +29,10 @@ export function useFramePlayer(
): UseFramePlayerResult { ): UseFramePlayerResult {
const [currentFrame, setCurrentFrame] = useState<number>(0) const [currentFrame, setCurrentFrame] = useState<number>(0)
const isSeekingRef = useRef<boolean>(false) const isSeekingRef = useRef<boolean>(false)
const seekCompletionRef = useRef<Promise<void> | null>(null)
const isPlayingRef = useRef<boolean>(false) const isPlayingRef = useRef<boolean>(false)
const pendingSeekFrameRef = useRef<number | null>(null) const pendingSeekFrameRef = useRef<number | null>(null)
const scrubPauseRef = useRef(false)
const currentFrameRef = useRef<number>(currentFrame) const currentFrameRef = useRef<number>(currentFrame)
currentFrameRef.current = currentFrame currentFrameRef.current = currentFrame
@@ -149,6 +152,8 @@ export function useFramePlayer(
} }
const handlePause = () => { const handlePause = () => {
const scrubPause = scrubPauseRef.current
scrubPauseRef.current = false
if (rVfcId !== null) { if (rVfcId !== null) {
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
if (videoWithCallback.cancelVideoFrameCallback) { if (videoWithCallback.cancelVideoFrameCallback) {
@@ -181,7 +186,7 @@ export function useFramePlayer(
// Snap the playhead to the center of the paused frame to align browser compositor // Snap the playhead to the center of the paused frame to align browser compositor
// Skip snapping if the video has ended to preserve the native ended state and allow native replay // Skip snapping if the video has ended to preserve the native ended state and allow native replay
if (!video.ended) { if (!video.ended && !scrubPause) {
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate) const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
video.currentTime = safeCenterTime video.currentTime = safeCenterTime
} }
@@ -222,6 +227,16 @@ export function useFramePlayer(
} }
}, [videoRef.current, frameRate, totalFrames]) }, [videoRef.current, frameRate, totalFrames])
const pauseForScrub = useCallback(() => {
const video = videoRef.current
if (video && !video.paused) {
// The ordinary pause snaps to the nearest frame. Scrubbing defers the
// first native seek until release.
scrubPauseRef.current = true
video.pause()
}
}, [videoRef])
const seekToFrame = useCallback( const seekToFrame = useCallback(
async (targetFrame: number) => { async (targetFrame: number) => {
const video = videoRef.current const video = videoRef.current
@@ -231,10 +246,10 @@ export function useFramePlayer(
const clampedFrame = Math.max(0, Math.min(roundedFrame, totalFrames - 1)) const clampedFrame = Math.max(0, Math.min(roundedFrame, totalFrames - 1))
// If a seek is already active, queue this target and update UI state optimistically // If a seek is already active, queue this target and update UI state optimistically
if (isSeekingRef.current) { if (seekCompletionRef.current) {
pendingSeekFrameRef.current = clampedFrame pendingSeekFrameRef.current = clampedFrame
setCurrentFrame(clampedFrame) setCurrentFrame(clampedFrame)
return return seekCompletionRef.current
} }
isSeekingRef.current = true isSeekingRef.current = true
@@ -280,18 +295,26 @@ export function useFramePlayer(
setCurrentFrame(verifiedFrame) setCurrentFrame(verifiedFrame)
}) })
} }
}
// Process next seek in the queue if any came in during the seek const runSeeks = async () => {
if (pendingSeekFrameRef.current !== null) { try {
const nextFrame = pendingSeekFrameRef.current // Process the latest queued seek before signaling completion to any caller.
let nextFrame: number | null = clampedFrame
while (nextFrame !== null) {
await performSeek(nextFrame)
nextFrame = pendingSeekFrameRef.current
pendingSeekFrameRef.current = null
}
} finally {
seekCompletionRef.current = null
pendingSeekFrameRef.current = null pendingSeekFrameRef.current = null
await performSeek(nextFrame)
} else {
isSeekingRef.current = false isSeekingRef.current = false
} }
} }
await performSeek(clampedFrame) seekCompletionRef.current = runSeeks()
await seekCompletionRef.current
}, },
[videoRef, frameRate, totalFrames], [videoRef, frameRate, totalFrames],
) )
@@ -356,6 +379,7 @@ export function useFramePlayer(
currentFrame, currentFrame,
setCurrentFrame, setCurrentFrame,
seekToFrame, seekToFrame,
pauseForScrub,
isSeeking: isSeekingRef, isSeeking: isSeekingRef,
} }
} }
@@ -0,0 +1,100 @@
// @vitest-environment happy-dom
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { useVideoScrub } from './use-video-scrub'
afterEach(cleanup)
function setup() {
const video = document.createElement('video')
const media = { paused: false, seeking: false, readyState: 4, currentTime: 1 }
Object.defineProperties(video, {
paused: { get: () => media.paused },
seeking: { get: () => media.seeking },
readyState: { get: () => media.readyState },
currentTime: { get: () => media.currentTime },
})
const play = vi.spyOn(video, 'play').mockResolvedValue(undefined)
const seekToFrame = vi.fn(async (frame: number) => {
media.seeking = true
media.readyState = 1
media.currentTime = (frame + 0.5) / 30
})
const { result, rerender } = renderHook(
({ source }) =>
useVideoScrub({
videoRef: { current: video },
assetId: 'video',
source,
totalFrames: 300,
frameRate: 30,
pauseForScrub: () => {
media.paused = true
},
seekToFrame,
}),
{ initialProps: { source: '/video.mp4' } },
)
return { result, rerender, media, video, play, seekToFrame }
}
it('keeps the preview and audio paused until the requested frame is ready', async () => {
const { result, media, video, play, seekToFrame } = setup()
act(() => result.current.scrub.onStart(30))
act(() => result.current.scrub.onMove(90))
expect(media.paused).toBe(true)
expect(seekToFrame).not.toHaveBeenCalled()
await act(() => result.current.scrub.onEnd(100))
expect(seekToFrame).toHaveBeenCalledExactlyOnceWith(100)
expect(result.current.scrubFrame).toBe(100)
expect(play).not.toHaveBeenCalled()
media.seeking = false
act(() => video.dispatchEvent(new Event('seeked')))
expect(result.current.scrubFrame).toBe(100)
expect(play).not.toHaveBeenCalled()
media.readyState = 2
act(() => video.dispatchEvent(new Event('loadeddata')))
expect(result.current.scrubFrame).toBeNull()
expect(play).toHaveBeenCalledTimes(1)
})
it('restores playback at the old position when the drag is canceled', () => {
const { result, media, play, seekToFrame } = setup()
act(() => result.current.scrub.onStart(50))
act(() => result.current.scrub.onCancel())
expect(seekToFrame).not.toHaveBeenCalled()
expect(media.currentTime).toBe(1)
expect(result.current.scrubFrame).toBeNull()
expect(play).toHaveBeenCalledTimes(1)
})
it('drops a pending handoff when the playback source changes', async () => {
const { result, rerender, media, video, play } = setup()
act(() => result.current.scrub.onStart(90))
await act(() => result.current.scrub.onEnd(90))
rerender({ source: '/other.mp4' })
media.seeking = false
media.readyState = 4
act(() => video.dispatchEvent(new Event('seeked')))
expect(result.current.scrubFrame).toBeNull()
expect(play).not.toHaveBeenCalled()
})
it('returns to the main video when a newer seek changes the landing frame', async () => {
const { result, media, video, play } = setup()
act(() => result.current.scrub.onStart(90))
await act(() => result.current.scrub.onEnd(90))
media.currentTime = 4
media.seeking = false
media.readyState = 4
act(() => video.dispatchEvent(new Event('seeked')))
expect(result.current.scrubFrame).toBeNull()
expect(play).toHaveBeenCalledTimes(1)
})
@@ -0,0 +1,108 @@
import { useLayoutEffect, useRef, useState, type RefObject } from 'react'
import type { SeekbarScrubHandlers } from './progress-bar'
import { calculateFrameCenterTime } from './utils'
interface ScrubSession {
resume: boolean
removeSeekListeners?: () => void
}
interface VideoScrubOptions {
videoRef: RefObject<HTMLVideoElement | null>
assetId: string | undefined
source: string
totalFrames: number
frameRate: number
pauseForScrub: () => void
seekToFrame: (frame: number) => Promise<void>
}
export function useVideoScrub({
videoRef,
assetId,
source,
totalFrames,
frameRate,
pauseForScrub,
seekToFrame,
}: VideoScrubOptions) {
const sessionRef = useRef<ScrubSession | null>(null)
const [scrubFrame, setScrubFrame] = useState<number | null>(null)
const clampFrame = (frame: number) => Math.max(0, Math.min(Math.round(frame), totalFrames - 1))
useLayoutEffect(() => {
setScrubFrame(null)
return () => {
sessionRef.current?.removeSeekListeners?.()
sessionRef.current = null
}
}, [assetId, source])
const finish = (session: ScrubSession, video: HTMLVideoElement, ready: boolean) => {
if (sessionRef.current !== session) return
session.removeSeekListeners?.()
sessionRef.current = null
setScrubFrame(null)
if (ready && session.resume) video.play().catch(() => {})
}
const scrub: SeekbarScrubHandlers = {
onStart(frame) {
const video = videoRef.current
if (!video) return
const previous = sessionRef.current
previous?.removeSeekListeners?.()
sessionRef.current = { resume: previous?.resume ?? !video.paused }
pauseForScrub()
setScrubFrame(clampFrame(frame))
},
onMove(frame) {
if (sessionRef.current) setScrubFrame(clampFrame(frame))
},
onEnd(frame) {
const session = sessionRef.current
const video = videoRef.current
if (!session || !video) return
const targetFrame = clampFrame(frame)
setScrubFrame(targetFrame)
let seekFinished = false
const showMainVideo = () => {
if (seekFinished && !video.seeking && video.readyState >= 2) {
finish(session, video, true)
}
}
const handleError = () => finish(session, video, false)
video.addEventListener('seeked', showMainVideo)
video.addEventListener('loadeddata', showMainVideo)
video.addEventListener('canplay', showMainVideo)
video.addEventListener('error', handleError)
video.addEventListener('emptied', handleError)
session.removeSeekListeners = () => {
video.removeEventListener('seeked', showMainVideo)
video.removeEventListener('loadeddata', showMainVideo)
video.removeEventListener('canplay', showMainVideo)
video.removeEventListener('error', handleError)
video.removeEventListener('emptied', handleError)
}
// The normal seek helper has a timeout. Keep the preview visible until
// the media element can actually present the requested frame.
void seekToFrame(targetFrame).then(() => {
seekFinished = true
showMainVideo()
}, handleError)
},
onCancel() {
const session = sessionRef.current
const video = videoRef.current
if (session && video) finish(session, video, true)
},
}
return {
scrub,
scrubFrame,
previewTime: scrubFrame === null ? null : calculateFrameCenterTime(scrubFrame, frameRate),
}
}
@@ -27,7 +27,7 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from '../../ui/dropdown-menu' } from '../../ui/dropdown-menu'
import { Slider } from '../../ui/slider' import { Slider } from '../../ui/slider'
import ProgressBar from './progress-bar' import ProgressBar, { type SeekbarScrubHandlers } from './progress-bar'
import { formatTime, formatTimecode } from './utils' import { formatTime, formatTimecode } from './utils'
import { getVideoResolutionLabel } from '@/ui/lib/media' import { getVideoResolutionLabel } from '@/ui/lib/media'
@@ -83,6 +83,7 @@ export interface ControlBarProps {
totalFrames: number totalFrames: number
currentFrame: number currentFrame: number
seekToFrame: (frame: number) => Promise<void> | void seekToFrame: (frame: number) => Promise<void> | void
scrub?: SeekbarScrubHandlers
/** /**
* Whether the bar floats as an absolute overlay over the media while * Whether the bar floats as an absolute overlay over the media while
* fullscreen (single-file player). Compare mode sets this false so the bar * fullscreen (single-file player). Compare mode sets this false so the bar
@@ -118,6 +119,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
totalFrames, totalFrames,
currentFrame, currentFrame,
seekToFrame, seekToFrame,
scrub,
floatOverlayInFullScreen = true, floatOverlayInFullScreen = true,
onMouseEnter, onMouseEnter,
onMouseLeave, onMouseLeave,
@@ -175,6 +177,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
buffered={buffered} buffered={buffered}
previewUrl={data.media.videoPreview?.url} previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame} onSeek={seekToFrame}
scrub={scrub}
metadata={{ metadata={{
...data.media.metadata, ...data.media.metadata,
frameRate: frameRate, frameRate: frameRate,
@@ -6,6 +6,8 @@ import { Play, AudioLines, Loader2, AlertCircle } from 'lucide-react'
import React, { useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react' import React, { useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react'
import Hls from 'hls.js' import Hls from 'hls.js'
import { useFramePlayer } from './use-frame-player' import { useFramePlayer } from './use-frame-player'
import { useVideoScrub } from './use-video-scrub'
import { ScrubPreview } from './scrub-preview'
import { calculateFrameCenterTime, resolveTotalFrames } from './utils' import { calculateFrameCenterTime, resolveTotalFrames } from './utils'
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar' import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
import { MobileVideoControlBar } from './mobile-video-control-bar' import { MobileVideoControlBar } from './mobile-video-control-bar'
@@ -269,7 +271,12 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const isAudio = data.proxyType === 'audio' const isAudio = data.proxyType === 'audio'
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate }) const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames, isAudio) const { currentFrame, seekToFrame, pauseForScrub } = useFramePlayer(
videoRef,
frameRate,
totalFrames,
isAudio,
)
const handleSeekToFrame = useCallback( const handleSeekToFrame = useCallback(
(frame: number) => { (frame: number) => {
@@ -283,7 +290,19 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
[seekToFrame], [seekToFrame],
) )
const currentTime = currentFrame / frameRate const targetSrc = isHls ? (data.media?.hls?.url ?? '') : (getInitialResolution()?.url ?? '')
const { scrub, scrubFrame, previewTime } = useVideoScrub({
videoRef,
assetId: data.id,
source: state.currentSrc ?? targetSrc,
totalFrames,
frameRate,
pauseForScrub,
seekToFrame: handleSeekToFrame,
})
const displayFrame = scrubFrame ?? currentFrame
const isScrubbing = scrubFrame !== null
const currentTime = displayFrame / frameRate
const duration = totalFrames / frameRate const duration = totalFrames / frameRate
const progress = duration > 0 ? (currentTime / duration) * 100 : 0 const progress = duration > 0 ? (currentTime / duration) * 100 : 0
@@ -305,8 +324,6 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}, [currentFrame, frameRate, onTimeUpdate]) }, [currentFrame, frameRate, onTimeUpdate])
// Initialize player (Hls.js or native HTML5 video) // Initialize player (Hls.js or native HTML5 video)
const targetSrc = isHls ? (data.media?.hls?.url ?? '') : (getInitialResolution()?.url ?? '')
useEffect(() => { useEffect(() => {
const video = videoRef.current const video = videoRef.current
if (!video) return if (!video) return
@@ -629,7 +646,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
// -- Event Handlers -- // -- Event Handlers --
const togglePlay = useCallback(() => { const togglePlay = useCallback(() => {
if (isLoading) return if (isLoading || isScrubbing) return
// Disable click-to-play if drawing // Disable click-to-play if drawing
if (useAnnotationStore.getState().isDrawing) return if (useAnnotationStore.getState().isDrawing) return
@@ -653,7 +670,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
} else { } else {
video.pause() video.pause()
} }
}, [isLoading]) }, [isLoading, isScrubbing])
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { const handleKeyDown = (e: KeyboardEvent) => {
@@ -1036,6 +1053,13 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
preload="auto" preload="auto"
poster={data.preview?.thumbnailUrl || undefined} poster={data.preview?.thumbnailUrl || undefined}
/> />
{data.media?.videoPreview?.url && (
<ScrubPreview
key={data.media.videoPreview.url}
url={data.media.videoPreview.url}
time={previewTime}
/>
)}
</div> </div>
)} )}
{isAudio && ( {isAudio && (
@@ -1095,7 +1119,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
)} )}
{/* Initial Big Play Button Overlay (shown only before playback starts) */} {/* Initial Big Play Button Overlay (shown only before playback starts) */}
{!isLoading && !hasStartedPlaying && !isDrawing && ( {!isLoading && !hasStartedPlaying && !isDrawing && !isScrubbing && (
<div <div
className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200" className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200"
data-testid="video-play-overlay" data-testid="video-play-overlay"
@@ -1128,8 +1152,9 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onZoomReset={handleZoomReset} onZoomReset={handleZoomReset}
frameRate={frameRate} frameRate={frameRate}
totalFrames={totalFrames} totalFrames={totalFrames}
currentFrame={currentFrame} currentFrame={displayFrame}
seekToFrame={handleSeekToFrame} seekToFrame={handleSeekToFrame}
scrub={isAudio ? undefined : scrub}
onMouseEnter={handleControlsMouseEnter} onMouseEnter={handleControlsMouseEnter}
onMouseLeave={handleControlsMouseLeave} onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload} allowDownload={allowDownload}
@@ -1155,8 +1180,9 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onZoomReset={handleZoomReset} onZoomReset={handleZoomReset}
frameRate={frameRate} frameRate={frameRate}
totalFrames={totalFrames} totalFrames={totalFrames}
currentFrame={currentFrame} currentFrame={displayFrame}
seekToFrame={handleSeekToFrame} seekToFrame={handleSeekToFrame}
scrub={isAudio ? undefined : scrub}
onMouseEnter={handleControlsMouseEnter} onMouseEnter={handleControlsMouseEnter}
onMouseLeave={handleControlsMouseLeave} onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload} allowDownload={allowDownload}
+1
View File
@@ -147,6 +147,7 @@ export const longAudioVideoAsset: AssetInfo = {
size: 6170, size: 6170,
}, },
], ],
videoPreview: { url: SAMPLE_VIDEO_URL },
metadata: { metadata: {
duration: LONG_AUDIO_DURATION, duration: LONG_AUDIO_DURATION,
originalWidth: SAMPLE_WIDTH, originalWidth: SAMPLE_WIDTH,
@@ -0,0 +1,71 @@
import { expect, test } from '@playwright/test'
import { VideoPlayerPage } from '../pages/video-player.page'
import { LONG_AUDIO_COMPUTED_TOTAL_FRAMES } from '../harness/fixture'
test('scrubs the preview while playing and seeks the main video once on release', async ({
page,
}) => {
const player = new VideoPlayerPage(page)
await player.gotoVariant('long-audio')
await player.muteNativeVideo()
await player.clickPlayToggle()
await expect.poll(() => player.isPaused()).toBe(false)
await player.video.evaluate((video: HTMLVideoElement) => {
video.dataset.seekCount = '0'
video.addEventListener('seeking', () => {
video.dataset.seekCount = String(Number(video.dataset.seekCount) + 1)
})
})
const track = await player.seekbar.boundingBox()
expect(track).not.toBeNull()
if (!track) throw new Error('Seekbar is not visible')
const moveToFrame = (frame: number) =>
page.mouse.move(
track.x + (track.width * frame) / LONG_AUDIO_COMPUTED_TOTAL_FRAMES,
track.y + track.height / 2,
)
const preview = page.getByTestId('scrub-preview')
const tooltip = player.seekbar.locator('video').last()
await moveToFrame(20)
await expect(tooltip).toBeVisible()
await page.mouse.down()
await moveToFrame(70)
await expect.poll(() => player.isPaused()).toBe(true)
const pausedTime = await player.currentTime()
await expect(preview).toBeVisible()
await expect(tooltip).toBeHidden()
await moveToFrame(105)
await expect(player.timeReadout).toHaveText('105 / 194 fr')
await expect
.poll(() => preview.evaluate((video: HTMLVideoElement) => video.currentTime))
.toBeCloseTo(3.5, 1)
expect(await player.currentTime()).toBeCloseTo(pausedTime, 3)
await expect(player.video).toHaveAttribute('data-seek-count', '0')
await page.mouse.up()
await expect(preview).toBeHidden()
await expect(player.video).toHaveAttribute('data-seek-count', '1')
await expect.poll(() => player.isPaused()).toBe(false)
expect(await player.currentTime()).toBeGreaterThanOrEqual(3.5)
})
test('seeks on release and stays paused when the preview is missing', async ({ page }) => {
const player = new VideoPlayerPage(page)
await player.goto()
const track = await player.seekbar.boundingBox()
if (!track) throw new Error('Seekbar is not visible')
const y = track.y + track.height / 2
await page.mouse.move(track.x + track.width * 0.2, y)
await page.mouse.down()
await page.mouse.move(track.x + track.width * 0.6, y)
await expect(player.timeReadout).toHaveText('90 / 149 fr')
expect(await player.currentTime()).toBeLessThan(0.1)
await page.mouse.up()
await expect.poll(() => player.currentTime()).toBeCloseTo(3.017, 2)
await expect(player.timeReadout).toHaveText('90 / 149 fr')
expect(await player.isPaused()).toBe(true)
})