From 14f6752de2fa3f22dbbee29e6c36bb62c54704c2 Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 29 Jun 2026 19:48:28 +0800 Subject: [PATCH 01/10] fix(webui): align video timeline duration and formatting with frameio --- .../webui/components/viewers/video-player.tsx | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 8376d57f..6c406e3a 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -27,7 +27,7 @@ import { } from '../ui/dropdown-menu' import { Slider } from '../ui/slider' import ProgressBar from './progress-bar' -import { formatTimecode } from './utils' +import { formatTimecode, formatTime } from './utils' import { useFramePlayer } from './use-frame-player' import { useUiStore } from '@/ui/stores/ui' @@ -120,7 +120,9 @@ const ControlBar: React.FC = ({ const displayString = videoTimeDisplayMode === 'frames' ? `${currentFrame} / ${displayTotalFrames} fr` - : `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}` + : videoTimeDisplayMode === 'standard' + ? `${formatTimecode(currentFrame, frameRate, 'standard')} / ${formatTime(totalFrames / frameRate)}` + : `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}` return (
= ({ // Frame-accurate hook and derived state const metadata = data.media.metadata const frameRate = metadata.frameRate || 30 - const totalFrames = metadata.totalFrames || 0 + const dbTotalFrames = metadata.totalFrames || 0 + const containerDuration = metadata.duration || 0 + const videoDuration = dbTotalFrames / frameRate + const frameDuration = 1 / frameRate + + const totalFrames = + containerDuration - videoDuration > 0.5 * frameDuration + ? Math.round(containerDuration * frameRate) + : dbTotalFrames const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames) const currentTime = currentFrame / frameRate From 9fd707b23f33901253c1b28af3d79c788f2a98bb Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 29 Jun 2026 20:16:06 +0800 Subject: [PATCH 02/10] fix(webui): fallback to requestAnimationFrame when video track freezes --- packages/webui/components/viewers/use-frame-player.ts | 10 +++++++--- packages/webui/components/viewers/video-player.tsx | 7 ++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts index bd7bb069..acdafde3 100644 --- a/packages/webui/components/viewers/use-frame-player.ts +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -19,6 +19,7 @@ export function useFramePlayer( videoRef: React.RefObject, frameRate: number, totalFrames: number, + videoTrackFrames?: number, ): UseFramePlayerResult { const [currentFrame, setCurrentFrame] = useState(0) const isSeekingRef = useRef(false) @@ -68,7 +69,10 @@ export function useFramePlayer( } const videoWithCallback = video as unknown as HtmlVideoElementWithCallback - if (videoWithCallback.requestVideoFrameCallback) { + const isPastVideoTrack = + videoTrackFrames !== undefined && video.currentTime >= (videoTrackFrames - 1) / frameRate + + if (videoWithCallback.requestVideoFrameCallback && !isPastVideoTrack) { rVfcId = videoWithCallback.requestVideoFrameCallback( (_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => { const frame = Math.round(metadata.mediaTime * frameRate) @@ -79,7 +83,7 @@ export function useFramePlayer( }, ) } else { - // Fallback for browsers without requestVideoFrameCallback + // Fallback for browsers without requestVideoFrameCallback or when video track is frozen const frame = Math.round(video.currentTime * frameRate) const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) setCurrentFrame(clamped) @@ -140,7 +144,7 @@ export function useFramePlayer( cancelAnimationFrame(rafId) } } - }, [videoRef.current, frameRate, totalFrames]) + }, [videoRef.current, frameRate, totalFrames, videoTrackFrames]) const seekToFrame = useCallback( async (targetFrame: number) => { diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 6c406e3a..60b9bcc9 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -520,7 +520,12 @@ const VideoPlayer: React.FC = ({ containerDuration - videoDuration > 0.5 * frameDuration ? Math.round(containerDuration * frameRate) : dbTotalFrames - const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames) + const { currentFrame, seekToFrame } = useFramePlayer( + videoRef, + frameRate, + totalFrames, + dbTotalFrames, + ) const currentTime = currentFrame / frameRate const duration = totalFrames / frameRate From 9c8f29e3ba03a11ff73bd679e5dafc00b292f408 Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 29 Jun 2026 20:19:15 +0800 Subject: [PATCH 03/10] fix(webui): unify playhead loop with requestAnimationFrame to prevent deadlock --- .../components/viewers/use-frame-player.ts | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts index acdafde3..4f07651c 100644 --- a/packages/webui/components/viewers/use-frame-player.ts +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useRef, useCallback } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' import { calculateFrameCenterTime } from './utils' export interface UseFramePlayerResult { @@ -72,22 +72,24 @@ export function useFramePlayer( const isPastVideoTrack = videoTrackFrames !== undefined && video.currentTime >= (videoTrackFrames - 1) / frameRate - if (videoWithCallback.requestVideoFrameCallback && !isPastVideoTrack) { + // Drive playhead update using requestAnimationFrame + const frame = Math.round(video.currentTime * frameRate) + const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) + setCurrentFrame(clamped) + + // Always schedule next update tick via requestAnimationFrame (avoids deadlocks when compositor freezes) + rafId = requestAnimationFrame(updateFrameLoop) + + // Schedule video frame callback for frame presentation synchronization if active + if (videoWithCallback.requestVideoFrameCallback && !isPastVideoTrack && rVfcId === null) { rVfcId = videoWithCallback.requestVideoFrameCallback( (_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => { - const frame = Math.round(metadata.mediaTime * frameRate) - const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) - setCurrentFrame(clamped) - // Continue the loop - updateFrameLoop() + rVfcId = null + const compositorFrame = Math.round(metadata.mediaTime * frameRate) + const compositorClamped = Math.max(0, Math.min(compositorFrame, totalFrames - 1)) + setCurrentFrame(compositorClamped) }, ) - } else { - // Fallback for browsers without requestVideoFrameCallback or when video track is frozen - const frame = Math.round(video.currentTime * frameRate) - const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) - setCurrentFrame(clamped) - rafId = requestAnimationFrame(updateFrameLoop) } } From 07d82377bd793bbf702ecc2d63a450f67c845773 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 09:47:13 +0800 Subject: [PATCH 04/10] fix(webui): implement dynamic stall threshold for requestVideoFrameCallback --- .../components/viewers/use-frame-player.ts | 35 +++++++++++++------ .../webui/components/viewers/video-player.tsx | 7 +--- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts index 4f07651c..bc0b2f72 100644 --- a/packages/webui/components/viewers/use-frame-player.ts +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -19,7 +19,6 @@ export function useFramePlayer( videoRef: React.RefObject, frameRate: number, totalFrames: number, - videoTrackFrames?: number, ): UseFramePlayerResult { const [currentFrame, setCurrentFrame] = useState(0) const isSeekingRef = useRef(false) @@ -60,6 +59,7 @@ export function useFramePlayer( let rVfcId: number | null = null let rafId: number | null = null let active = true + let lastVfcTime = Date.now() const updateFrameLoop = () => { if (!active) return @@ -69,22 +69,35 @@ export function useFramePlayer( } const videoWithCallback = video as unknown as HtmlVideoElementWithCallback - const isPastVideoTrack = - videoTrackFrames !== undefined && video.currentTime >= (videoTrackFrames - 1) / frameRate - // Drive playhead update using requestAnimationFrame - const frame = Math.round(video.currentTime * frameRate) - const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) - setCurrentFrame(clamped) + // Calculate dynamic stall threshold (minimum 100ms, or 3 frames of duration) + const stallThreshold = Math.max(100, 3000 / frameRate) + const isVfcStalled = Date.now() - lastVfcTime > stallThreshold - // Always schedule next update tick via requestAnimationFrame (avoids deadlocks when compositor freezes) + // Print debug log roughly once per second during playback + if (Math.round(video.currentTime * frameRate) % 30 === 0) { + console.log( + `[useFramePlayer] currentTime: ${video.currentTime}, isVfcStalled: ${isVfcStalled}, stallThreshold: ${stallThreshold}, totalFrames: ${totalFrames}`, + ) + } + + // Only update playhead via currentTime (RAF) if rVFC has stalled or isn't supported + if (!videoWithCallback.requestVideoFrameCallback || isVfcStalled) { + const frame = Math.round(video.currentTime * frameRate) + const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) + setCurrentFrame(clamped) + } + + // Always schedule the next update tick via requestAnimationFrame to keep the loop alive rafId = requestAnimationFrame(updateFrameLoop) - // Schedule video frame callback for frame presentation synchronization if active - if (videoWithCallback.requestVideoFrameCallback && !isPastVideoTrack && rVfcId === null) { + // Schedule video frame callback for compositor-accurate synchronization + if (videoWithCallback.requestVideoFrameCallback && rVfcId === null) { rVfcId = videoWithCallback.requestVideoFrameCallback( (_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => { rVfcId = null + lastVfcTime = Date.now() // Reset stall timer + const compositorFrame = Math.round(metadata.mediaTime * frameRate) const compositorClamped = Math.max(0, Math.min(compositorFrame, totalFrames - 1)) setCurrentFrame(compositorClamped) @@ -146,7 +159,7 @@ export function useFramePlayer( cancelAnimationFrame(rafId) } } - }, [videoRef.current, frameRate, totalFrames, videoTrackFrames]) + }, [videoRef.current, frameRate, totalFrames]) const seekToFrame = useCallback( async (targetFrame: number) => { diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 60b9bcc9..6c406e3a 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -520,12 +520,7 @@ const VideoPlayer: React.FC = ({ containerDuration - videoDuration > 0.5 * frameDuration ? Math.round(containerDuration * frameRate) : dbTotalFrames - const { currentFrame, seekToFrame } = useFramePlayer( - videoRef, - frameRate, - totalFrames, - dbTotalFrames, - ) + const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames) const currentTime = currentFrame / frameRate const duration = totalFrames / frameRate From 1704fddc67c3aa6c6b597d07e7e3230941fe37a2 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 10:22:32 +0800 Subject: [PATCH 05/10] refactor(webui): use Floor with Epsilon (0.001) for frame conversion calculations --- .../webui/components/viewers/use-frame-player.ts | 12 ++++++------ packages/webui/components/viewers/utils.ts | 4 ++-- packages/webui/components/viewers/video-player.tsx | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts index bc0b2f72..a508a60f 100644 --- a/packages/webui/components/viewers/use-frame-player.ts +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -75,7 +75,7 @@ export function useFramePlayer( const isVfcStalled = Date.now() - lastVfcTime > stallThreshold // Print debug log roughly once per second during playback - if (Math.round(video.currentTime * frameRate) % 30 === 0) { + if (Math.floor(video.currentTime * frameRate + 0.001) % 30 === 0) { console.log( `[useFramePlayer] currentTime: ${video.currentTime}, isVfcStalled: ${isVfcStalled}, stallThreshold: ${stallThreshold}, totalFrames: ${totalFrames}`, ) @@ -83,7 +83,7 @@ export function useFramePlayer( // Only update playhead via currentTime (RAF) if rVFC has stalled or isn't supported if (!videoWithCallback.requestVideoFrameCallback || isVfcStalled) { - const frame = Math.round(video.currentTime * frameRate) + const frame = Math.floor(video.currentTime * frameRate + 0.001) const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) setCurrentFrame(clamped) } @@ -98,7 +98,7 @@ export function useFramePlayer( rVfcId = null lastVfcTime = Date.now() // Reset stall timer - const compositorFrame = Math.round(metadata.mediaTime * frameRate) + const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.001) const compositorClamped = Math.max(0, Math.min(compositorFrame, totalFrames - 1)) setCurrentFrame(compositorClamped) }, @@ -128,7 +128,7 @@ export function useFramePlayer( } // Synchronize frame on pause - const frame = Math.round(video.currentTime * frameRate) + const frame = Math.floor(video.currentTime * frameRate + 0.001) const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) setCurrentFrame(clamped) } @@ -214,7 +214,7 @@ export function useFramePlayer( const videoWithCallback = video as unknown as HtmlVideoElementWithCallback if (videoWithCallback.requestVideoFrameCallback) { videoWithCallback.requestVideoFrameCallback((_now, metadata) => { - const compositorFrame = Math.round(metadata.mediaTime * frameRate) + const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.001) const verifiedFrame = Math.max(0, Math.min(compositorFrame, totalFrames - 1)) setCurrentFrame(verifiedFrame) }) @@ -272,7 +272,7 @@ export function useFramePlayer( const handleExternalSeeked = () => { // Only sync if this seek was not triggered internally by seekToFrame if (!isSeekingRef.current) { - const actualFrame = Math.round(video.currentTime * frameRate) + const actualFrame = Math.floor(video.currentTime * frameRate + 0.001) const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1)) setCurrentFrame(finalFrame) diff --git a/packages/webui/components/viewers/utils.ts b/packages/webui/components/viewers/utils.ts index e5790972..35a85d4f 100644 --- a/packages/webui/components/viewers/utils.ts +++ b/packages/webui/components/viewers/utils.ts @@ -80,13 +80,13 @@ export const formatTimecode = ( export const formatTimestamp = (seconds: number, fps: number): string => { if (isNaN(seconds)) return '00:00:00:00' - const frameIndex = Math.round(seconds * fps) + const frameIndex = Math.floor(seconds * fps + 0.001) return formatTimecode(frameIndex, fps, 'timecode') } export const formatFrame = (seconds: number, fps: number): number => { if (isNaN(seconds) || !fps) return 0 - return Math.floor(seconds * fps) + return Math.floor(seconds * fps + 0.001) } export const calculateFrameCenterTime = (frameIndex: number, frameRate: number): number => { diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 6c406e3a..285575db 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -653,7 +653,7 @@ const VideoPlayer: React.FC = ({ if (startTime !== undefined && startTime !== null && startTime > 0) { if (startTime !== lastProcessedStartTimeRef.current) { lastProcessedStartTimeRef.current = startTime - const targetFrame = Math.round(startTime * frameRate) + const targetFrame = Math.floor(startTime * frameRate + 0.001) seekToFrame(targetFrame) } } From 7cb1aa3c86da0ab8dba1b0824aa58274cddc73a9 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 10:34:19 +0800 Subject: [PATCH 06/10] docs(webui): add video player design document --- packages/webui/docs/video_player_design.md | 215 +++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 packages/webui/docs/video_player_design.md diff --git a/packages/webui/docs/video_player_design.md b/packages/webui/docs/video_player_design.md new file mode 100644 index 00000000..2b122c04 --- /dev/null +++ b/packages/webui/docs/video_player_design.md @@ -0,0 +1,215 @@ +# Frame-Accurate Video Player & Comment System: Technical Design Document + +This document outlines the technical design, mathematical formulas, synchronization loops, and database schemes that guarantee **100% frame-accurate playback, scrubbing, stepping, and comment navigation** in Shumai. + +--- + +## 1. Architectural Overview + +Shumai's video player is a decoupled, frame-locked system that coordinates three primary components around a single state coordinator (`useFramePlayer`): + +``` + ┌───────────────────────────┐ + │ useFramePlayer Hook │ + │ (State: currentFrame) │ + └──────┬─────────────▲──────┘ + │ │ + 1. Set currentTime │ │ 2. Sync frame index + (Frame Center Nudge)│ │ (Floor-with-Epsilon) + ▼ │ + ┌────────────────────────────┴──┐ + │ Native HTML5 Video Player │ + │ (VideoJS Engine Wrapper) │ + └───────────────────────────────┘ + ▲ ▲ + │ │ + Stepping / │ │ Comment Selection / + Scrubbing │ │ Timestamp Navigation + │ │ + ┌───────┴──────┐ ┌──────┴───────┐ + │ Seekbar │ │ Comments │ + │ (Progress) │ │ (Panel/List) │ + └──────────────┘ └──────────────┘ +``` + +1. **Native HTML5 Video Player (VideoJS Engine Wrapper):** Manages the underlying browser media stream, buffering, audio clock, and presentation. +2. **Seekbar (Scrubber & Progress Bar):** Visualizes playback progress and maps horizontal screen clicks/drags to playhead percentages. +3. **Comment Area (Sidebar):** Renders comment list, displays timestamp labels, captures drawings, and triggers seeks to target frames. + +--- + +## 2. Core Mathematical Foundations + +To achieve frame-accurate synchronization across different browsers (which use floating-point double precision for playhead timestamps), we utilize three key mathematical formulas: + +### A. Frame-to-Time Boundary Formula +When generating timestamps for external storage (such as database comments), we calculate the exact **start boundary time** of the frame. This avoids carrying floating-point errors into the database: + +$$\text{Time}_{\text{boundary}} = \frac{N}{\text{frameRate}}$$ + +*Where $N$ is the integer frame index ($0$-indexed).* + +--- + +### B. Time-to-Frame Conversion (Floor with Epsilon) +When converting a raw player timestamp ($t$) back to an integer frame index, we use a **Floor with Epsilon** formula to absorb sub-millisecond clock drift and presentation lag without triggering premature frame jumps: + +$$\text{Frame} = \lfloor(t \cdot \text{frameRate}) + \epsilon\rfloor$$ + +*Where $\epsilon = 0.001$ frames.* +* **Start Boundary Guard:** If the browser reports time slightly early due to float precision (e.g. $119.9999$ frames instead of $120.0$), the $+ 0.001$ bumps it to $120.0009$, flooring correctly to Frame `120`. +* **Late Pause Guard:** If the playhead stops very late in the frame (e.g. $120.96$ frames), adding `0.001` yields $120.961$, which still floors correctly to **Frame `120`**, matching what is actually displayed on the screen. + +--- + +### C. Safe Seek Time (Half-Frame Offset Center) +Browsers can occasionally render the previous frame if the playhead lands exactly on a frame boundary due to float rounding. To guarantee that seeking always lands squarely inside the target frame's presentation window, we seek to the **center of the frame**: + +$$\text{Time}_{\text{center}} = \left(N \cdot T_d\right) + \frac{T_d}{2} = \frac{N}{\text{frameRate}} + \frac{1}{2 \cdot \text{frameRate}}$$ + +*Where $T_d = \frac{1}{\text{frameRate}}$ is the duration of a single frame.* + +--- + +## 3. Active Playback Loops & Dual-Drive Coordination + +When playing, the playhead loop coordinates two mechanisms in parallel to prevent timeline freezes and avoid visual jitter: + +``` + ┌───────────────────┐ + │ Playback Started │ + └─────────┬─────────┘ + │ + ┌────────────┴────────────┐ + │ Start loops: RAF & │ + │ VFC (if supported) │ + └────────────┬────────────┘ + │ + ┌──────────────┴──────────────┐ + │ Is VFC Stalled (> Thresh)? │ + └─────┬─────────────────┬─────┘ + │ Yes │ No + ▼ ▼ + ┌───────────────────────┐ ┌───────────────────────┐ + │ Update UI using │ │ Update UI using │ + │ currentTime (RAF) │ │ mediaTime (VFC) │ + └───────────────────────┘ └───────────────────────┘ +``` + +1. **`requestVideoFrameCallback` (rVFC):** The primary driver when the video is actively decoding. It fires only when a new video frame is sent to the compositor, updating the UI frame-accurately based on `metadata.mediaTime`. +2. **`requestAnimationFrame` (RAF):** Runs continuously at 60Hz. It acts as the fallback driver. +3. **Stall Detection:** The playhead tracks when the last rVFC callback was fired. If it has been stalled for longer than the **dynamic stall threshold**: + $$\text{Threshold} = \max\left(100, \frac{3000}{\text{frameRate}}\right)\text{ ms}$$ + the RAF loop takes over playhead updates using `video.currentTime`. + + This prevents the timeline from freezing when the video track ends but audio keeps playing (e.g. video track ends at 10s, audio at 15.4s). + +--- + +## 4. Scenario Walkthroughs (User Operations) + +### A. Play Video +1. User clicks Play. +2. The `play` event listener triggers `updateFrameLoop()`. +3. If supported, `requestVideoFrameCallback` is registered. In parallel, `requestAnimationFrame` is scheduled recursively. +4. UI displays continuous updates aligned with compositor frames. + +--- + +### B. Pause Video +1. User clicks Pause. +2. The `pause` event listener triggers `handlePause()`: + * Cancels active VFC (`cancelVideoFrameCallback`) and RAF (`cancelAnimationFrame`) loops. + * Performs a final playhead synchronization: + $$\text{clampedFrame} = \max\left(0, \min\left(\lfloor(video.currentTime \cdot frameRate) + 0.001\rfloor, \text{totalFrames} - 1\right)\right)$$ + * Calls `setCurrentFrame(clampedFrame)` to lock the UI to the correct frame. + +--- + +### C. Drag Seekbar Head to a Timestamp +1. User clicks or drags on the seekbar track. +2. The progress bar computes the click horizontal percentage ($P$). +3. The player calculates the target frame: + $$\text{targetFrame} = \text{Math.round}(P \cdot \text{totalFrames})$$ +4. The player calls `seekToFrame(targetFrame)`: + * Sets `isSeekingRef.current = true` to lock the synchronization loop. + * Calculates the safe center time: `safeTargetTime = calculateFrameCenterTime(targetFrame, frameRate)`. + * Sets `video.currentTime = safeTargetTime`. + * Listens for the browser's native `seeked` event, then resets `isSeekingRef.current = false`. + +--- + +### D. Step Frame-by-Frame (Arrow Keys) +1. User presses `ArrowRight` (Next Frame) or `ArrowLeft` (Prev Frame). +2. The keydown handler intercepts the event, calculates the target frame index ($N \pm 1$), and calls `seekToFrame(targetFrame)`. +3. The video seeks to the safe center time of the adjacent frame, rendering it frame-accurately. + +--- + +### E. Pause Video and Create a Comment +1. User pauses the video (UI locks to integer `currentFrame`, e.g. `120`). +2. User writes a comment and clicks submit. +3. The comment creation form reads the `currentTime` prop, which is computed strictly from the frame index: + $$\text{currentTime} = \frac{\text{currentFrame}}{\text{frameRate}} = \frac{120}{23.976} = 5.005005\text{s}$$ +4. The API saves the exact frame boundary time `5.005005` in the database. + +--- + +### F. Click Comment to Jump to Comment-Timestamp +1. User clicks a comment in the sidebar. +2. The select handler calls: + ```typescript + videoRef.current.currentTime(comment.second) // e.g., 5.005005s + videoRef.current.pause() + ``` +3. The browser seeks the media element. Once finished, it fires the native `seeked` event. +4. The `handleExternalSeeked` listener in `useFramePlayer` triggers because `isSeekingRef.current` is `false`: + * Maps `video.currentTime` back to the frame index: + $$\text{finalFrame} = \lfloor(video.currentTime \cdot frameRate) + 0.001\rfloor = \lfloor(5.005005 \cdot 23.976) + 0.001\rfloor = 120$$ + * Computes the safe center time: `safeCenterTime = calculateFrameCenterTime(120, 23.976) = 5.025859s`. + * Detects if the current time is offset from the center by more than a quarter-frame: + $$\text{Math.abs}(5.005005 - 5.025859) = 0.020854\text{s} > \frac{0.041708}{4}\text{s}$$ + * Nudges the browser's playhead: `video.currentTime = safeCenterTime` (`5.025859`s). This forces the browser to render Frame 120 cleanly. + +--- + +### G. Switch Resolution +1. User selects a different resolution (e.g. `720p` or `Original`). +2. The player intercepts the click: + * Captures `wasPlaying = !player.paused()` and the current playhead time: `currentT = player.currentTime()`. + * Updates the source URL: `player.src({ type: 'video/mp4', src: res.url })`. +3. The player registers a one-shot `loadedmetadata` event listener on the new source: + * Restores playhead time: `player.currentTime(currentT)`. + * Restores playback state (`play()` if `wasPlaying` was true) and playback rate. +4. The seek triggered by `player.currentTime(currentT)` fires a `seeked` event, which automatically calls `handleExternalSeeked`, recalculating the frame index and nudging the playhead to the safe frame center on the new media stream. + +--- + +## 5. Backend Specifications + +### A. Transcode & Metadata Extraction +When a video is uploaded, the `@shumai/transcode` worker executes an `ffprobe` command to analyze the source container and streams: +```bash +ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate,duration,nb_frames -of default=noprint_wrappers=1:nocaveat=1 input.mp4 +``` +The extracted metadata details are saved to the `AssetMetadata` table: +* `frameRate` (e.g. `23.976` or `30`) +* `duration` (the absolute container duration, e.g. `15.42`) +* `totalFrames` (the physical number of frames in the video stream, e.g. `240`) + +--- + +### B. Database Schema +Comments are represented in the Prisma database schema by the `Comment` model: + +```prisma +model Comment { + id String @id @default(ulid()) + text String + second Decimal? @db.Decimal(10, 4) // Stores currentFrame / frameRate + fileId String + file Asset @relation(fields: [fileId], references: [id], onDelete: Cascade) + createdAt DateTime @default(now()) +} +``` +* **Precision:** The `second` column uses `Decimal(10, 4)` to store sub-millisecond timestamps accurately without rounding or floating-point truncation. From d2ee7f1c45788b607aee3abcf59ff9056aa5c59d Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 10:45:51 +0800 Subject: [PATCH 07/10] fix(webui): prevent initial scale fit layout race condition --- .../webui/components/viewers/video-player.tsx | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 285575db..5cdd6979 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -376,8 +376,14 @@ const VideoPlayer: React.FC = ({ const [videoHtmlEl, setVideoHtmlEl] = useState(undefined) const videoRef = useRef(null) const [zoom, setZoom] = useState(1) + const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false) const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }) + const handleZoomChange = (newZoom: number) => { + setZoom(newZoom) + setHasManuallyZoomed(true) + } + // Store const { isDrawing, @@ -406,20 +412,17 @@ const VideoPlayer: React.FC = ({ return () => observer.disconnect() }, []) - // Fit to screen initial + // Fit to screen initial / responsive resize useEffect(() => { if (containerSize.width > 0 && containerSize.height > 0) { - // Only if not already set or reset? - // Actually, we want to start fit. const vidW = data.media?.metadata?.originalWidth ?? 1920 const vidH = data.media?.metadata?.originalHeight ?? 1080 const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH) - // Only set if zoom is 1 (initial). - if (zoom === 1) { + if (!hasManuallyZoomed) { setZoom(scale) } } - }, [containerSize.width, containerSize.height, data.media?.metadata]) + }, [containerSize.width, containerSize.height, data.media?.metadata, hasManuallyZoomed]) // Cleanup ref when player is disposed useEffect(() => { @@ -922,7 +925,7 @@ const VideoPlayer: React.FC = ({ changeResolution={changeResolution} handleDownload={handleDownload} toggleFullScreen={toggleFullScreen} - onZoomChange={setZoom} + onZoomChange={handleZoomChange} frameRate={frameRate} totalFrames={totalFrames} currentFrame={currentFrame} From 86ad68a705710c82d61ced6188c9ad3b0e157adf Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 10:50:30 +0800 Subject: [PATCH 08/10] feat(webui): add Fit zoom button in video player control bar --- .../webui/components/viewers/video-player.tsx | 39 +++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 5cdd6979..97092b2b 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -79,6 +79,7 @@ interface ControlBarProps { handleDownload: (url: string, resolution: string) => void toggleFullScreen: () => void onZoomChange: (zoom: number) => void + onZoomReset: () => void // Frame-accurate props frameRate: number totalFrames: number @@ -102,6 +103,7 @@ const ControlBar: React.FC = ({ handleDownload, toggleFullScreen, onZoomChange, + onZoomReset, frameRate, totalFrames, currentFrame, @@ -248,19 +250,29 @@ const ControlBar: React.FC = ({ {/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
{/* Zoom Controls */} -
+
+
+ + + {Math.round(zoom * 100)}% + + +
- {Math.round(zoom * 100)}% -
@@ -384,6 +396,10 @@ const VideoPlayer: React.FC = ({ setHasManuallyZoomed(true) } + const handleZoomReset = () => { + setHasManuallyZoomed(false) + } + // Store const { isDrawing, @@ -926,6 +942,7 @@ const VideoPlayer: React.FC = ({ handleDownload={handleDownload} toggleFullScreen={toggleFullScreen} onZoomChange={handleZoomChange} + onZoomReset={handleZoomReset} frameRate={frameRate} totalFrames={totalFrames} currentFrame={currentFrame} From 954d8ee497f737feb80b0870b488499949c9487a Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 10:50:39 +0800 Subject: [PATCH 09/10] docs(webui): update video player design doc with Zoom Fit section --- packages/webui/docs/video_player_design.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/webui/docs/video_player_design.md b/packages/webui/docs/video_player_design.md index 2b122c04..bc409ae2 100644 --- a/packages/webui/docs/video_player_design.md +++ b/packages/webui/docs/video_player_design.md @@ -185,6 +185,17 @@ When playing, the playhead loop coordinates two mechanisms in parallel to preven --- +### H. Manual Zoom & Zoom Fit Reset +1. User adjusts zoom manually using the `Zoom In` (+) or `Zoom Out` (-) buttons: + * Sets `hasManuallyZoomed` to `true`. + * Sets the new manual scale, overriding any auto-scale layout behavior. +2. User clicks the **Fit** button: + * Resets `hasManuallyZoomed` to `false`. + * Triggers the responsive scale recalculation effect, mapping the video scale back to the layout container bounds: + $$\text{scale} = \min\left(\frac{\text{containerSize.width}}{\text{originalWidth}}, \frac{\text{containerSize.height}}{\text{originalHeight}}\right)$$ + +--- + ## 5. Backend Specifications ### A. Transcode & Metadata Extraction From 899b600417e9871074663240c4a575f6efa216c9 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 30 Jun 2026 11:10:53 +0800 Subject: [PATCH 10/10] fix(webui): resolve 1-frame comment mismatch via 0.45 offset and pause snapping --- .../components/viewers/use-frame-player.ts | 20 +++++++++++------- packages/webui/components/viewers/utils.ts | 4 ++-- .../webui/components/viewers/video-player.tsx | 2 +- packages/webui/docs/video_player_design.md | 21 ++++++++++--------- 4 files changed, 26 insertions(+), 21 deletions(-) diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts index a508a60f..001da55c 100644 --- a/packages/webui/components/viewers/use-frame-player.ts +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -75,7 +75,7 @@ export function useFramePlayer( const isVfcStalled = Date.now() - lastVfcTime > stallThreshold // Print debug log roughly once per second during playback - if (Math.floor(video.currentTime * frameRate + 0.001) % 30 === 0) { + if (Math.floor(video.currentTime * frameRate + 0.45) % 30 === 0) { console.log( `[useFramePlayer] currentTime: ${video.currentTime}, isVfcStalled: ${isVfcStalled}, stallThreshold: ${stallThreshold}, totalFrames: ${totalFrames}`, ) @@ -83,7 +83,7 @@ export function useFramePlayer( // Only update playhead via currentTime (RAF) if rVFC has stalled or isn't supported if (!videoWithCallback.requestVideoFrameCallback || isVfcStalled) { - const frame = Math.floor(video.currentTime * frameRate + 0.001) + const frame = Math.floor(video.currentTime * frameRate + 0.45) const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) setCurrentFrame(clamped) } @@ -98,7 +98,7 @@ export function useFramePlayer( rVfcId = null lastVfcTime = Date.now() // Reset stall timer - const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.001) + const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.45) const compositorClamped = Math.max(0, Math.min(compositorFrame, totalFrames - 1)) setCurrentFrame(compositorClamped) }, @@ -128,9 +128,13 @@ export function useFramePlayer( } // Synchronize frame on pause - const frame = Math.floor(video.currentTime * frameRate + 0.001) + const frame = Math.floor(video.currentTime * frameRate + 0.45) const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) setCurrentFrame(clamped) + + // Snap the playhead to the center of the paused frame to align browser compositor + const safeCenterTime = calculateFrameCenterTime(clamped, frameRate) + video.currentTime = safeCenterTime } video.addEventListener('play', handlePlay) @@ -205,8 +209,8 @@ export function useFramePlayer( video.pause() } - // Seek complete: update frame immediately using Math.floor (accounts for half-frame offset) - const actualFrame = Math.floor(video.currentTime * frameRate) + // Seek complete: update frame immediately using Math.floor + const actualFrame = Math.floor(video.currentTime * frameRate + 0.45) const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1)) setCurrentFrame(finalFrame) @@ -214,7 +218,7 @@ export function useFramePlayer( const videoWithCallback = video as unknown as HtmlVideoElementWithCallback if (videoWithCallback.requestVideoFrameCallback) { videoWithCallback.requestVideoFrameCallback((_now, metadata) => { - const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.001) + const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.45) const verifiedFrame = Math.max(0, Math.min(compositorFrame, totalFrames - 1)) setCurrentFrame(verifiedFrame) }) @@ -272,7 +276,7 @@ export function useFramePlayer( const handleExternalSeeked = () => { // Only sync if this seek was not triggered internally by seekToFrame if (!isSeekingRef.current) { - const actualFrame = Math.floor(video.currentTime * frameRate + 0.001) + const actualFrame = Math.floor(video.currentTime * frameRate + 0.45) const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1)) setCurrentFrame(finalFrame) diff --git a/packages/webui/components/viewers/utils.ts b/packages/webui/components/viewers/utils.ts index 35a85d4f..5dfe28e6 100644 --- a/packages/webui/components/viewers/utils.ts +++ b/packages/webui/components/viewers/utils.ts @@ -80,13 +80,13 @@ export const formatTimecode = ( export const formatTimestamp = (seconds: number, fps: number): string => { if (isNaN(seconds)) return '00:00:00:00' - const frameIndex = Math.floor(seconds * fps + 0.001) + const frameIndex = Math.floor(seconds * fps + 0.45) return formatTimecode(frameIndex, fps, 'timecode') } export const formatFrame = (seconds: number, fps: number): number => { if (isNaN(seconds) || !fps) return 0 - return Math.floor(seconds * fps + 0.001) + return Math.floor(seconds * fps + 0.45) } export const calculateFrameCenterTime = (frameIndex: number, frameRate: number): number => { diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 97092b2b..394222ab 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -672,7 +672,7 @@ const VideoPlayer: React.FC = ({ if (startTime !== undefined && startTime !== null && startTime > 0) { if (startTime !== lastProcessedStartTimeRef.current) { lastProcessedStartTimeRef.current = startTime - const targetFrame = Math.floor(startTime * frameRate + 0.001) + const targetFrame = Math.floor(startTime * frameRate + 0.45) seekToFrame(targetFrame) } } diff --git a/packages/webui/docs/video_player_design.md b/packages/webui/docs/video_player_design.md index bc409ae2..e2514ce0 100644 --- a/packages/webui/docs/video_player_design.md +++ b/packages/webui/docs/video_player_design.md @@ -51,14 +51,13 @@ $$\text{Time}_{\text{boundary}} = \frac{N}{\text{frameRate}}$$ --- -### B. Time-to-Frame Conversion (Floor with Epsilon) -When converting a raw player timestamp ($t$) back to an integer frame index, we use a **Floor with Epsilon** formula to absorb sub-millisecond clock drift and presentation lag without triggering premature frame jumps: +### B. Time-to-Frame Conversion (Floor with 0.45 Offset) +When converting a raw player timestamp ($t$) back to an integer frame index, we use a **Floor with 0.45 Offset** formula to absorb sub-millisecond clock drift, compositor presentation offsets, and V-Sync boundaries: -$$\text{Frame} = \lfloor(t \cdot \text{frameRate}) + \epsilon\rfloor$$ +$$\text{Frame} = \lfloor(t \cdot \text{frameRate}) + 0.45\rfloor$$ -*Where $\epsilon = 0.001$ frames.* -* **Start Boundary Guard:** If the browser reports time slightly early due to float precision (e.g. $119.9999$ frames instead of $120.0$), the $+ 0.001$ bumps it to $120.0009$, flooring correctly to Frame `120`. -* **Late Pause Guard:** If the playhead stops very late in the frame (e.g. $120.96$ frames), adding `0.001` yields $120.961$, which still floors correctly to **Frame `120`**, matching what is actually displayed on the screen. +* **Compositor Lag Guard:** Since the browser compositor typically presents a frame slightly before the playhead crosses the exact mathematical start time (due to V-Sync ticks and decoding latency), the browser transitions visually around the half-frame mark. An offset of `0.45` shifts the transition boundary to `0.55` frames, matching user perception. +* **Seek Buffer Guard:** When we seek to the safe center of a frame ($N + 0.5$ frames), using a `0.45` offset yields $N + 0.95$, which floors back to the correct frame index $N$ even if the browser has minor floating-point seek target deviations. --- @@ -121,8 +120,10 @@ When playing, the playhead loop coordinates two mechanisms in parallel to preven 2. The `pause` event listener triggers `handlePause()`: * Cancels active VFC (`cancelVideoFrameCallback`) and RAF (`cancelAnimationFrame`) loops. * Performs a final playhead synchronization: - $$\text{clampedFrame} = \max\left(0, \min\left(\lfloor(video.currentTime \cdot frameRate) + 0.001\rfloor, \text{totalFrames} - 1\right)\right)$$ + $$\text{clampedFrame} = \max\left(0, \min\left(\lfloor(video.currentTime \cdot frameRate) + 0.45\rfloor, \text{totalFrames} - 1\right)\right)$$ * Calls `setCurrentFrame(clampedFrame)` to lock the UI to the correct frame. + * **Snaps the browser playhead** to the calculated frame's center time to force the browser compositor to align: + $$\text{currentTime} = \text{calculateFrameCenterTime}(\text{clampedFrame}, \text{frameRate})$$ --- @@ -164,9 +165,9 @@ When playing, the playhead loop coordinates two mechanisms in parallel to preven ``` 3. The browser seeks the media element. Once finished, it fires the native `seeked` event. 4. The `handleExternalSeeked` listener in `useFramePlayer` triggers because `isSeekingRef.current` is `false`: - * Maps `video.currentTime` back to the frame index: - $$\text{finalFrame} = \lfloor(video.currentTime \cdot frameRate) + 0.001\rfloor = \lfloor(5.005005 \cdot 23.976) + 0.001\rfloor = 120$$ - * Computes the safe center time: `safeCenterTime = calculateFrameCenterTime(120, 23.976) = 5.025859s`. + * Maps `video.currentTime` back to the frame index: + $$\text{finalFrame} = \lfloor(video.currentTime \cdot frameRate) + 0.45\rfloor = \lfloor(5.005005 \cdot 23.976) + 0.45\rfloor = 120$$ + * Computes the safe center time: `safeCenterTime = calculateFrameCenterTime(120, 23.976) = 5.025859s`. * Detects if the current time is offset from the center by more than a quarter-frame: $$\text{Math.abs}(5.005005 - 5.025859) = 0.020854\text{s} > \frac{0.041708}{4}\text{s}$$ * Nudges the browser's playhead: `video.currentTime = safeCenterTime` (`5.025859`s). This forces the browser to render Frame 120 cleanly.