diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d619e79..dcbad37d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens. - **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open. - **video**: Use **Generate Transcripts** in a video's context menu to save a transcript with the local embedding server. Choose a language or let the server detect it automatically. -- **video**: Open saved transcripts from the video player, switch languages, search the text, and jump to a timestamp by selecting a segment. Follow along as the video plays. +- **video**: Open saved transcripts from the video player, switch languages, search the text, and jump to the exact start of a segment by selecting it. Follow along as the video plays. ### Fixed diff --git a/apps/web/e2e/tests/file/view-transcript.spec.ts b/apps/web/e2e/tests/file/view-transcript.spec.ts index cf83c0d1..136ed110 100644 --- a/apps/web/e2e/tests/file/view-transcript.spec.ts +++ b/apps/web/e2e/tests/file/view-transcript.spec.ts @@ -32,6 +32,7 @@ test('reads, searches and follows a saved transcript in the video player', async text: `Intervening segment ${index + 1}`, })), { position: 29, startMs: 720, endMs: 980, text: 'Final signal.' }, + { position: 30, startMs: 995, endMs: 1000, text: 'Closing word.' }, ], }, }, @@ -122,6 +123,19 @@ test('reads, searches and follows a saved transcript in the video player', async await expect(last).toHaveAttribute('aria-current', 'true') await expect(video).toHaveJSProperty('paused', true) + const closingWord = panel.getByRole('button', { name: /Closing word\./ }) + await closingWord.click() + await expect + .poll(() => + video.evaluate((element) => { + const media = element as HTMLVideoElement + return { seeking: media.seeking, timeMs: Math.round(media.currentTime * 1000) } + }), + ) + .toEqual({ seeking: false, timeMs: 995 }) + await expect(closingWord).toHaveAttribute('aria-current', 'true') + await expect(video).toHaveJSProperty('paused', true) + await panel.getByRole('combobox', { name: 'Language' }).selectOption('zh') await expect(panel.getByText('你好。')).toBeVisible() await expect(last).toHaveCount(0) diff --git a/packages/webui/components/file-viewer/transcript-panel.tsx b/packages/webui/components/file-viewer/transcript-panel.tsx index 06097002..fb554902 100644 --- a/packages/webui/components/file-viewer/transcript-panel.tsx +++ b/packages/webui/components/file-viewer/transcript-panel.tsx @@ -88,7 +88,7 @@ const SegmentRow = memo(function SegmentRow({ ) { return } - mediaControllerRef.current?.seekTo(segment.startMs / 1000) + mediaControllerRef.current?.seekTo(segment.startMs / 1000, { exact: true }) }} > diff --git a/packages/webui/components/file-viewer/transcript-timeline.test.ts b/packages/webui/components/file-viewer/transcript-timeline.test.ts index 7a8d368c..4dc473ed 100644 --- a/packages/webui/components/file-viewer/transcript-timeline.test.ts +++ b/packages/webui/components/file-viewer/transcript-timeline.test.ts @@ -29,4 +29,14 @@ describe('createTranscriptTimeline', () => { expect(at(4000)).toBeUndefined() expect(createTranscriptTimeline([])(0)).toBeUndefined() }) + + it('uses the new segment at an exact millisecond after converting the seek through seconds', () => { + const at = createTranscriptTimeline([ + { id: 'before', startMs: 1800, endMs: 2010, text: '' }, + { id: 'after', startMs: 2010, endMs: 2200, text: '' }, + ]) + + expect(at(2009.999)).toBe('before') + expect(at((2010 / 1000) * 1000)).toBe('after') + }) }) diff --git a/packages/webui/components/file-viewer/transcript-timeline.ts b/packages/webui/components/file-viewer/transcript-timeline.ts index 9da31491..6b670ffa 100644 --- a/packages/webui/components/file-viewer/transcript-timeline.ts +++ b/packages/webui/components/file-viewer/transcript-timeline.ts @@ -8,7 +8,9 @@ export function createTranscriptTimeline(segments: TranscriptSegment[]) { return { segment, latestEndMs } }) - return (timeMs: number): string | undefined => { + return (playbackTimeMs: number): string | undefined => { + // Remove floating-point noise around millisecond boundaries while keeping microsecond precision. + const timeMs = Math.round(playbackTimeMs * 1000) / 1000 let first = 0 let last = timeline.length while (first < last) { diff --git a/packages/webui/components/viewers/types.ts b/packages/webui/components/viewers/types.ts index e3564de0..72c141d6 100644 --- a/packages/webui/components/viewers/types.ts +++ b/packages/webui/components/viewers/types.ts @@ -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 diff --git a/packages/webui/components/viewers/video/use-frame-player.test.ts b/packages/webui/components/viewers/video/use-frame-player.test.ts index 7f2cfac2..08554e0e 100644 --- a/packages/webui/components/viewers/video/use-frame-player.test.ts +++ b/packages/webui/components/viewers/video/use-frame-player.test.ts @@ -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 | 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[] = [] + 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 | 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[] = [] + 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() diff --git a/packages/webui/components/viewers/video/use-frame-player.ts b/packages/webui/components/viewers/video/use-frame-player.ts index 882a5bad..93a062ab 100644 --- a/packages/webui/components/viewers/video/use-frame-player.ts +++ b/packages/webui/components/viewers/video/use-frame-player.ts @@ -5,10 +5,22 @@ export interface UseFramePlayerResult { currentFrame: number setCurrentFrame: React.Dispatch> seekToFrame: (targetFrame: number) => Promise + seekToTime: (second: number, exact?: boolean) => Promise pauseForScrub: () => void isSeeking: React.RefObject } +interface SeekTarget { + frame: number + exactSecond?: number +} + +interface SeekSession { + completion: Promise | 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(0) const isSeekingRef = useRef(false) - const seekCompletionRef = useRef | null>(null) + const exactSeekRef = useRef<{ video: HTMLVideoElement; second: number } | null>(null) + const seekSessionRef = useRef(null) const isPlayingRef = useRef(false) - const pendingSeekFrameRef = useRef(null) const scrubPauseRef = useRef(false) const currentFrameRef = useRef(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((resolve) => { - let timeoutId: ReturnType | 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, } diff --git a/packages/webui/components/viewers/video/video-viewer.tsx b/packages/webui/components/viewers/video/video-viewer.tsx index 117bb0bf..da2ff277 100644 --- a/packages/webui/components/viewers/video/video-viewer.tsx +++ b/packages/webui/components/viewers/video/video-viewer.tsx @@ -126,15 +126,13 @@ const VideoViewer = React.forwardRef( 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( 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,