# 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:
### 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:
* **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.
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**:
### D. Effective Frame Count Derivation (Container vs. Video Stream)
The player's `totalFrames` governs the frame readout (`N / M fr`), the seekbar extent, frame-stepping bounds, and the playback clamp. It is **not** always the same as the container's frame count, because a container's duration can exceed its video stream — most commonly when the **audio track is slightly longer than the video track** (AAC padding and the fixed 1024-samples-per-frame granularity mean audio rarely ends on the exact video timestamp), or from container overhead.
Deriving the count naively from the container duration ($\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil$) invents **phantom trailing frames** the video stream does not contain. Whether those extra frames should be counted depends on whether the playhead can actually *reach* them during playback, which is governed by the same **stall threshold** used by the playback loop (§3):
Let $\text{tail} = \text{containerDuration} - \frac{\text{dbTotalFrames}}{\text{frameRate}}$ (where `dbTotalFrames` is the video stream's `nb_frames`). Then:
* **Small tail (tail ≤ threshold):** The RAF fallback never activates (§3), so the playhead physically cannot enter the tail. Counting those frames would strand the readout short of its own maximum (e.g. a 268-frame video in a 270-frame container would show `267 / 269` and stop at 267). We therefore use the accurate video-stream count → `267 / 267`. The trailing audio still plays out to the container end on the native element; it is simply not represented as extra scrubbable frames.
* **Large tail (tail > threshold):** The playhead *does* traverse the audio-only region (the RAF fallback drives it from `video.currentTime`, §3), so the container-derived count is correct and the readout reaches its maximum at the natural end (e.g. a 150-frame video with a 6.5s audio tail shows `194 / 194`).
This rule is implemented by `resolveTotalFrames` in `viewers/utils.ts`, which shares `stallThresholdMs` with `useFramePlayer` so the frame-count boundary and the runtime playhead-reachability boundary can never drift apart.
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.**Compositor-First Gating & Stall Detection:**`video.currentTime` is the playback (audio) clock, and on some engines (notably Safari/WebKit) it runs *ahead* of the frame actually presented on screen right after playback starts. Trusting it before the compositor catches up would race the playhead forward and then snap it backward when the first rVFC (`mediaTime`) arrives. To prevent this, each `play` resets the per-session sync state, and the playhead is driven from `video.currentTime`**only** when `requestVideoFrameCallback` is unsupported, **or** rVFC has delivered a frame this session and has since stalled beyond the **dynamic stall threshold**:
the `requestAnimationFrame` loop may drive playhead updates from `video.currentTime`. As a safety net, this fallback also engages if rVFC never fires within an initial grace window (~1000 ms) after play, so the playhead can never freeze permanently. Until the first compositor frame is presented, the playhead follows `mediaTime` (rVFC) exclusively, so it never leads the on-screen image.
4. Until the first rVFC frame is presented, the playhead is driven **only** by `mediaTime`; the `requestAnimationFrame` path does not advance it from `video.currentTime` (see §3), avoiding a forward race on engines whose playback clock leads presentation at startup.
5. Thereafter the UI displays continuous updates aligned with compositor frames.
* Chooses the synchronization time. When rVFC is **fresh** (it delivered a frame within the stall threshold), the last presented compositor time `lastMediaTime` is used — this is the frame actually on screen. Otherwise (rVFC stale or unsupported, e.g. an audio-only tail after the video track ends) it falls back to `video.currentTime`:
> **Frame-accurate tradeoff:** because pause locks to the *presented* frame (which on Safari lags the audio clock), snapping `currentTime` back to that frame's center means the small audio segment between the presented frame and the audio position is replayed on resume. This is intentional and matches other frame-accurate tools (e.g. frame.io): landing on the exact displayed frame takes priority over seamless audio. The effect is proportional to the engine's audio/video presentation offset — negligible on Chrome, ~100–300 ms on Safari.
* 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.
> **Note:** `totalFrames` is always the physical **video-stream** frame count (`nb_frames`), while `duration` is the **container** duration (which can be longer, e.g. when the audio track outlasts the video). The frontend reconciles the two into an effective frame count via the rule in §2.D — it does not blindly trust either value alone.
* **Precision:** The `second` column uses `Decimal(10, 4)` to store sub-millisecond timestamps accurately without rounding or floating-point truncation.