fix(video): preserve transcript seek timestamps

This commit is contained in:
yiling
2026-12-03 15:25:28 +08:00
parent 3952928b88
commit 5daa2a8f92
9 changed files with 262 additions and 44 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ import type React from 'react'
export interface MediaController {
play: () => void
pause: () => void
seekTo: (second: number) => void
seekTo: (second: number, options?: { exact?: boolean }) => void
getCurrentTime?: () => number
getDuration?: () => number
subscribeToPlaybackTime?: (listener: (second: number) => void) => (() => void) | undefined
@@ -109,6 +109,136 @@ afterEach(() => {
// --- Tests --------------------------------------------------------------------
describe('useFramePlayer exact timestamp seeking', () => {
it.each([true, false])('keeps the settled timestamp with paused=%s', async (paused) => {
const video = new FakeVideo()
video.paused = paused
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
let exactSeek: Promise<void> | undefined
act(() => {
exactSeek = result.current.seekToTime(0.995, true)
})
await act(async () => {
video.dispatchEvent(new Event('seeked'))
await exactSeek
})
expect(video.currentTime).toBe(0.995)
expect(video.paused).toBe(paused)
expect(result.current.currentFrame).toBe(29)
act(() => {
video.currentTime = 0.996
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBeCloseTo(29.5 / 30)
})
it('keeps the latest transcript seek queued behind a frame seek when playback is paused mid-seek', async () => {
const video = new FakeVideo()
video.paused = false
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
const seeks: Promise<void>[] = []
act(() => {
seeks.push(result.current.seekToFrame(18))
seeks.push(result.current.seekToTime(0.005, true))
seeks.push(result.current.seekToTime(0.995, true))
})
expect(video.currentTime).toBeCloseTo(18.5 / 30)
await act(async () => {
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBe(0.995)
act(() => video.pause())
await act(async () => {
video.dispatchEvent(new Event('seeked'))
await Promise.all(seeks)
})
expect(video.currentTime).toBe(0.995)
expect(video.paused).toBe(true)
expect(result.current.currentFrame).toBe(29)
})
it('keeps the exact timestamp when the native seek completes after the seek queue times out', async () => {
vi.useFakeTimers()
try {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
let exactSeek: Promise<void> | undefined
act(() => {
exactSeek = result.current.seekToTime(0.995, true)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(501)
await exactSeek
})
act(() => video.dispatchEvent(new Event('seeked')))
expect(video.currentTime).toBe(0.995)
} finally {
vi.useRealTimers()
}
})
it.each(['controller', 'native'] as const)(
'lets a newer ordinary %s seek supersede a timed-out exact seek',
async (source) => {
vi.useFakeTimers()
try {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
await act(async () => {
const exactSeek = result.current.seekToTime(0.995, true)
await vi.advanceTimersByTimeAsync(501)
await exactSeek
})
act(() => {
if (source === 'controller') {
void result.current.seekToTime(0.995)
} else {
video.currentTime = 0.996
}
video.dispatchEvent(new Event('seeking'))
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBeCloseTo(29.5 / 30)
} finally {
vi.useRealTimers()
}
},
)
it('lets a comment seek supersede both the active and queued transcript seeks', async () => {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
const transcriptSeeks: Promise<void>[] = []
act(() => {
transcriptSeeks.push(result.current.seekToTime(0.5, true))
transcriptSeeks.push(result.current.seekToTime(0.7, true))
void result.current.seekToTime(0.996)
})
expect(video.currentTime).toBe(0.996)
await act(async () => video.dispatchEvent(new Event('seeked')))
expect(video.currentTime).toBeCloseTo(29.5 / 30)
await Promise.all(transcriptSeeks)
expect(result.current.currentFrame).toBe(29)
})
})
describe('useFramePlayer Safari playhead synchronization', () => {
it('does not rewind the playhead on play when currentTime leads the presented frame', () => {
const video = new FakeVideo()
@@ -5,10 +5,22 @@ export interface UseFramePlayerResult {
currentFrame: number
setCurrentFrame: React.Dispatch<React.SetStateAction<number>>
seekToFrame: (targetFrame: number) => Promise<void>
seekToTime: (second: number, exact?: boolean) => Promise<void>
pauseForScrub: () => void
isSeeking: React.RefObject<boolean>
}
interface SeekTarget {
frame: number
exactSecond?: number
}
interface SeekSession {
completion: Promise<void> | null
pending: SeekTarget | null
finishWait: (() => void) | null
}
interface HtmlVideoElementWithCallback {
requestVideoFrameCallback?: (
callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void,
@@ -29,9 +41,9 @@ export function useFramePlayer(
): UseFramePlayerResult {
const [currentFrame, setCurrentFrame] = useState<number>(0)
const isSeekingRef = useRef<boolean>(false)
const seekCompletionRef = useRef<Promise<void> | null>(null)
const exactSeekRef = useRef<{ video: HTMLVideoElement; second: number } | null>(null)
const seekSessionRef = useRef<SeekSession | null>(null)
const isPlayingRef = useRef<boolean>(false)
const pendingSeekFrameRef = useRef<number | null>(null)
const scrubPauseRef = useRef(false)
const currentFrameRef = useRef<number>(currentFrame)
currentFrameRef.current = currentFrame
@@ -186,7 +198,9 @@ export function useFramePlayer(
// 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
if (!video.ended && !scrubPause) {
const exactSeekPending =
exactSeekRef.current?.video === video && (isSeekingRef.current || video.seeking)
if (!video.ended && !scrubPause && !exactSeekPending) {
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
video.currentTime = safeCenterTime
}
@@ -237,47 +251,50 @@ export function useFramePlayer(
}
}, [videoRef])
const seekToFrame = useCallback(
async (targetFrame: number) => {
const seek = useCallback(
async (target: SeekTarget) => {
const video = videoRef.current
if (!video) return
const roundedFrame = Math.round(targetFrame)
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 (seekCompletionRef.current) {
pendingSeekFrameRef.current = clampedFrame
setCurrentFrame(clampedFrame)
return seekCompletionRef.current
const activeSession = seekSessionRef.current
if (activeSession?.completion) {
activeSession.pending = target
setCurrentFrame(target.frame)
return activeSession.completion
}
const session: SeekSession = { completion: null, pending: null, finishWait: null }
seekSessionRef.current = session
isSeekingRef.current = true
setCurrentFrame(clampedFrame) // Optimistic update for active seek
setCurrentFrame(target.frame) // Optimistic update for active seek
const performSeek = async (frameToSeek: number) => {
const safeTargetTime = calculateFrameCenterTime(frameToSeek, frameRate)
const performSeek = async ({ frame, exactSecond }: SeekTarget) => {
exactSeekRef.current = exactSecond === undefined ? null : { video, second: exactSecond }
const wasPlaying = !video.paused
video.currentTime = safeTargetTime
video.currentTime = exactSecond ?? calculateFrameCenterTime(frame, frameRate)
// Wait for native seek to complete (with a 500ms fallback timeout to prevent hanging)
await new Promise<void>((resolve) => {
let timeoutId: ReturnType<typeof setTimeout> | null = null
const onSeeked = () => {
if (timeoutId) clearTimeout(timeoutId)
const finishWait = () => {
clearTimeout(timeoutId)
video.removeEventListener('seeked', onSeeked)
session.finishWait = null
resolve()
}
const onSeeked = () => {
if (!video.seeking) finishWait()
}
const timeoutId = setTimeout(finishWait, 500)
session.finishWait = finishWait
video.addEventListener('seeked', onSeeked)
timeoutId = setTimeout(() => {
video.removeEventListener('seeked', onSeeked)
resolve()
}, 500)
})
if (seekSessionRef.current !== session) return
// Pause only if we started paused and the user hasn't pressed play in the meantime
if (!wasPlaying && !isPlayingRef.current) {
if (exactSecond === undefined && !wasPlaying && !isPlayingRef.current) {
video.pause()
}
@@ -300,25 +317,55 @@ export function useFramePlayer(
const runSeeks = async () => {
try {
// 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
let next: SeekTarget | null = target
while (next !== null && seekSessionRef.current === session) {
await performSeek(next)
next = session.pending
session.pending = null
}
} finally {
seekCompletionRef.current = null
pendingSeekFrameRef.current = null
isSeekingRef.current = false
if (seekSessionRef.current === session) {
seekSessionRef.current = null
isSeekingRef.current = false
}
}
}
seekCompletionRef.current = runSeeks()
await seekCompletionRef.current
session.completion = runSeeks()
return session.completion
},
[videoRef, frameRate, totalFrames],
)
const seekToFrame = useCallback(
(targetFrame: number) =>
seek({ frame: Math.max(0, Math.min(Math.round(targetFrame), totalFrames - 1)) }),
[seek, totalFrames],
)
const seekToTime = useCallback(
(second: number, exact = false) => {
if (!exact) {
// Ordinary timestamp seeks take effect immediately, superseding queued frame and transcript seeks.
const previousSession = seekSessionRef.current
seekSessionRef.current = null
isSeekingRef.current = false
previousSession?.finishWait?.()
exactSeekRef.current = null
const video = videoRef.current
if (video) video.currentTime = second
return Promise.resolve()
}
const frame = Math.floor(second * frameRate + 0.45)
return seek({
frame: Math.max(0, Math.min(frame, totalFrames - 1)),
exactSecond: second,
})
},
[seek, videoRef, frameRate, totalFrames],
)
// Keyboard Shortcuts Keydown Listener
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -353,12 +400,26 @@ export function useFramePlayer(
const video = videoRef.current
if (!video) return
const handleSeeking = () => {
const exactSeek = exactSeekRef.current
// A newer native seek can replace the pending target.
if (exactSeek?.video === video && Math.abs(exactSeek.second - video.currentTime) > 0.000001) {
exactSeekRef.current = null
}
}
const handleExternalSeeked = () => {
// Only sync if this seek was not triggered internally by seekToFrame
if (video.seeking) return
// The queue may have timed out while the browser was still seeking.
const preserveTime = exactSeekRef.current?.video === video
if (preserveTime) exactSeekRef.current = null
// The queue updates its own seeks when they settle.
if (!isSeekingRef.current) {
const actualFrame = Math.floor(video.currentTime * frameRate + 0.45)
const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1))
setCurrentFrame(finalFrame)
if (preserveTime) return
// Nudge to safe frame center to guarantee correct browser decoding
const safeCenterTime = calculateFrameCenterTime(finalFrame, frameRate)
@@ -369,8 +430,10 @@ export function useFramePlayer(
}
}
video.addEventListener('seeking', handleSeeking)
video.addEventListener('seeked', handleExternalSeeked)
return () => {
video.removeEventListener('seeking', handleSeeking)
video.removeEventListener('seeked', handleExternalSeeked)
}
}, [videoRef.current, frameRate, totalFrames])
@@ -379,6 +442,7 @@ export function useFramePlayer(
currentFrame,
setCurrentFrame,
seekToFrame,
seekToTime,
pauseForScrub,
isSeeking: isSeekingRef,
}
@@ -126,15 +126,13 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
pause: () => {
videoRef.current?.pause()
},
seekTo: (second: number) => {
seekTo: (second, options) => {
if (pendingResolutionCorrectionRef.current) {
pendingResolutionCorrectionRef.current()
pendingResolutionCorrectionRef.current = null
}
setHasStartedPlaying(true)
if (videoRef.current) {
videoRef.current.currentTime = second
}
void seekToTime(second, options?.exact)
},
getCurrentTime: () => {
return (videoRef.current ? videoRef.current.currentTime : 0) ?? 0
@@ -288,7 +286,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const isAudio = data.proxyType === 'audio'
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const { currentFrame, seekToFrame, pauseForScrub } = useFramePlayer(
const { currentFrame, seekToFrame, seekToTime, pauseForScrub } = useFramePlayer(
videoRef,
frameRate,
totalFrames,