refactor(webui): modularize file viewer components into registry-driven architecture

This commit is contained in:
yiling
2026-07-05 10:51:42 +08:00
parent 229070fe19
commit 4cc35d3453
28 changed files with 1161 additions and 1043 deletions
@@ -0,0 +1,470 @@
import { client } from '@/ui/api/client'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { cn } from '@/ui/lib/utils'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { Annotation } from '@/ui/types'
import type { AssetInfo } from '@shumai/dtos'
import { Play } from 'lucide-react'
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import videojs from 'video.js'
import type Player from 'video.js/dist/types/player'
import { useFramePlayer } from './use-frame-player'
import { resolveTotalFrames } from './utils'
import { clampFrame as clampFrameUtil } from '../../compare/compare-utils'
import type { ComparePaneHandle, DisplayTranscode, PaneReportedState } from '../../compare/types'
interface CompareVideoPaneProps {
file: AssetInfo
shareId?: string
isActive: boolean
/** Whether this pane's audio should be muted (only the active side plays audio). */
muted?: boolean
volume?: number
annotations: Annotation[]
onStateChange: (state: PaneReportedState) => void
onActivate: () => void
onRequestTogglePlay?: () => void
/** Called with the current playhead time in seconds (used only for the active pane). */
onTimeUpdate?: (second: number) => void
onPlay?: () => void
}
function computeResolutions(file: AssetInfo): DisplayTranscode[] {
const original: DisplayTranscode | null = file.media?.original?.downloadUrl
? {
id: 'original',
url: file.media.original.downloadUrl,
key: file.media.original.key ?? '',
width: file.media?.metadata?.originalWidth ?? 0,
height: file.media?.metadata?.originalHeight ?? 0,
size: 0,
isRaw: true,
resolution: 'Original',
}
: null
const transcodes: DisplayTranscode[] = (file.media?.videoTranscodes ?? []).map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return { ...t, resolution: t.isRaw ? 'Original' : resolution }
})
const hasOriginalTranscode = transcodes.some((t) => t.isRaw)
if (!hasOriginalTranscode && original) {
return [...transcodes, original]
}
return transcodes
}
export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPaneProps>(
function CompareVideoPane(
{
file,
shareId,
isActive,
muted = true,
volume = 1,
annotations,
onStateChange,
onActivate,
onRequestTogglePlay,
onTimeUpdate,
onPlay,
},
ref,
) {
const playerRef = useRef<Player | null>(null)
const videoContainerRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const videoRef = useRef<HTMLVideoElement | null>(null)
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
} = useAnnotationStore()
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const [zoom, setZoom] = useState(1)
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
const [pan, setPan] = useState<{ x: number; y: number } | null>(null)
const [isPlaying, setIsPlaying] = useState(false)
const [isLooping, setIsLooping] = useState(false)
const [playbackRate, setPlaybackRate] = useState(1)
const [buffered, setBuffered] = useState(0)
const [playerVolume, setPlayerVolume] = useState(volume)
const [playerMuted, setPlayerMuted] = useState(muted)
const [isPlayerReady, setIsPlayerReady] = useState(false)
const metadata = file.media?.metadata
const frameRate = metadata?.frameRate || 30
const dbTotalFrames = metadata?.totalFrames || 0
const containerDuration = metadata?.duration || 0
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const resolutions = computeResolutions(file)
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const initialRes = previewResolutions[0] ?? resolutions[0]
const [currentResolution, setCurrentResolution] = useState(initialRes?.resolution ?? 'Original')
const currentSrcRef = useRef(initialRes?.url)
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
const zoomRef = useRef(zoom)
zoomRef.current = zoom
const currentFrameRef = useRef(currentFrame)
currentFrameRef.current = currentFrame
// Resize observer
useEffect(() => {
if (!containerRef.current) return
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({ width: entry.contentRect.width, height: entry.contentRect.height })
}
})
observer.observe(containerRef.current)
return () => observer.disconnect()
}, [])
const vidW = metadata?.originalWidth ?? 1920
const vidH = metadata?.originalHeight ?? 1080
// Auto-fit zoom
useEffect(() => {
if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) {
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
setZoom(scale)
}
}, [containerSize.width, containerSize.height, vidW, vidH, hasManuallyZoomed])
// Keep the resolution selection and source url in sync when the displayed
// asset changes, so the player (re)initializes with the correct source even
// if the parent renders this pane without a per-asset `key`. Runs before the
// video.js init effect below (declaration order) so the ref is fresh.
useEffect(() => {
setCurrentResolution(initialRes?.resolution ?? 'Original')
currentSrcRef.current = initialRes?.url
}, [file.id])
// Initialize video.js
useEffect(() => {
if (!videoContainerRef.current) return
const videoElement = document.createElement('video-js')
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
videoElement.style.opacity = '0'
videoElement.style.pointerEvents = 'none'
videoContainerRef.current.appendChild(videoElement)
const player = (playerRef.current = videojs(videoElement, {
controls: false,
autoplay: false,
preload: 'auto',
playsinline: true,
sources: [{ src: currentSrcRef.current ?? '', type: 'video/mp4' }],
}))
const htmlVid = videoElement.querySelector('video')
if (htmlVid) {
setVideoHtmlEl(htmlVid)
videoRef.current = htmlVid
} else {
player.ready(() => {
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
if (techEl) {
setVideoHtmlEl(techEl)
videoRef.current = techEl
}
})
}
player.on('play', () => {
setIsPlaying(true)
onPlay?.()
})
player.on('pause', () => setIsPlaying(false))
player.on('ended', () => setIsPlaying(false))
player.on('loadedmetadata', () => setIsPlayerReady(true))
player.on('loadstart', () => setIsPlayerReady(false))
player.on('timeupdate', () => {
const playerDuration = player.duration() || containerDuration || 0
const bufferedEnd = player.bufferedEnd()
if (playerDuration > 0) setBuffered((bufferedEnd / playerDuration) * 100)
})
player.on('volumechange', () => {
setPlayerVolume(player.volume() || 0)
setPlayerMuted(player.muted() || false)
})
player.on('ratechange', () => setPlaybackRate(player.playbackRate() || 1))
return () => {
if (player && !player.isDisposed()) {
player.dispose()
playerRef.current = null
videoRef.current = null
}
}
}, [file.id])
// Apply muted / volume (audio routing: only active side unmuted)
useEffect(() => {
const player = playerRef.current
if (!player || !isPlayerReady) return
player.muted(muted)
player.volume(volume)
}, [muted, volume, isPlayerReady])
// Report state upward
useEffect(() => {
const state: PaneReportedState = {
kind: 'video',
zoom,
video: {
frameRate,
totalFrames,
currentFrame,
isPlaying,
volume: playerVolume,
isMuted: playerMuted,
playbackRate,
isLooping,
currentResolution,
resolutions,
buffered,
},
}
onStateChange(state)
}, [
zoom,
frameRate,
totalFrames,
currentFrame,
isPlaying,
playerVolume,
playerMuted,
playbackRate,
isLooping,
currentResolution,
buffered,
])
// Propagate active playhead time
useEffect(() => {
if (isActive) onTimeUpdate?.(currentFrame / frameRate)
}, [currentFrame, frameRate, isActive, onTimeUpdate])
const applyZoom = useCallback((factor: number) => {
const cur = zoomRef.current
const newZoom = cur * factor
if (newZoom < 0.01 || newZoom > 50) return
setZoom(newZoom)
setHasManuallyZoomed(true)
}, [])
const fit = useCallback(() => {
setHasManuallyZoomed(false)
setPan(null)
}, [])
const clampFrame = useCallback(
(frame: number) => clampFrameUtil(frame, totalFrames),
[totalFrames],
)
const handleDownload = useCallback(
async (key?: string) => {
const dlKey = key ?? file.media?.original?.key
if (!dlKey || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key: dlKey },
})
: await client.api.files['download-url'].$post({
json: { key: dlKey, assetId: file.id },
})
if (!res.ok) return
const { url } = await res.json()
const link = document.createElement('a')
link.href = url
link.download = ''
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// silently fail
}
},
[file.id, file.media?.original?.key, shareId],
)
const changeResolution = useCallback(
(resolution: string) => {
const player = playerRef.current
if (!player) return
const target = resolutions.find((r) => r.resolution === resolution)
if (!target) return
const wasPlaying = !player.paused()
const currentT = player.currentTime()
setCurrentResolution(resolution)
currentSrcRef.current = target.url
player.src({ type: 'video/mp4', src: target.url })
player.one('loadedmetadata', () => {
player.currentTime(currentT)
if (wasPlaying) {
const p = player.play()
if (p !== undefined) p.catch(() => {})
}
})
},
[resolutions],
)
useImperativeHandle(
ref,
(): ComparePaneHandle => ({
getKind: () => 'video',
play: () => {
const p = playerRef.current?.play()
if (p !== undefined) p.catch(() => {})
},
pause: () => playerRef.current?.pause(),
togglePlay: () => {
const player = playerRef.current
if (!player) return
if (player.paused() || player.ended()) {
const p = player.play()
if (p !== undefined) p.catch(() => {})
} else {
player.pause()
}
},
seekToFrame: (frame) => seekToFrame(clampFrame(frame)),
seekToSecond: (second) => {
const frame = Math.floor(second * frameRate + 0.45)
seekToFrame(clampFrame(frame))
},
stepFrame: (delta) => seekToFrame(clampFrame(currentFrameRef.current + delta)),
setMuted: (m) => playerRef.current?.muted(m),
setVolume: (v) => {
const player = playerRef.current
if (!player) return
player.volume(v)
if (v > 0 && player.muted()) player.muted(false)
else if (v === 0 && !player.muted()) player.muted(true)
},
setPlaybackRate: (rate) => playerRef.current?.playbackRate(rate),
toggleLoop: () => {
const player = playerRef.current
if (!player) return
const next = !player.loop()
player.loop(next)
setIsLooping(next)
},
changeResolution,
zoomBy: applyZoom,
fit,
panBy: (dx, dy) =>
setPan((p) => {
const scale = zoomRef.current
const base = p ?? {
x: (containerSize.width - vidW * scale) / 2,
y: (containerSize.height - vidH * scale) / 2,
}
return { x: base.x + dx, y: base.y + dy }
}),
download: (key?: string) => handleDownload(key),
}),
[
seekToFrame,
clampFrame,
frameRate,
applyZoom,
fit,
changeResolution,
handleDownload,
containerSize.width,
containerSize.height,
vidW,
vidH,
],
)
const displayAnnotations = [...annotations, ...(isActive ? draftAnnotations : [])]
const scale = zoom
const defaultPanX = (containerSize.width - vidW * scale) / 2
const defaultPanY = (containerSize.height - vidH * scale) / 2
const panX = pan?.x ?? defaultPanX
const panY = pan?.y ?? defaultPanY
const handleAreaClick = useCallback(() => {
if (useAnnotationStore.getState().isDrawing) return
// Clicking an inactive pane only activates it; playback is untouched.
if (!isActive) {
onActivate?.()
return
}
onRequestTogglePlay?.()
}, [isActive, onActivate, onRequestTogglePlay])
if (!file.media?.original?.downloadUrl || !metadata) {
return (
<div className="flex h-full w-full items-center justify-center bg-black">
<p className="text-muted-foreground">Media is not available.</p>
</div>
)
}
return (
<div
ref={containerRef}
className={cn(
'relative flex flex-1 cursor-pointer items-center justify-center overflow-hidden bg-black',
)}
onClick={handleAreaClick}
data-testid="compare-video-area"
>
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{videoHtmlEl && containerSize.width > 0 && (
<DrawingCanvas
width={containerSize.width}
height={containerSize.height}
mediaDimensions={{ width: vidW, height: vidH }}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={{ x: panX, y: panY }}
className="absolute inset-0"
onClick={handleAreaClick}
isDrawing={isActive && isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={isActive ? addAnnotation : undefined}
/>
)}
{!isPlaying && !isDrawing && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20">
<div className="flex h-16 w-16 items-center justify-center rounded-full border-2 border-white/30 bg-white/10 backdrop-blur-sm">
<Play className="ml-1 h-8 w-8 fill-white text-white" />
</div>
</div>
)}
</div>
)
},
)
@@ -0,0 +1,16 @@
import { FileTypeDefinition } from '../types'
import VideoViewer from './video-viewer'
import { CompareVideoPane } from './compare-video-pane'
export const videoTypeDefinition: FileTypeDefinition = {
id: 'video',
name: 'Video',
match: (file) => !!file.mediaType?.startsWith('video/'),
viewer: VideoViewer,
comparePane: CompareVideoPane,
commentsConfig: {
hasTimestamp: true,
hasAnnotations: true,
hasAiBots: true,
},
}
@@ -0,0 +1,334 @@
import { cn } from '@/ui/lib/utils'
import type { MediaMetadata } from '@shumai/dtos'
import React, { useCallback, useEffect, useRef, useState } from 'react'
const formatTime = (seconds: number): string => {
if (isNaN(seconds)) return '00:00'
const date = new Date(seconds * 1000)
const hh = date.getUTCHours()
const mm = date.getUTCMinutes()
const ss = date.getUTCSeconds().toString().padStart(2, '0')
if (hh) {
return `${hh}:${mm.toString().padStart(2, '0')}:${ss}`
}
return `${mm}:${ss}`
}
interface ProgressBarProps {
totalFrames: number
currentFrame: number
fps: number
previewUrl?: string
onSeek: (frame: number) => void
buffered?: number
metadata?: MediaMetadata
}
const ProgressBar: React.FC<ProgressBarProps> = ({
totalFrames,
currentFrame,
fps,
previewUrl,
onSeek,
buffered = 0,
metadata,
}) => {
const containerRef = useRef<HTMLDivElement>(null)
const previewVideoRef = useRef<HTMLVideoElement>(null)
const [hoverPosition, setHoverPosition] = useState<number | null>(null) // 0 to 1
const [isHovering, setIsHovering] = useState(false)
const [isDragging, setIsDragging] = useState(false)
const onSeekRef = useRef(onSeek)
useEffect(() => {
onSeekRef.current = onSeek
}, [onSeek])
// Load the preview video in background
useEffect(() => {
if (previewVideoRef.current && previewUrl) {
previewVideoRef.current.load()
}
}, [previewUrl])
const getPercentageFromEvent = useCallback((clientX: number) => {
if (!containerRef.current) return 0
const rect = containerRef.current.getBoundingClientRect()
const x = Math.max(0, Math.min(clientX - rect.left, rect.width))
return x / rect.width
}, [])
const handleMouseMove = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (isDragging) return
if (!containerRef.current) return
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)
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
}
}
},
[totalFrames, fps, isDragging],
)
const handleMouseLeave = () => {
if (!isDragging) {
setIsHovering(false)
setHoverPosition(null)
}
}
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
if (e.button !== 0) return
e.preventDefault()
setIsDragging(true)
const percentage = getPercentageFromEvent(e.clientX)
setHoverPosition(percentage)
setIsHovering(true)
onSeekRef.current(percentage * totalFrames)
}
const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
setIsDragging(true)
const percentage = getPercentageFromEvent(e.touches[0].clientX)
setHoverPosition(percentage)
setIsHovering(true)
onSeekRef.current(percentage * totalFrames)
}
useEffect(() => {
if (!isDragging) return
const handleWindowMouseMove = (e: MouseEvent) => {
const percentage = getPercentageFromEvent(e.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 handleWindowMouseUp = (e: MouseEvent) => {
setIsDragging(false)
let stillHovering = false
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)
}
const percentage = getPercentageFromEvent(e.clientX)
onSeekRef.current(percentage * totalFrames)
}
const handleWindowTouchMove = (e: TouchEvent) => {
if (e.touches.length === 0) 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)
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)
setHoverPosition(null)
}
if (clientX !== null) {
const percentage = getPercentageFromEvent(clientX)
onSeekRef.current(percentage * totalFrames)
}
}
window.addEventListener('mousemove', handleWindowMouseMove)
window.addEventListener('mouseup', handleWindowMouseUp)
window.addEventListener('touchmove', handleWindowTouchMove, { passive: true })
window.addEventListener('touchend', handleWindowTouchEnd)
return () => {
window.removeEventListener('mousemove', handleWindowMouseMove)
window.removeEventListener('mouseup', handleWindowMouseUp)
window.removeEventListener('touchmove', handleWindowTouchMove)
window.removeEventListener('touchend', handleWindowTouchEnd)
}
}, [isDragging, totalFrames, fps, getPercentageFromEvent])
const progressPercent =
isDragging && hoverPosition !== null
? hoverPosition * 100
: totalFrames > 0
? (currentFrame / totalFrames) * 100
: 0
const hoverPercent = hoverPosition !== null ? hoverPosition * 100 : 0
// Calculate preview tooltip position
const getTooltipStyle = () => {
if (hoverPosition === null) return {}
return {
left: `${hoverPercent}%`,
transform: `translateX(-${hoverPercent}%)`,
}
}
// Dynamic Size Calculation
const MAX_PREVIEW_SIZE = 180
let previewDimensions: React.CSSProperties = {
width: `${MAX_PREVIEW_SIZE}px`,
height: 'auto',
}
if (metadata && metadata.originalWidth && metadata.originalHeight) {
const { originalWidth, originalHeight } = metadata
if (originalWidth >= originalHeight) {
// Landscape or Square: Constrain width
const height = (MAX_PREVIEW_SIZE * originalHeight) / originalWidth
previewDimensions = {
width: `${MAX_PREVIEW_SIZE}px`,
height: `${height}px`,
}
} else {
// Portrait: Constrain height
const width = (MAX_PREVIEW_SIZE * originalWidth) / originalHeight
previewDimensions = {
width: `${width}px`,
height: `${MAX_PREVIEW_SIZE}px`,
}
}
}
return (
<div
ref={containerRef}
className="group relative h-1.5 w-full cursor-pointer touch-none rounded-full bg-muted transition-colors duration-200"
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
data-testid="seekbar"
>
{/* Hidden Preview Video Element */}
<video
ref={previewVideoRef}
src={previewUrl}
className="hidden"
preload="auto"
muted
playsInline
/>
{/* Hover Preview Tooltip */}
{isHovering && totalFrames > 0 && (
<div
className="pointer-events-none absolute bottom-full z-50 mb-3 flex w-max flex-col"
style={getTooltipStyle()}
>
<div className="relative overflow-hidden rounded-lg border-2 border-border bg-popover shadow-2xl">
<video
src={previewUrl}
className="bg-black object-cover"
style={previewDimensions}
muted
ref={(el) => {
if (el && previewVideoRef.current) {
el.currentTime = previewVideoRef.current.currentTime
}
}}
/>
<div className="absolute bottom-0 w-full bg-popover/80 py-0.5 text-center text-xs font-medium text-popover-foreground">
{formatTime((hoverPosition! * totalFrames) / fps)}
</div>
</div>
</div>
)}
{/* Buffered Bar */}
<div
className="absolute top-0 left-0 h-full rounded-full bg-muted-foreground/30 transition-all duration-200"
style={{ width: `${buffered}%` }}
/>
{/* Hover Highlight Bar */}
{isHovering && (
<div
className="absolute top-0 left-0 h-full rounded-full bg-primary/30"
style={{ width: `${hoverPercent}%` }}
/>
)}
{/* Play Progress Bar */}
<div
className="relative absolute top-0 left-0 h-full rounded-full bg-primary"
style={{ width: `${progressPercent}%` }}
data-testid="seekbar-fill"
>
{/* Thumb (Playhead) - visible on group hover or active */}
<div
className={cn(
'absolute top-1/2 right-0 h-3.5 w-3.5 -translate-y-1/2 translate-x-1/2 rounded-full border border-border bg-primary shadow-md transition-transform duration-100',
isHovering || isDragging ? 'scale-100' : 'scale-0 group-hover:scale-100',
)}
/>
</div>
</div>
)
}
export default ProgressBar
@@ -0,0 +1,229 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, renderHook } from '@testing-library/react'
import { useFramePlayer } from './use-frame-player'
/**
* Deterministic reproduction of the Safari playhead-rewind bug.
*
* On Safari/WebKit, `video.currentTime` (the playback/audio clock) runs AHEAD of
* the frame actually presented on screen right after playback starts, and the
* first `requestVideoFrameCallback` (mediaTime) arrives only after a delay. The
* old logic drove the playhead from `currentTime` immediately on play, racing it
* forward, then snapped it backward when the first rVFC reported the true (lower)
* presented frame.
*
* The headless WebKit engine does not exhibit that clock skew, so this can only
* be reproduced deterministically at the logic layer: we mock a video element
* whose `currentTime` leads while a fake `requestVideoFrameCallback` delivers a
* lagging `mediaTime`, drive RAF/clock manually, and assert the playhead never
* moves backward.
*/
const FPS = 30
const TOTAL = 150
// --- Controllable environment -------------------------------------------------
interface RafEntry {
id: number
cb: FrameRequestCallback
}
let clock = 0
let rafQueue: RafEntry[] = []
let rafSeq = 0
/** Run exactly the RAF callbacks queued at flush time (one simulated frame). */
const flushRaf = () => {
const queued = rafQueue
rafQueue = []
for (const { cb } of queued) cb(clock)
}
/** Minimal HTMLVideoElement stand-in with a manually-fired rVFC. */
class FakeVideo extends EventTarget {
currentTime = 0
paused = true
ended = false
private vfcCallbacks: Array<(now: number, meta: { mediaTime: number }) => void> = []
requestVideoFrameCallback(cb: (now: number, meta: { mediaTime: number }) => void): number {
this.vfcCallbacks.push(cb)
return this.vfcCallbacks.length
}
cancelVideoFrameCallback(): void {
this.vfcCallbacks = []
}
pause(): void {
this.paused = true
this.dispatchEvent(new Event('pause'))
}
play(): void {
this.paused = false
this.dispatchEvent(new Event('play'))
}
/** Simulate the compositor presenting a frame at the given mediaTime. */
fireVfc(mediaTime: number): void {
const callbacks = this.vfcCallbacks
this.vfcCallbacks = []
for (const cb of callbacks) cb(0, { mediaTime })
}
}
function makeRef(video: FakeVideo): { current: HTMLVideoElement | null } {
return { current: video as unknown as HTMLVideoElement }
}
let originalRaf: typeof globalThis.requestAnimationFrame
let originalCaf: typeof globalThis.cancelAnimationFrame
beforeEach(() => {
clock = 0
rafQueue = []
rafSeq = 0
vi.spyOn(Date, 'now').mockImplementation(() => clock)
originalRaf = globalThis.requestAnimationFrame
originalCaf = globalThis.cancelAnimationFrame
globalThis.requestAnimationFrame = ((cb: FrameRequestCallback): number => {
rafSeq += 1
rafQueue.push({ id: rafSeq, cb })
return rafSeq
}) as typeof globalThis.requestAnimationFrame
globalThis.cancelAnimationFrame = ((id: number): void => {
rafQueue = rafQueue.filter((entry) => entry.id !== id)
}) as typeof globalThis.cancelAnimationFrame
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
globalThis.requestAnimationFrame = originalRaf
globalThis.cancelAnimationFrame = originalCaf
})
// --- Tests --------------------------------------------------------------------
describe('useFramePlayer Safari playhead synchronization', () => {
it('does not rewind the playhead on play when currentTime leads the presented frame', () => {
const video = new FakeVideo()
const { result } = renderHook(() => useFramePlayer(makeRef(video), FPS, TOTAL))
const frames: number[] = []
const record = () => frames.push(result.current.currentFrame)
// Start playback via the play event (as a real click would).
act(() => {
video.paused = false
video.dispatchEvent(new Event('play'))
})
record()
// Safari: the playback clock races ahead (~frame 10) while NO rVFC frame has
// been presented yet. The playhead must NOT follow currentTime here.
const leadingCurrentTimes = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35]
for (const ct of leadingCurrentTimes) {
clock += 50
video.currentTime = ct
act(() => {
flushRaf()
})
record()
}
expect(Math.max(...frames)).toBe(0) // Fix 1: no forward race from currentTime
// First presented frame arrives, lagging currentTime (frame 1).
act(() => {
video.fireVfc(1 / FPS)
})
record()
// Subsequent presented frames advance normally.
for (let f = 2; f <= 8; f++) {
clock += 33
act(() => {
flushRaf()
})
act(() => {
video.fireVfc(f / FPS)
})
record()
}
// The playhead must be monotonic non-decreasing throughout (never rewinds).
for (let i = 1; i < frames.length; i++) {
expect(frames[i]).toBeGreaterThanOrEqual(frames[i - 1])
}
expect(result.current.currentFrame).toBe(8)
})
it('still falls back to currentTime once rVFC has delivered and then stalls', () => {
const video = new FakeVideo()
const { result } = renderHook(() => useFramePlayer(makeRef(video), FPS, TOTAL))
act(() => {
video.paused = false
video.dispatchEvent(new Event('play'))
})
// rVFC delivers a few frames -> the session has "seen" the compositor.
for (let f = 1; f <= 3; f++) {
clock += 33
video.currentTime = f / FPS
act(() => {
flushRaf()
})
act(() => {
video.fireVfc(f / FPS)
})
}
expect(result.current.currentFrame).toBe(3)
// Video track ends: rVFC stops, but audio (currentTime) keeps advancing past
// the stall threshold. The RAF fallback should take over from currentTime.
clock += 200
video.currentTime = 10 / FPS
act(() => {
flushRaf()
})
expect(result.current.currentFrame).toBe(10)
})
it('locks the paused frame to the presented mediaTime, not the leading currentTime', () => {
const video = new FakeVideo()
const { result } = renderHook(() => useFramePlayer(makeRef(video), FPS, TOTAL))
act(() => {
video.paused = false
video.dispatchEvent(new Event('play'))
})
// Presented up to frame 16 via rVFC.
for (let f = 1; f <= 16; f++) {
clock += 33
act(() => {
flushRaf()
})
act(() => {
video.fireVfc(f / FPS)
})
}
expect(result.current.currentFrame).toBe(16)
// Safari's currentTime has raced ahead to frame 20's center.
video.currentTime = 20 / FPS + 1 / (2 * FPS)
// Pause while rVFC is still fresh.
act(() => {
video.pause()
})
// Fix 2: the paused frame follows the presented frame (16), not currentTime (20).
expect(result.current.currentFrame).toBe(16)
})
})
@@ -0,0 +1,353 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { calculateFrameCenterTime, stallThresholdMs } from './utils'
export interface UseFramePlayerResult {
currentFrame: number
setCurrentFrame: React.Dispatch<React.SetStateAction<number>>
seekToFrame: (targetFrame: number) => Promise<void>
isSeeking: React.RefObject<boolean>
}
interface HtmlVideoElementWithCallback {
requestVideoFrameCallback?: (
callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void,
) => number
cancelVideoFrameCallback?: (id: number) => void
}
// If requestVideoFrameCallback is supported but has not delivered a frame within
// this window after playback starts, fall back to the currentTime/RAF driver so
// the playhead can never freeze permanently on an engine that stops emitting rVFC.
const INITIAL_VFC_GRACE_MS = 1000
export function useFramePlayer(
videoRef: React.RefObject<HTMLVideoElement | null>,
frameRate: number,
totalFrames: number,
): UseFramePlayerResult {
const [currentFrame, setCurrentFrame] = useState<number>(0)
const isSeekingRef = useRef<boolean>(false)
const isPlayingRef = useRef<boolean>(false)
const pendingSeekFrameRef = useRef<number | null>(null)
const currentFrameRef = useRef<number>(currentFrame)
currentFrameRef.current = currentFrame
// Track playing state of the HTML video element
useEffect(() => {
const video = videoRef.current
if (!video) return
const handlePlay = () => {
isPlayingRef.current = true
}
const handlePause = () => {
isPlayingRef.current = false
}
video.addEventListener('play', handlePlay)
video.addEventListener('pause', handlePause)
// Initial check
isPlayingRef.current = !video.paused
return () => {
video.removeEventListener('play', handlePlay)
video.removeEventListener('pause', handlePause)
}
}, [videoRef.current])
// Continuous frame updating loop during active playback
useEffect(() => {
const video = videoRef.current
if (!video) return
let rVfcId: number | null = null
let rafId: number | null = null
let active = true
// Per-playback-session synchronization state.
// `lastVfcTime` / `hasDeliveredVfc` gate when it is safe to trust
// `video.currentTime` (see the fallback condition below). `lastMediaTime` is
// the most recent compositor-presented time, used to lock the playhead on
// pause to the frame the user is actually looking at.
let lastVfcTime = Date.now()
let hasDeliveredVfc = false
let lastMediaTime = -1
// Reset session state whenever playback (re)starts, so each play waits for a
// fresh compositor frame before trusting the playback clock.
const beginSession = () => {
lastVfcTime = Date.now()
hasDeliveredVfc = false
lastMediaTime = -1
}
const updateFrameLoop = () => {
if (!active) return
if (video.paused || video.ended) {
return
}
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
const rVfcSupported = !!videoWithCallback.requestVideoFrameCallback
// Calculate dynamic stall threshold (minimum 100ms, or 3 frames of duration)
const stallThreshold = stallThresholdMs(frameRate)
const sinceLastVfc = Date.now() - lastVfcTime
// Decide whether the RAF path may drive the playhead from `video.currentTime`.
//
// `video.currentTime` is the playback (audio) clock. On some engines
// (notably Safari/WebKit) it runs AHEAD of the frame actually presented on
// screen right after playback starts, so trusting it before the compositor
// catches up makes the playhead race forward and then snap backward when the
// first requestVideoFrameCallback (mediaTime) arrives.
//
// We therefore only use the currentTime fallback when:
// - rVFC is unsupported (it is the only driver available), or
// - rVFC has delivered at least one frame this session AND has since
// stalled (e.g. the video track ended while audio keeps playing), or
// - rVFC never delivered within the initial grace window (safety net so
// the playhead cannot freeze forever).
const rVfcStalledAfterDelivery = hasDeliveredVfc && sinceLastVfc > stallThreshold
const rVfcNeverDelivered = !hasDeliveredVfc && sinceLastVfc > INITIAL_VFC_GRACE_MS
const useCurrentTimeFallback =
!rVfcSupported || rVfcStalledAfterDelivery || rVfcNeverDelivered
if (useCurrentTimeFallback) {
const frame = Math.floor(video.currentTime * frameRate + 0.45)
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 compositor-accurate synchronization
if (videoWithCallback.requestVideoFrameCallback && rVfcId === null) {
rVfcId = videoWithCallback.requestVideoFrameCallback(
(_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => {
rVfcId = null
lastVfcTime = Date.now() // Reset stall timer
hasDeliveredVfc = true
lastMediaTime = metadata.mediaTime
const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.45)
const compositorClamped = Math.max(0, Math.min(compositorFrame, totalFrames - 1))
setCurrentFrame(compositorClamped)
},
)
}
}
const handlePlay = () => {
beginSession()
updateFrameLoop()
}
const handlePause = () => {
if (rVfcId !== null) {
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
if (videoWithCallback.cancelVideoFrameCallback) {
try {
videoWithCallback.cancelVideoFrameCallback(rVfcId)
} catch {
// Ignore error during cancellation
}
}
rVfcId = null
}
if (rafId !== null) {
cancelAnimationFrame(rafId)
rafId = null
}
// Synchronize the frame on pause. Prefer the last compositor-presented time
// (mediaTime) when it is still fresh, because on Safari `video.currentTime`
// can lead the on-screen frame — using it would snap the playhead forward
// past the frame the user actually paused on. Fall back to currentTime when
// rVFC is stale/unsupported (e.g. the video track ended while audio plays).
const stallThreshold = stallThresholdMs(frameRate)
const vfcFresh =
hasDeliveredVfc && lastMediaTime >= 0 && Date.now() - lastVfcTime <= stallThreshold
const syncTime = vfcFresh ? lastMediaTime : video.currentTime
const frame = Math.floor(syncTime * 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
// Skip snapping if the video has ended to preserve the native ended state and allow native replay
if (!video.ended) {
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
video.currentTime = safeCenterTime
}
}
video.addEventListener('play', handlePlay)
video.addEventListener('pause', handlePause)
// If it's already playing when this effect runs
if (!video.paused) {
beginSession()
updateFrameLoop()
}
return () => {
active = false
video.removeEventListener('play', handlePlay)
video.removeEventListener('pause', handlePause)
if (rVfcId !== null) {
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
if (videoWithCallback.cancelVideoFrameCallback) {
try {
videoWithCallback.cancelVideoFrameCallback(rVfcId)
} catch {
// Ignore error during cancellation
}
}
}
if (rafId !== null) {
cancelAnimationFrame(rafId)
}
}
}, [videoRef.current, frameRate, totalFrames])
const seekToFrame = useCallback(
async (targetFrame: number) => {
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 (isSeekingRef.current) {
pendingSeekFrameRef.current = clampedFrame
setCurrentFrame(clampedFrame)
return
}
isSeekingRef.current = true
setCurrentFrame(clampedFrame) // Optimistic update for active seek
const performSeek = async (frameToSeek: number) => {
const safeTargetTime = calculateFrameCenterTime(frameToSeek, frameRate)
const wasPlaying = !video.paused
video.currentTime = safeTargetTime
// 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)
video.removeEventListener('seeked', onSeeked)
resolve()
}
video.addEventListener('seeked', onSeeked)
timeoutId = setTimeout(() => {
video.removeEventListener('seeked', onSeeked)
resolve()
}, 500)
})
// Pause only if we started paused and the user hasn't pressed play in the meantime
if (!wasPlaying && !isPlayingRef.current) {
video.pause()
}
// 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)
// Verify with requestVideoFrameCallback in the background (non-blocking)
const videoWithCallback = video as unknown as HtmlVideoElementWithCallback
if (videoWithCallback.requestVideoFrameCallback) {
videoWithCallback.requestVideoFrameCallback((_now, metadata) => {
const compositorFrame = Math.floor(metadata.mediaTime * frameRate + 0.45)
const verifiedFrame = Math.max(0, Math.min(compositorFrame, totalFrames - 1))
setCurrentFrame(verifiedFrame)
})
}
// Process next seek in the queue if any came in during the seek
if (pendingSeekFrameRef.current !== null) {
const nextFrame = pendingSeekFrameRef.current
pendingSeekFrameRef.current = null
await performSeek(nextFrame)
} else {
isSeekingRef.current = false
}
}
await performSeek(clampedFrame)
},
[videoRef, frameRate, totalFrames],
)
// Keyboard Shortcuts Keydown Listener
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const target = e.target as HTMLElement
if (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target.isContentEditable
) {
return
}
if (e.key === 'ArrowRight') {
e.preventDefault()
const delta = e.shiftKey ? 10 : 1
seekToFrame(currentFrameRef.current + delta)
} else if (e.key === 'ArrowLeft') {
e.preventDefault()
const delta = e.shiftKey ? 10 : 1
seekToFrame(currentFrameRef.current - delta)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => {
window.removeEventListener('keydown', handleKeyDown)
}
}, [seekToFrame])
// Listen to external seeks (like comment clicks or VideoJS timeline clicks)
useEffect(() => {
const video = videoRef.current
if (!video) return
const handleExternalSeeked = () => {
// Only sync if this seek was not triggered internally by seekToFrame
if (!isSeekingRef.current) {
const actualFrame = Math.floor(video.currentTime * frameRate + 0.45)
const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1))
setCurrentFrame(finalFrame)
// Nudge to safe frame center to guarantee correct browser decoding
const safeCenterTime = calculateFrameCenterTime(finalFrame, frameRate)
const frameDuration = 1 / frameRate
if (Math.abs(video.currentTime - safeCenterTime) > frameDuration / 4) {
video.currentTime = safeCenterTime
}
}
}
video.addEventListener('seeked', handleExternalSeeked)
return () => {
video.removeEventListener('seeked', handleExternalSeeked)
}
}, [videoRef.current, frameRate, totalFrames])
return {
currentFrame,
setCurrentFrame,
seekToFrame,
isSeeking: isSeekingRef,
}
}
@@ -0,0 +1,167 @@
import { describe, it, expect } from 'vitest'
import {
formatTimecode,
calculateFrameCenterTime,
resolveTotalFrames,
stallThresholdMs,
} from './utils'
describe('formatTimecode tests', () => {
describe('non-drop-frame calculations', () => {
it('formats non-drop-frame correctly at 25 fps', () => {
// 2999 frames at 25 fps => 00:01:59:24
expect(formatTimecode(2999, 25, 'timecode')).toBe('00:01:59:24')
// 3000 frames at 25 fps => 00:02:00:00
expect(formatTimecode(3000, 25, 'timecode')).toBe('00:02:00:00')
// 15000 frames at 25 fps => 00:10:00:00
expect(formatTimecode(15000, 25, 'timecode')).toBe('00:10:00:00')
// 900000 frames at 25 fps => 10:00:00:00
expect(formatTimecode(900000, 25, 'timecode')).toBe('10:00:00:00')
})
})
describe('drop-frame calculations', () => {
it('formats drop-frame correctly at 29.97 fps', () => {
// 3597 frames at 29.97 fps => 00:01:59;29
expect(formatTimecode(3597, 29.97, 'timecode')).toBe('00:01:59;29')
// 17982 frames at 29.97 fps => 00:10:00;00
expect(formatTimecode(17982, 29.97, 'timecode')).toBe('00:10:00;00')
// 1078920 frames at 29.97 fps => 10:00:00;00
expect(formatTimecode(1078920, 29.97, 'timecode')).toBe('10:00:00;00')
})
it('formats drop-frame correctly at 59.94 fps', () => {
// 3597 * 2 + 1 = 7195 frames at 59.94 fps => 00:01:59;59
expect(formatTimecode(7195, 59.94, 'timecode')).toBe('00:01:59;59')
// 17982 * 2 = 35964 frames at 59.94 fps => 00:10:00;00
expect(formatTimecode(35964, 59.94, 'timecode')).toBe('00:10:00;00')
// 1078920 * 2 = 2157840 frames at 59.94 fps => 10:00:00;00
expect(formatTimecode(2157840, 59.94, 'timecode')).toBe('10:00:00;00')
})
})
describe('starting timecode offsets', () => {
it('offsets timecode correctly based on startTimecode string', () => {
// 0 frames at 29.97 fps with start '01:00:00:00' => 01:00:00:00
expect(formatTimecode(0, 29.97, 'timecode', '01:00:00:00')).toBe('01:00:00:00')
// 0 frames at 29.97 fps with start '01:00:00;00' => 01:00:00;00
expect(formatTimecode(0, 29.97, 'timecode', '01:00:00;00')).toBe('01:00:00;00')
// 30 frames at 30 fps with start '01:00:00:00' => 01:00:01:00
expect(formatTimecode(30, 30, 'timecode', '01:00:00:00')).toBe('01:00:01:00')
})
})
describe('other display modes', () => {
it('formats as frames index', () => {
expect(formatTimecode(150, 30, 'frames')).toBe('150 fr')
})
it('formats as standard MM:SS time', () => {
expect(formatTimecode(150, 30, 'standard')).toBe('00:05')
})
})
describe('calculateFrameCenterTime tests', () => {
it('calculates frame center time correctly', () => {
// frame 0 at 30 fps => 0 * 1/30 + 1/60 = 1/60 = 0.0166666...
expect(calculateFrameCenterTime(0, 30)).toBeCloseTo(0.0166666, 5)
// frame 251 at 30 fps => 251 * 1/30 + 1/60 = 251.5 / 30 = 8.3833333...
expect(calculateFrameCenterTime(251, 30)).toBeCloseTo(8.3833333, 5)
// frame rate 0 returns 0
expect(calculateFrameCenterTime(10, 0)).toBe(0)
})
})
})
describe('stallThresholdMs', () => {
it('is 100ms at 30fps and 60fps (floor of 100ms dominates)', () => {
expect(stallThresholdMs(30)).toBe(100)
expect(stallThresholdMs(60)).toBe(100)
})
it('is frame-rate dependent below 30fps', () => {
// 3000 / 24 = 125ms
expect(stallThresholdMs(24)).toBe(125)
// 3000 / 25 = 120ms
expect(stallThresholdMs(25)).toBe(120)
})
it('guards against a falsy frame rate by treating it as 30fps', () => {
expect(stallThresholdMs(0)).toBe(100)
})
})
describe('resolveTotalFrames', () => {
describe('at 30fps (100ms stall threshold)', () => {
it('uses the video-stream count when there is no container tail', () => {
expect(resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 5, frameRate: 30 })).toBe(
150,
)
})
it('uses the video-stream count for a sub-threshold tail (videoA / ~2 frames)', () => {
// video 268 frames = 8.9333s, container 9.008s -> 0.0747s tail (< 100ms).
// Must NOT inflate to round(9.008 * 30) = 270.
expect(
resolveTotalFrames({ dbTotalFrames: 268, containerDuration: 9.008, frameRate: 30 }),
).toBe(268)
})
it('uses the video-stream count for the container-longer e2e fixture tail', () => {
// 150 frames = 5.0s, container 5.075s -> 0.075s tail (< 100ms).
expect(
resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 5.075, frameRate: 30 }),
).toBe(150)
})
it('still uses the video-stream count just below the threshold', () => {
// 300 frames = 10s, container 10.09s -> 0.09s tail (< 100ms).
expect(
resolveTotalFrames({ dbTotalFrames: 300, containerDuration: 10.09, frameRate: 30 }),
).toBe(300)
})
it('switches to the container count just above the threshold', () => {
// 300 frames = 10s, container 10.11s -> 0.11s tail (> 100ms).
// round(10.11 * 30) = 303.
expect(
resolveTotalFrames({ dbTotalFrames: 300, containerDuration: 10.11, frameRate: 30 }),
).toBe(303)
})
it('uses the container count for a large tail (videoB / long audio)', () => {
// 150 frames = 5.0s, container 6.5s -> 1.5s tail. round(6.5 * 30) = 195.
expect(
resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 6.5, frameRate: 30 }),
).toBe(195)
})
})
describe('frame-rate dependence of the threshold', () => {
it('treats a 100ms tail as below threshold at 24fps (threshold 125ms)', () => {
// 240 frames = 10s, container 10.1s -> 0.1s tail (< 125ms at 24fps).
expect(
resolveTotalFrames({ dbTotalFrames: 240, containerDuration: 10.1, frameRate: 24 }),
).toBe(240)
})
it('treats a 130ms tail as above threshold at 24fps', () => {
// 240 frames = 10s, container 10.13s -> 0.13s tail (> 125ms).
// round(10.13 * 24) = 243.
expect(
resolveTotalFrames({ dbTotalFrames: 240, containerDuration: 10.13, frameRate: 24 }),
).toBe(243)
})
})
describe('missing video-stream frame count', () => {
it('falls back to the container-derived count when nb_frames is 0', () => {
expect(resolveTotalFrames({ dbTotalFrames: 0, containerDuration: 5, frameRate: 30 })).toBe(
150,
)
expect(resolveTotalFrames({ dbTotalFrames: 0, containerDuration: 6.5, frameRate: 30 })).toBe(
195,
)
})
})
})
@@ -0,0 +1,156 @@
export const formatTime = (seconds: number): string => {
if (isNaN(seconds)) return '00:00'
const date = new Date(seconds * 1000)
const hh = date.getUTCHours()
const mm = date.getUTCMinutes().toString().padStart(2, '0')
const ss = date.getUTCSeconds().toString().padStart(2, '0')
if (hh) {
return `${hh}:${mm}:${ss}`
}
return `${mm}:${ss}`
}
export const formatTimecode = (
frameIndex: number,
frameRate: number,
mode: 'standard' | 'frames' | 'timecode',
startTimecode?: string | null,
): string => {
if (mode === 'frames') {
return `${frameIndex} fr`
}
if (mode === 'standard') {
return formatTime(frameIndex / frameRate)
}
// Determine if drop-frame should be used (standard for NTSC 29.97 and 59.94)
const frameRateRound = Math.round(frameRate)
const isFractional = frameRate !== frameRateRound
let dropFrame = false
if (isFractional && (frameRateRound === 30 || frameRateRound === 60)) {
dropFrame = true
}
// Parse start timecode if provided
let startFrameCount = 0
if (startTimecode) {
const parts = startTimecode.match(/^([012]\d):(\d\d):(\d\d)(:|;|\.)(\d+)$/)
if (parts) {
const hours = parseInt(parts[1], 10)
const minutes = parseInt(parts[2], 10)
const seconds = parseInt(parts[3], 10)
const frames = parseInt(parts[5], 10)
// Timecode string format overrides the default dropFrame setting
dropFrame = parts[4] !== ':'
// Calculate frame count from timecode
startFrameCount = (hours * 3600 + minutes * 60 + seconds) * frameRateRound + frames
if (dropFrame) {
const totalMinutes = hours * 60 + minutes
const df = frameRate < 30 ? 2 : 4
startFrameCount -= df * (totalMinutes - Math.floor(totalMinutes / 10))
}
}
}
// Calculate absolute frame count
let fc = frameIndex + startFrameCount
// Convert frame count to timecode using the exact smpte-timecode formula
if (dropFrame) {
const df = frameRate < 30 ? 2 : 4
const d = Math.floor(fc / ((17982 * df) / 2))
let m = fc % ((17982 * df) / 2)
if (m < df) {
m = m + df
}
fc += 9 * df * d + df * Math.floor((m - df) / ((1798 * df) / 2))
}
const frames = fc % frameRateRound
const seconds = Math.floor(fc / frameRateRound) % 60
const minutes = Math.floor(fc / (frameRateRound * 60)) % 60
const hours = Math.floor(fc / (frameRateRound * 3600)) % 24
const separator = dropFrame ? ';' : ':'
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}${separator}${frames.toString().padStart(2, '0')}`
}
export const formatTimestamp = (seconds: number, fps: number): string => {
if (isNaN(seconds)) return '00:00:00:00'
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.45)
}
export const calculateFrameCenterTime = (frameIndex: number, frameRate: number): number => {
if (!frameRate) return 0
const frameDuration = 1 / frameRate
return frameIndex * frameDuration + frameDuration / 2
}
/**
* The dynamic playback stall threshold, in milliseconds: the window of
* `requestVideoFrameCallback` silence after which the playback loop's
* `requestAnimationFrame` fallback begins driving the playhead from
* `video.currentTime`.
*
* Shared by `useFramePlayer` (runtime stall detection) and `resolveTotalFrames`
* (frame-count derivation) so the two stay in lockstep: the boundary at which a
* container's audio-only tail becomes *reachable* by the playhead is exactly the
* boundary at which we start counting those tail frames.
*/
export const stallThresholdMs = (frameRate: number): number =>
Math.max(100, 3000 / (frameRate || 30))
interface ResolveTotalFramesArgs {
/**
* Physical video-stream frame count (ffprobe `nb_frames`), as stored in
* `metadata.totalFrames`.
*/
dbTotalFrames: number
/**
* Container/format duration in seconds (`metadata.duration`). May exceed the
* video-stream duration when e.g. the audio track is longer.
*/
containerDuration: number
frameRate: number
}
/**
* Derive the player's effective total frame count.
*
* A container's duration can exceed its video stream (commonly because the audio
* track is slightly longer, or from container overhead). Deriving the frame count
* from the container duration in that case invents phantom trailing frames the
* video stream does not contain.
*
* We only trust the container-derived count when the extra tail is long enough
* for the playhead to actually reach it during playback — i.e. longer than the
* playback stall threshold (see `stallThresholdMs`). Below that threshold the
* RAF fallback never activates, so those tail frames are unreachable and would
* strand the readout short of its own maximum; we use the accurate video-stream
* frame count instead.
*
* When `nb_frames` is unavailable (`dbTotalFrames <= 0`), fall back to the
* container-derived count.
*/
export const resolveTotalFrames = ({
dbTotalFrames,
containerDuration,
frameRate,
}: ResolveTotalFramesArgs): number => {
const fps = frameRate || 30
const containerFrames = Math.round(containerDuration * fps)
if (dbTotalFrames <= 0) return containerFrames
const videoDuration = dbTotalFrames / fps
const tailSeconds = containerDuration - videoDuration
const thresholdSeconds = stallThresholdMs(fps) / 1000
return tailSeconds > thresholdSeconds ? containerFrames : dbTotalFrames
}
@@ -0,0 +1,374 @@
import { cn } from '@/ui/lib/utils'
import { useUiStore } from '@/ui/stores/ui'
import type { AssetInfo, VideoTranscode } from '@shumai/dtos'
import {
Check,
ChevronDown,
Download,
Maximize,
Minimize,
Minus,
Pause,
Play,
Plus,
Repeat,
Settings,
Volume2,
VolumeX,
} from 'lucide-react'
import React from 'react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '../../ui/dropdown-menu'
import { Slider } from '../../ui/slider'
import ProgressBar from './progress-bar'
import { formatTime, formatTimecode } from './utils'
export interface PlayerState {
isPlaying: boolean
progress: number // 0 to 100
currentTime: number
duration: number
volume: number
isMuted: boolean
isLooping: boolean
playbackRate: number
isFullScreen: boolean
showFrames: boolean // Toggle between time (02:30) and frames (1234)
currentResolution: string // 'Original' or '720p', '480p' etc.
currentSrc?: string
}
export type DisplayTranscode = VideoTranscode & { resolution: string }
export interface ControlBarProps {
state: PlayerState
zoom: number
isControlsVisible: boolean
buffered: number
data: AssetInfo
resolutions: DisplayTranscode[]
togglePlay: () => void
toggleLoop: () => void
toggleMute: () => void
handleVolumeChange: (newVolume: number) => void
changePlaybackRate: (rate: number) => void
changeResolution: (res: DisplayTranscode) => void
handleDownload: (key: string) => void
toggleFullScreen: () => void
onZoomChange: (zoom: number) => void
onZoomReset: () => void
// Frame-accurate props
frameRate: number
totalFrames: number
currentFrame: number
seekToFrame: (frame: number) => Promise<void> | void
/**
* Whether the bar floats as an absolute overlay over the media while
* fullscreen (single-file player). Compare mode sets this false so the bar
* stays in-flow. Colors are always theme-aware regardless of this flag.
*/
floatOverlayInFullScreen?: boolean
/** Fired when the cursor enters/leaves the bar (used to pin it visible). */
onMouseEnter?: () => void
onMouseLeave?: () => void
}
export const VideoControlBar: React.FC<ControlBarProps> = ({
state,
zoom,
isControlsVisible,
buffered,
data,
resolutions,
togglePlay,
toggleLoop,
toggleMute,
handleVolumeChange,
changePlaybackRate,
changeResolution,
handleDownload,
toggleFullScreen,
onZoomChange,
onZoomReset,
frameRate,
totalFrames,
currentFrame,
seekToFrame,
floatOverlayInFullScreen = true,
onMouseEnter,
onMouseLeave,
}) => {
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
if (!data.media?.metadata) {
return null
}
// Whether to render the bar as a floating overlay over the media (single-file
// fullscreen). Compare keeps it in-flow. Colors stay theme-aware either way.
const overlay = state.isFullScreen && floatOverlayInFullScreen
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const startTimecode = data.media?.metadata?.startTimecode
const displayTotalFrames = Math.max(0, totalFrames - 1)
const displayString =
videoTimeDisplayMode === 'frames'
? `${currentFrame} / ${displayTotalFrames} fr`
: videoTimeDisplayMode === 'standard'
? `${formatTimecode(currentFrame, frameRate, 'standard')} / ${formatTime(totalFrames / frameRate)}`
: `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}`
return (
<div
className={cn(
'transition-all duration-300 ease-in-out z-20 text-foreground',
overlay
? 'absolute bottom-0 left-0 right-0 px-4 py-4 bg-card/90 backdrop-blur-md border-t border-border'
: 'relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200',
isControlsVisible
? 'opacity-100 translate-y-0'
: 'opacity-0 translate-y-4 pointer-events-none',
)}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
{/* Progress Bar */}
<div className="mb-4 px-1">
<ProgressBar
totalFrames={totalFrames}
currentFrame={currentFrame}
fps={frameRate}
buffered={buffered}
previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame}
metadata={{
...data.media.metadata,
frameRate: frameRate,
}}
/>
</div>
{/* Lower Controls Row */}
<div className="flex items-center justify-between text-foreground">
{/* Left Side: Play, Vol, Time */}
<div className="flex items-center gap-4">
<button
onClick={togglePlay}
className="hover:text-primary transition-colors"
data-testid="play-toggle"
data-playing={state.isPlaying}
aria-label={state.isPlaying ? 'Pause' : 'Play'}
>
{state.isPlaying ? (
<Pause className="w-6 h-6 fill-current" />
) : (
<Play className="w-6 h-6 fill-current" />
)}
</button>
<button
onClick={toggleLoop}
className={cn(
'transition-colors',
state.isLooping ? 'text-primary' : 'text-muted-foreground',
)}
title="Loop"
>
<Repeat className="w-5 h-5" />
</button>
<div className="flex items-center gap-3 group/vol">
<button onClick={toggleMute} className="hover:text-primary">
{state.isMuted || state.volume === 0 ? (
<VolumeX className="w-6 h-6" />
) : (
<Volume2 className="w-6 h-6" />
)}
</button>
<div className="w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out">
<div className="w-24 px-1">
<Slider
value={state.isMuted ? [0] : [state.volume]}
onValueChange={(v: number[]) => handleVolumeChange(v[0])}
max={1}
step={0.05}
/>
</div>
</div>
</div>
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
<span className="text-muted-foreground font-mono" data-testid="time-readout">
{displayString}
</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
<ChevronDown className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-40 z-30">
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
Format
</DropdownMenuLabel>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('standard')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Standard Time</span>
{videoTimeDisplayMode === 'standard' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('frames')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Frames</span>
{videoTimeDisplayMode === 'frames' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('timecode')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Timecode</span>
{videoTimeDisplayMode === 'timecode' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
<div className="relative flex items-center gap-3">
{/* Zoom Controls */}
<div className="flex items-center gap-1">
<div className="flex items-center gap-1 rounded-md bg-muted p-0.5">
<button
onClick={() => onZoomChange(zoom * 0.8)}
className="p-1 hover:text-primary rounded"
>
<Minus size={14} />
</button>
<span className="text-xs w-8 text-center tabular-nums">
{Math.round(zoom * 100)}%
</span>
<button
onClick={() => onZoomChange(zoom * 1.2)}
className="p-1 hover:text-primary rounded"
>
<Plus size={14} />
</button>
</div>
<button
onClick={onZoomReset}
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
>
Fit
</button>
</div>
{/* Playback Rate */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="w-8 text-sm font-bold hover:text-primary">
{state.playbackRate}x
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
{[0.5, 1, 1.5, 2].map((rate) => (
<DropdownMenuItem
key={rate}
onClick={() => changePlaybackRate(rate)}
className={cn(
'rounded py-1 px-2 text-left text-xs',
state.playbackRate === rate
? 'bg-primary text-primary-foreground focus:bg-primary focus:text-primary-foreground'
: 'text-foreground',
)}
>
{rate}x
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Resolution Selector */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="flex items-center gap-1 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors">
<Settings className="h-3.5 w-3.5" />
<span>{state.currentResolution}</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Quality</DropdownMenuLabel>
{previewResolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => changeResolution(res)}
className={cn(
'flex w-full items-center justify-between',
state.currentResolution === res.resolution
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{res.resolution}</span>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Download */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="transition-colors hover:text-primary" title="Download">
<Download className="h-5 w-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Download</DropdownMenuLabel>
{resolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{res.resolution}</span>
<span className="text-xs text-muted-foreground">
{res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Fullscreen */}
<button onClick={toggleFullScreen} className="transition-colors hover:text-primary">
{state.isFullScreen ? (
<Minimize className="h-6 w-6" />
) : (
<Maximize className="h-6 w-6" />
)}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,649 @@
import { client } from '@/ui/api/client'
import { cn } from '@/ui/lib/utils'
import { Play } from 'lucide-react'
import React, { useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react'
import videojs from 'video.js'
import type Player from 'video.js/dist/types/player'
import { useFramePlayer } from './use-frame-player'
import { resolveTotalFrames } from './utils'
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import { FileViewerProps, MediaController } from '../types'
const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
(
{ file: data, onPlay, onPause, onTimeUpdate, annotations, startTime, shareId, children },
ref,
) => {
const localPlayerRef = useRef<Player | null>(null)
const playerRef = localPlayerRef
// We use a container ref to manually append the video element
const videoContainerRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const rootRef = useRef<HTMLDivElement>(null)
const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useImperativeHandle(ref, () => ({
play: () => {
if (localPlayerRef.current) {
localPlayerRef.current.play()
}
},
pause: () => {
if (localPlayerRef.current) {
localPlayerRef.current.pause()
}
},
seekTo: (second: number) => {
if (localPlayerRef.current) {
localPlayerRef.current.currentTime(second)
}
},
getCurrentTime: () => {
return (localPlayerRef.current ? localPlayerRef.current.currentTime() : 0) ?? 0
},
getDuration: () => {
return (localPlayerRef.current ? localPlayerRef.current.duration() : 0) ?? 0
},
}))
const isOverControlsRef = useRef(false)
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
const videoRef = useRef<HTMLVideoElement | null>(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)
}
const handleZoomReset = () => {
setHasManuallyZoomed(false)
}
// Store
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
} = useAnnotationStore()
// Combine annotations
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
// Resize Observer for container
useEffect(() => {
if (!containerRef.current) return
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(containerRef.current)
return () => observer.disconnect()
}, [])
// Fit to screen initial / responsive resize
useEffect(() => {
if (containerSize.width > 0 && containerSize.height > 0) {
const vidW = data.media?.metadata?.originalWidth ?? 1920
const vidH = data.media?.metadata?.originalHeight ?? 1080
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
if (!hasManuallyZoomed) {
setZoom(scale)
}
}
}, [containerSize.width, containerSize.height, data.media?.metadata, hasManuallyZoomed])
// Cleanup ref when player is disposed
useEffect(() => {
return () => {
videoRef.current = null
}
}, [])
if (!data.media?.original?.downloadUrl || !data.media.metadata) {
return (
<div className="flex h-full w-full items-center justify-center">
<p className="text-muted-foreground">Media is not available.</p>
</div>
)
}
// Initial resolution setup
const originalRes: DisplayTranscode = {
id: 'original',
url: data.media.original.downloadUrl,
key: data.media.original.key ?? '',
width: data.media.metadata.originalWidth ?? 0,
height: data.media.metadata.originalHeight ?? 0,
size: 0,
isRaw: true,
resolution: 'Original',
}
const resolutions: DisplayTranscode[] = (data.media.videoTranscodes ?? []).map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return {
...t,
resolution: t.isRaw ? 'Original' : resolution,
}
})
const previewResolutions = resolutions.filter((r) => !r.isRaw)
// Logic to select best resolution based on screen size
const getInitialResolution = (): DisplayTranscode => {
if (previewResolutions.length === 0) return originalRes
if (typeof window === 'undefined') return previewResolutions[0]
// Use device pixel ratio for high DPI screens
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
// 1. Sort by width ascending
const sortedResolutions = [...previewResolutions].sort((a, b) => {
const wA = a.width ?? 0
const wB = b.width ?? 0
return wA - wB
})
// 2. Find first one >= screenWidth
const bestFit = sortedResolutions.find((r) => (r.width ?? 0) >= screenWidth)
// 3. If found, return it. If not (all are smaller), return the last one (largest).
return bestFit || sortedResolutions[sortedResolutions.length - 1]
}
const initialRes = getInitialResolution()
// State
const [state, setState] = useState<PlayerState>({
isPlaying: false,
progress: 0,
currentTime: 0,
duration: data.media.metadata.duration || 0,
volume: 1,
isMuted: false,
isLooping: false,
playbackRate: 1,
isFullScreen: false,
showFrames: false,
currentResolution: initialRes.resolution,
currentSrc: initialRes.url,
})
const [buffered, setBuffered] = useState(0)
const [isControlsVisible, setIsControlsVisible] = useState(true)
const [isPlayerReady, setIsPlayerReady] = useState(false)
const lastProcessedStartTimeRef = useRef<number | null>(null)
// Frame-accurate hook and derived state
const metadata = data.media.metadata
const frameRate = metadata.frameRate || 30
const dbTotalFrames = metadata.totalFrames || 0
const containerDuration = metadata.duration || 0
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
const currentTime = currentFrame / frameRate
const duration = totalFrames / frameRate
const progress = duration > 0 ? (currentTime / duration) * 100 : 0
const controlBarState: PlayerState = {
...state,
currentTime,
duration,
progress,
}
// Trigger time update event reactively
useEffect(() => {
if (onTimeUpdate) {
onTimeUpdate(currentFrame / frameRate)
}
}, [currentFrame, frameRate, onTimeUpdate])
// Initialize Video.js
useEffect(() => {
if (!videoContainerRef.current) return
// 1. Create the video element manually
// This avoids conflicts with React Strict Mode where the DOM might not match React's virtual DOM expectations after Video.js modifies it.
const videoElement = document.createElement('video-js')
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
// Hide it, but keep it in DOM
videoElement.style.opacity = '0'
videoElement.style.pointerEvents = 'none'
// Append to our container
videoContainerRef.current.appendChild(videoElement)
// 2. Initialize the player
const player = (playerRef.current = videojs(videoElement, {
controls: false,
autoplay: false,
preload: 'auto',
playsinline: true,
sources: [
{
src: state.currentSrc,
type: 'video/mp4',
},
],
}))
// Extract video element for Konva
const htmlVid = videoElement.querySelector('video')
if (htmlVid) {
setVideoHtmlEl(htmlVid)
videoRef.current = htmlVid
} else {
// Fallback: try player.tech().el()
// Wait for ready?
player.ready(() => {
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
if (techEl) {
setVideoHtmlEl(techEl)
videoRef.current = techEl
}
})
}
player.on('play', () => {
setState((p) => ({ ...p, isPlaying: true }))
onPlay?.()
})
player.on('pause', () => {
setState((p) => ({ ...p, isPlaying: false }))
onPause?.()
})
player.on('ended', () => setState((p) => ({ ...p, isPlaying: false })))
player.on('loadedmetadata', () => {
setIsPlayerReady(true)
})
player.on('loadstart', () => {
setIsPlayerReady(false)
})
player.on('timeupdate', () => {
const playerDuration = player.duration() || data.media?.metadata?.duration || 0
const bufferedEnd = player.bufferedEnd()
if (playerDuration > 0) {
setBuffered((bufferedEnd / playerDuration) * 100)
}
})
player.on('volumechange', () => {
const vol = player.volume()
const muted = player.muted()
setState((prev) => ({
...prev,
volume: vol || 0,
isMuted: muted || false,
}))
})
player.on('ratechange', () => {
setState((prev) => ({
...prev,
playbackRate: player.playbackRate() || 1,
}))
})
player.on('error', () => {
console.error('VideoJS Error:', player.error())
})
// Set initial state
player.volume(state.volume)
// 4. Cleanup
return () => {
if (player && !player.isDisposed()) {
player.dispose()
playerRef.current = null
videoRef.current = null
}
}
}, [data])
// Handle changes to startTime (e.g., clicking different chunks in search results)
useEffect(() => {
if (!isPlayerReady) return
if (startTime !== undefined && startTime !== null && startTime > 0) {
if (startTime !== lastProcessedStartTimeRef.current) {
lastProcessedStartTimeRef.current = startTime
const targetFrame = Math.floor(startTime * frameRate + 0.45)
seekToFrame(targetFrame)
}
}
}, [startTime, frameRate, seekToFrame, isPlayerReady])
const scheduleHide = useCallback(() => {
if (controlsTimeoutRef.current) {
clearTimeout(controlsTimeoutRef.current)
}
// Never hide while the cursor rests over the control bar itself.
if (state.isFullScreen && !isOverControlsRef.current) {
controlsTimeoutRef.current = setTimeout(() => {
setIsControlsVisible(false)
}, 1200)
}
}, [state.isFullScreen])
const handleMouseMove = useCallback(() => {
// Always show controls on movement, then (re)start the idle hide timer.
setIsControlsVisible(true)
scheduleHide()
}, [scheduleHide])
const handleControlsMouseEnter = useCallback(() => {
isOverControlsRef.current = true
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
setIsControlsVisible(true)
}, [])
const handleControlsMouseLeave = useCallback(() => {
isOverControlsRef.current = false
scheduleHide()
}, [scheduleHide])
const handleMouseLeave = useCallback(() => {
// If the cursor leaves the player while fullscreen, hide the controls.
if (state.isFullScreen) {
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
setIsControlsVisible(false)
}
}, [state.isFullScreen])
// Clean up timeout on unmount or state change
useEffect(() => {
return () => {
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
}
}, [])
// Windowed mode: controls are always visible. Fullscreen: show now and let
// the idle timer hide them (re-runs on play/pause so pausing re-reveals them).
useEffect(() => {
if (!state.isFullScreen) {
setIsControlsVisible(true)
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
} else {
handleMouseMove()
}
}, [state.isPlaying, state.isFullScreen, handleMouseMove])
// -- Event Handlers --
const togglePlay = useCallback(() => {
// Disable click-to-play if drawing
if (useAnnotationStore.getState().isDrawing) return
const player = playerRef.current
if (!player) return
if (player.paused() || player.ended()) {
const playPromise = player.play()
if (playPromise !== undefined) {
playPromise.catch((error) => {
// Ignore AbortError which happens when pausing rapidly after playing
if (error.name === 'AbortError') return
console.error('Play failed:', error)
})
}
} else {
player.pause()
}
}, [])
const toggleLoop = () => {
const player = playerRef.current
if (!player) return
const newLoop = !state.isLooping
player.loop(newLoop)
setState((prev) => ({ ...prev, isLooping: newLoop }))
}
const handleVolumeChange = (newVolume: number) => {
// Optimistic update to prevent slider jumping and ensure immediate UI feedback
setState((prev) => ({
...prev,
volume: newVolume,
isMuted: newVolume === 0, // If dragging to 0, consider it muted
}))
const player = playerRef.current
if (!player) return
// Set volume first so if we unmute, it is at the correct level
player.volume(newVolume)
// Manage mute state based on volume
if (newVolume > 0 && player.muted()) {
player.muted(false)
} else if (newVolume === 0 && !player.muted()) {
player.muted(true)
}
}
const toggleMute = () => {
const player = playerRef.current
if (!player) return
const isMuted = player.muted()
if (isMuted) {
player.muted(false)
// If volume was 0 (e.g. user dragged to 0), restore to default 0.5 so they hear something
if (player.volume() === 0) {
player.volume(0.5)
}
} else {
player.muted(true)
}
}
const changePlaybackRate = (rate: number) => {
const player = playerRef.current
if (!player) return
player.playbackRate(rate)
}
const changeResolution = (res: DisplayTranscode) => {
const player = playerRef.current
if (!player) return
const wasPlaying = !player.paused()
const currentT = player.currentTime()
setState((prev) => ({
...prev,
currentResolution: res.resolution,
currentSrc: res.url,
}))
player.src({ type: 'video/mp4', src: res.url })
player.one('loadedmetadata', () => {
player.currentTime(currentT)
if (wasPlaying) {
const playPromise = player.play()
if (playPromise !== undefined) {
playPromise.catch((error) => {
if (error.name === 'AbortError') return
console.error('Play after seek failed:', error)
})
}
}
player.playbackRate(state.playbackRate)
})
}
const toggleFullScreen = () => {
if (!rootRef.current) return
if (!document.fullscreenElement) {
rootRef.current.requestFullscreen()
setState((prev) => ({ ...prev, isFullScreen: true }))
} else {
document.exitFullscreen()
setState((prev) => ({ ...prev, isFullScreen: false }))
}
}
const handleDownload = async (key: string) => {
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: data.id! },
json: { key },
})
: await client.api.files['download-url'].$post({
json: { key, assetId: data.id! },
})
if (!res.ok) return
const { url } = await res.json()
const link = document.createElement('a')
link.href = url
link.download = ''
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// silently fail
}
}
// Listen for fullscreen change events (ESC key)
useEffect(() => {
const onFsChange = () => {
setState((prev) => ({
...prev,
isFullScreen: !!document.fullscreenElement,
}))
}
document.addEventListener('fullscreenchange', onFsChange)
return () => document.removeEventListener('fullscreenchange', onFsChange)
}, [])
// Calculate center pan
const vidW = data.media?.metadata?.originalWidth ?? 1920
const vidH = data.media?.metadata?.originalHeight ?? 1080
const scale = zoom
const panX = (containerSize.width - vidW * scale) / 2
const panY = (containerSize.height - vidH * scale) / 2
return (
<div
ref={rootRef}
className={cn(
'group shadow-2xl font-sans select-none flex flex-col mx-auto transition-all duration-300 relative',
state.isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
!isControlsVisible && state.isFullScreen ? 'cursor-none' : '',
)}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{/* Render Carousel/Sidebar here if not fullscreen */}
{!state.isFullScreen && children}
{/* Video Area */}
<div
ref={containerRef}
className={cn(
'flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0',
)}
onClick={togglePlay}
data-vjs-player
data-testid="video-area"
>
{/* Hidden VideoJS container */}
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{/* Drawing Canvas (Visible) */}
{videoHtmlEl && containerSize.width > 0 && (
<DrawingCanvas
width={containerSize.width}
height={containerSize.height}
mediaDimensions={{
width: vidW,
height: vidH,
}}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={{ x: panX, y: panY }}
className="absolute inset-0"
onClick={togglePlay}
// Drawing Props
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)}
{/* Big Play Button Overlay (when paused) */}
{!state.isPlaying && !isDrawing && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
<Play className="w-10 h-10 text-white ml-1 fill-white" />
</div>
</div>
)}
</div>
</div>
<VideoControlBar
state={controlBarState}
zoom={zoom}
isControlsVisible={isControlsVisible}
buffered={buffered}
data={data}
resolutions={resolutions}
togglePlay={togglePlay}
toggleLoop={toggleLoop}
toggleMute={toggleMute}
handleVolumeChange={handleVolumeChange}
changePlaybackRate={changePlaybackRate}
changeResolution={changeResolution}
handleDownload={handleDownload}
toggleFullScreen={toggleFullScreen}
onZoomChange={handleZoomChange}
onZoomReset={handleZoomReset}
frameRate={frameRate}
totalFrames={totalFrames}
currentFrame={currentFrame}
seekToFrame={seekToFrame}
onMouseEnter={handleControlsMouseEnter}
onMouseLeave={handleControlsMouseLeave}
/>
</div>
)
},
)
export default VideoViewer