diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index 2bebc2a9..61ea2639 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -234,6 +234,7 @@ describe('TranscodeService', () => { originalHeight: 1080, bitRate: 1000, frameRate: 30, + totalFrames: 300, hasAudio: true, mimeType: 'video/mp4', }) diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 099b5aff..640cd624 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -18,6 +18,7 @@ export interface MediaMetadata { duration: number bitRate: number frameRate: number + totalFrames: number hasAudio: boolean videoCodec?: string audioCodec?: string @@ -90,15 +91,46 @@ export class TranscodeService { throw new Error('No video stream found') } - const frameRateParts = videoStream.r_frame_rate.split('/') - const frameRate = parseFloat(frameRateParts[0]) / parseFloat(frameRateParts[1]) + let fps = 0 + if (videoStream.avg_frame_rate) { + const parts = videoStream.avg_frame_rate.split('/') + if (parts.length === 2) { + const num = parseFloat(parts[0]) + const den = parseFloat(parts[1]) + if (den > 0) { + fps = num / den + } + } + } + + if (fps === 0 && videoStream.r_frame_rate) { + const parts = videoStream.r_frame_rate.split('/') + if (parts.length === 2) { + const num = parseFloat(parts[0]) + const den = parseFloat(parts[1]) + if (den > 0) { + fps = num / den + } + } + } + + const duration = parseFloat(info.format.duration) + let totalFrames = 0 + if (videoStream.nb_frames) { + totalFrames = parseInt(videoStream.nb_frames, 10) + } + + if (!totalFrames && fps > 0 && !isNaN(duration)) { + totalFrames = Math.round(duration * fps) + } return { originalWidth: videoStream.width, originalHeight: videoStream.height, - duration: parseFloat(info.format.duration), + duration, bitRate: parseFloat(info.format.bit_rate), - frameRate, + frameRate: fps || 30, + totalFrames: totalFrames || 0, hasAudio: !!audioStream, videoCodec: this.resolveCodecName(videoStream), audioCodec: audioStream ? this.resolveCodecName(audioStream) : undefined, @@ -128,6 +160,7 @@ export class TranscodeService { duration: 0, bitRate: 0, frameRate: 0, + totalFrames: 0, hasAudio: false, mimeType: metadata.format || '', } @@ -142,11 +175,36 @@ export class TranscodeService { const args = ['-i', params.inputFile, '-filter_complex', filterComplex, '-map', '[vout]'] + if (params.frameRate) { + let calculatedFps: number + if (typeof params.frameRate === 'number') { + calculatedFps = params.frameRate + } else { + const parts = params.frameRate.split('/') + if (parts.length === 2) { + calculatedFps = parseFloat(parts[0]) / parseFloat(parts[1]) + } else { + calculatedFps = parseFloat(params.frameRate) + } + } + if (!isNaN(calculatedFps) && calculatedFps > 0) { + const roundedFps = Math.max(1, Math.round(calculatedFps)) + args.push( + '-r', + calculatedFps.toString(), + '-g', + roundedFps.toString(), + '-force_key_frames', + 'expr:gte(t,n_forced*1)', + ) + } + } + if (!params.disableAudio) { args.push('-map', '0:a?') } - args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '23') + args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '26') if (!params.disableAudio) { args.push('-c:a', 'aac', '-b:a', '128k') diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index dbd1b086..a26e9b72 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -106,6 +106,7 @@ declare global { duration: number bitRate: number frameRate: number + totalFrames?: number videoCodec?: string audioCodec?: string audioChannels?: number @@ -124,7 +125,6 @@ declare global { export interface MediaInfo { duration: number filesize: number - fps: number frames: number imageTranscodes: ImageTranscode[] videoTranscodes: VideoTranscode[] diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 0b87b9bd..eb2b3e3c 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -47,6 +47,7 @@ export const mediaMetadataSchema = z.object({ originalWidth: z.number().optional(), originalHeight: z.number().optional(), frameRate: z.number().optional(), + totalFrames: z.number().optional(), }) export type MediaMetadata = z.infer diff --git a/packages/transcode/src/activities/transcode.test.ts b/packages/transcode/src/activities/transcode.test.ts index b4586ef6..042d8d69 100644 --- a/packages/transcode/src/activities/transcode.test.ts +++ b/packages/transcode/src/activities/transcode.test.ts @@ -81,6 +81,7 @@ describe('Transcode Activities', () => { duration: 10, bitRate: 1000, frameRate: 30, + totalFrames: 300, hasAudio: true, videoCodec: 'Advanced Video Coding', audioCodec: 'MPEG-4 Audio', @@ -121,6 +122,7 @@ describe('Transcode Activities', () => { duration: 0, bitRate: 0, frameRate: 0, + totalFrames: 0, hasAudio: false, mimeType: 'image/png', }) diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts index 2017a863..79b9c70d 100644 --- a/packages/transcode/src/activities/transcode.ts +++ b/packages/transcode/src/activities/transcode.ts @@ -61,7 +61,6 @@ export async function getMediaInfoActivity(params: { const mediaInfo: PrismaJson.MediaInfo = { duration: 0, filesize: 0, - fps: 0, frames: 0, imageTranscodes: [], videoTranscodes: [], @@ -84,13 +83,14 @@ export async function getMediaInfoActivity(params: { if (isVideo) { const info = await transcodeService.getVideoInfo(params.filePath) mediaInfo.duration = info.duration - mediaInfo.fps = info.frameRate + mediaInfo.frames = info.totalFrames mediaInfo.metadata = { originalWidth: info.originalWidth, originalHeight: info.originalHeight, duration: info.duration, bitRate: info.bitRate, frameRate: info.frameRate, + totalFrames: info.totalFrames, hasAudio: info.hasAudio, videoCodec: info.videoCodec, audioCodec: info.audioCodec, @@ -172,7 +172,7 @@ export async function transcodeVideoActivity( const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`) try { - let targetFps: number | string = 0 + let targetFps: number | string = params.originalFps || 30 let disableAudio = false if (params.videoSpec.resolution === '180p') { diff --git a/packages/webui/components/viewers/progress-bar.tsx b/packages/webui/components/viewers/progress-bar.tsx index 44531b6b..3af8a42b 100644 --- a/packages/webui/components/viewers/progress-bar.tsx +++ b/packages/webui/components/viewers/progress-bar.tsx @@ -15,17 +15,19 @@ const formatTime = (seconds: number): string => { } interface ProgressBarProps { - duration: number - currentTime: number + totalFrames: number + currentFrame: number + fps: number previewUrl?: string - onSeek: (time: number) => void + onSeek: (frame: number) => void buffered?: number metadata?: MediaMetadata } const ProgressBar: React.FC = ({ - duration, - currentTime, + totalFrames, + currentFrame, + fps, previewUrl, onSeek, buffered = 0, @@ -68,16 +70,17 @@ const ProgressBar: React.FC = ({ setHoverPosition(percentage) setIsHovering(true) - if (previewVideoRef.current && duration) { - const seekTime = percentage * duration - // Use fastSeek if available for smoother scrubbing, otherwise currentTime + 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 } } }, - [duration, isDragging], + [totalFrames, fps, isDragging], ) const handleMouseLeave = () => { @@ -94,7 +97,7 @@ const ProgressBar: React.FC = ({ const percentage = getPercentageFromEvent(e.clientX) setHoverPosition(percentage) setIsHovering(true) - onSeekRef.current(percentage * duration) + onSeekRef.current(percentage * totalFrames) } const handleTouchStart = (e: React.TouchEvent) => { @@ -102,7 +105,7 @@ const ProgressBar: React.FC = ({ const percentage = getPercentageFromEvent(e.touches[0].clientX) setHoverPosition(percentage) setIsHovering(true) - onSeekRef.current(percentage * duration) + onSeekRef.current(percentage * totalFrames) } useEffect(() => { @@ -113,15 +116,17 @@ const ProgressBar: React.FC = ({ setHoverPosition(percentage) setIsHovering(true) - if (previewVideoRef.current && duration) { - const seekTime = percentage * duration + 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 * duration) + onSeekRef.current(percentage * totalFrames) } const handleWindowMouseUp = (e: MouseEvent) => { @@ -143,7 +148,7 @@ const ProgressBar: React.FC = ({ } const percentage = getPercentageFromEvent(e.clientX) - onSeekRef.current(percentage * duration) + onSeekRef.current(percentage * totalFrames) } const handleWindowTouchMove = (e: TouchEvent) => { @@ -152,15 +157,17 @@ const ProgressBar: React.FC = ({ setHoverPosition(percentage) setIsHovering(true) - if (previewVideoRef.current && duration) { - const seekTime = percentage * duration + 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 * duration) + onSeekRef.current(percentage * totalFrames) } const handleWindowTouchEnd = (e: TouchEvent) => { @@ -186,7 +193,7 @@ const ProgressBar: React.FC = ({ if (clientX !== null) { const percentage = getPercentageFromEvent(clientX) - onSeekRef.current(percentage * duration) + onSeekRef.current(percentage * totalFrames) } } @@ -201,21 +208,17 @@ const ProgressBar: React.FC = ({ window.removeEventListener('touchmove', handleWindowTouchMove) window.removeEventListener('touchend', handleWindowTouchEnd) } - }, [isDragging, duration, getPercentageFromEvent]) + }, [isDragging, totalFrames, fps, getPercentageFromEvent]) const progressPercent = isDragging && hoverPosition !== null ? hoverPosition * 100 - : duration > 0 - ? (currentTime / duration) * 100 + : totalFrames > 0 + ? (currentFrame / totalFrames) * 100 : 0 const hoverPercent = hoverPosition !== null ? hoverPosition * 100 : 0 // Calculate preview tooltip position - // Logic: Interpolate translation based on position to keep preview fully visible - // 0% -> translateX(0%) (Left aligned) - // 50% -> translateX(-50%) (Center aligned) - // 100% -> translateX(-100%) (Right aligned) const getTooltipStyle = () => { if (hoverPosition === null) return {} return { @@ -271,7 +274,7 @@ const ProgressBar: React.FC = ({ /> {/* Hover Preview Tooltip */} - {isHovering && duration > 0 && ( + {isHovering && totalFrames > 0 && (
= ({ }} />
- {formatTime(hoverPosition! * duration)} + {formatTime((hoverPosition! * totalFrames) / fps)}
diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts new file mode 100644 index 00000000..876caf75 --- /dev/null +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -0,0 +1,266 @@ +import React, { useState, useEffect, useRef, useCallback } from 'react' + +export interface UseFramePlayerResult { + currentFrame: number + setCurrentFrame: React.Dispatch> + seekToFrame: (targetFrame: number) => Promise + isSeeking: React.RefObject +} + +interface HtmlVideoElementWithCallback { + requestVideoFrameCallback?: ( + callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void, + ) => number + cancelVideoFrameCallback?: (id: number) => void +} + +export function useFramePlayer( + videoRef: React.RefObject, + frameRate: number, + totalFrames: number, +): UseFramePlayerResult { + const [currentFrame, setCurrentFrame] = useState(0) + const isSeekingRef = useRef(false) + const isPlayingRef = useRef(false) + const pendingSeekFrameRef = useRef(null) + + // 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 + + const updateFrameLoop = () => { + if (!active) return + + if (video.paused || video.ended) { + return + } + + const videoWithCallback = video as unknown as HtmlVideoElementWithCallback + if (videoWithCallback.requestVideoFrameCallback) { + 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() + }, + ) + } else { + // Fallback for browsers without requestVideoFrameCallback + const frame = Math.round(video.currentTime * frameRate) + const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) + setCurrentFrame(clamped) + rafId = requestAnimationFrame(updateFrameLoop) + } + } + + const handlePlay = () => { + 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 frame on pause + const frame = Math.round(video.currentTime * frameRate) + const clamped = Math.max(0, Math.min(frame, totalFrames - 1)) + setCurrentFrame(clamped) + } + + video.addEventListener('play', handlePlay) + video.addEventListener('pause', handlePause) + + // If it's already playing when this effect runs + if (!video.paused) { + 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 frameDuration = 1 / frameRate + const safeTargetTime = frameToSeek * frameDuration + frameDuration / 2 + const wasPlaying = !video.paused + + video.currentTime = safeTargetTime + + // Wait for native seek to complete + await new Promise((resolve) => { + const onSeeked = () => { + video.removeEventListener('seeked', onSeeked) + resolve() + } + video.addEventListener('seeked', onSeeked) + }) + + // 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 (accounts for half-frame offset) + const actualFrame = Math.floor(video.currentTime * frameRate) + 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.round(metadata.mediaTime * frameRate) + 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(currentFrame + delta) + } else if (e.key === 'ArrowLeft') { + e.preventDefault() + const delta = e.shiftKey ? 10 : 1 + seekToFrame(currentFrame - delta) + } + } + + window.addEventListener('keydown', handleKeyDown) + return () => { + window.removeEventListener('keydown', handleKeyDown) + } + }, [currentFrame, 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) + const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1)) + setCurrentFrame(finalFrame) + } + } + + video.addEventListener('seeked', handleExternalSeeked) + return () => { + video.removeEventListener('seeked', handleExternalSeeked) + } + }, [videoRef.current, frameRate, totalFrames]) + + return { + currentFrame, + setCurrentFrame, + seekToFrame, + isSeeking: isSeekingRef, + } +} diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 02ac2c84..1303cae9 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -25,7 +25,8 @@ import { } from '../ui/dropdown-menu' import { Slider } from '../ui/slider' import ProgressBar from './progress-bar' -import { formatFrame, formatTime } from './utils' +import { formatTime } from './utils' +import { useFramePlayer } from './use-frame-player' import type { Annotation } from '@/ui/types' import DrawingCanvas from '../drawing-canvas' @@ -68,7 +69,6 @@ interface ControlBarProps { resolutions: DisplayTranscode[] togglePlay: () => void toggleLoop: () => void - handleSeek: (time: number) => void toggleMute: () => void handleVolumeChange: (newVolume: number) => void setState: React.Dispatch> @@ -77,6 +77,11 @@ interface ControlBarProps { handleDownload: (url: string, resolution: string) => void toggleFullScreen: () => void onZoomChange: (zoom: number) => void + // Frame-accurate props + frameRate: number + totalFrames: number + currentFrame: number + seekToFrame: (frame: number) => Promise } const ControlBar: React.FC = ({ @@ -88,7 +93,6 @@ const ControlBar: React.FC = ({ resolutions, togglePlay, toggleLoop, - handleSeek, toggleMute, handleVolumeChange, setState, @@ -97,6 +101,10 @@ const ControlBar: React.FC = ({ handleDownload, toggleFullScreen, onZoomChange, + frameRate, + totalFrames, + currentFrame, + seekToFrame, }) => { if (!data.media?.metadata) { return null @@ -119,14 +127,15 @@ const ControlBar: React.FC = ({ {/* Progress Bar */}
@@ -186,8 +195,8 @@ const ControlBar: React.FC = ({ title="Click to toggle Time/Frames" > {state.showFrames - ? `${formatFrame(state.currentTime, data.media.metadata.frameRate ?? 30)} / ${formatFrame(state.duration, data.media.metadata.frameRate ?? 30)}` - : `${formatTime(state.currentTime)} / ${formatTime(state.duration)}`} + ? `${currentFrame} / ${totalFrames}` + : `${formatTime(currentFrame / frameRate)} / ${formatTime(totalFrames / frameRate)}`} {state.showFrames ? 'fr' : ''} @@ -323,6 +332,7 @@ const VideoPlayer: React.FC = ({ const controlsTimeoutRef = useRef | null>(null) const [videoHtmlEl, setVideoHtmlEl] = useState(undefined) + const videoRef = useRef(null) const [zoom, setZoom] = useState(1) const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }) @@ -369,6 +379,13 @@ const VideoPlayer: React.FC = ({ } }, [containerSize.width, containerSize.height, data.media?.metadata]) + // Cleanup ref when player is disposed + useEffect(() => { + return () => { + videoRef.current = null + } + }, []) + if (!data.media?.original?.downloadUrl || !data.media.metadata) { return (
@@ -447,6 +464,30 @@ const VideoPlayer: React.FC = ({ const [buffered, setBuffered] = useState(0) const [isControlsVisible, setIsControlsVisible] = useState(true) + // Frame-accurate hook and derived state + const metadata = data.media.metadata + const frameRate = metadata.frameRate || 30 + const totalFrames = metadata.totalFrames || Math.round((metadata.duration || 0) * 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 @@ -481,12 +522,16 @@ const VideoPlayer: React.FC = ({ 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) + if (techEl) { + setVideoHtmlEl(techEl) + videoRef.current = techEl + } }) } @@ -501,30 +546,11 @@ const VideoPlayer: React.FC = ({ player.on('ended', () => setState((p) => ({ ...p, isPlaying: false }))) player.on('timeupdate', () => { - const current = player.currentTime() || 0 - const duration = player.duration() || data.media?.metadata?.duration || 0 + const playerDuration = player.duration() || data.media?.metadata?.duration || 0 const bufferedEnd = player.bufferedEnd() - if (duration > 0) { - setBuffered((bufferedEnd / duration) * 100) - } - - // Only update state here if the player is paused. - // When playing, requestAnimationFrame handles smooth updates. - if (player.paused()) { - setState((prev) => { - if (prev.currentTime === current) return prev - return { - ...prev, - currentTime: current, - duration: duration || prev.duration, - progress: duration > 0 ? (current / duration) * 100 : 0, - } - }) - } - - if (onTimeUpdate) { - onTimeUpdate(current) + if (playerDuration > 0) { + setBuffered((bufferedEnd / playerDuration) * 100) } }) @@ -555,7 +581,7 @@ const VideoPlayer: React.FC = ({ // Seek to startTime if provided if (startTime && startTime > 0) { player.ready(() => { - player.currentTime(startTime) + seekToFrame(Math.round(startTime * frameRate)) }) } @@ -564,56 +590,20 @@ const VideoPlayer: React.FC = ({ 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(() => { - const player = playerRef.current - if (player && startTime !== undefined && startTime !== null && startTime > 0) { - // Only seek if the difference is significant (e.g., > 1s) to avoid jumping due to small precision differences - const current = player.currentTime() || 0 - if (Math.abs(current - startTime) > 1) { - player.currentTime(startTime) + if (startTime !== undefined && startTime !== null && startTime > 0) { + const targetFrame = Math.round(startTime * frameRate) + if (Math.abs(currentFrame - targetFrame) > frameRate) { + seekToFrame(targetFrame) } } - }, [startTime, playerRef]) - - // Smooth progress updates using requestAnimationFrame when playing - useEffect(() => { - let animationFrameId: number - - const updateProgress = () => { - const player = playerRef.current - if (player && !player.paused()) { - const current = player.currentTime() || 0 - const duration = player.duration() || data.media?.metadata?.duration || 0 - - setState((prev) => { - if (prev.currentTime === current) return prev - return { - ...prev, - currentTime: current, - duration: duration || prev.duration, - progress: duration > 0 ? (current / duration) * 100 : 0, - } - }) - - animationFrameId = requestAnimationFrame(updateProgress) - } - } - - if (state.isPlaying) { - animationFrameId = requestAnimationFrame(updateProgress) - } - - return () => { - if (animationFrameId) { - cancelAnimationFrame(animationFrameId) - } - } - }, [state.isPlaying, playerRef, data.media?.metadata?.duration]) + }, [startTime, frameRate, currentFrame, seekToFrame]) const handleMouseMove = useCallback(() => { // Always show controls on movement @@ -689,13 +679,6 @@ const VideoPlayer: React.FC = ({ setState((prev) => ({ ...prev, isLooping: newLoop })) } - const handleSeek = (time: number) => { - const player = playerRef.current - if (!player) return - player.currentTime(time) - setState((prev) => ({ ...prev, currentTime: time })) - } - const handleVolumeChange = (newVolume: number) => { // Optimistic update to prevent slider jumping and ensure immediate UI feedback setState((prev) => ({ @@ -745,7 +728,7 @@ const VideoPlayer: React.FC = ({ if (!player) return const wasPlaying = !player.paused() - const currentTime = player.currentTime() + const currentT = player.currentTime() setState((prev) => ({ ...prev, @@ -756,7 +739,7 @@ const VideoPlayer: React.FC = ({ player.src({ type: 'video/mp4', src: res.url }) player.one('loadedmetadata', () => { - player.currentTime(currentTime) + player.currentTime(currentT) if (wasPlaying) { const playPromise = player.play() if (playPromise !== undefined) { @@ -871,7 +854,7 @@ const VideoPlayer: React.FC = ({
= ({ resolutions={resolutions} togglePlay={togglePlay} toggleLoop={toggleLoop} - handleSeek={handleSeek} toggleMute={toggleMute} handleVolumeChange={handleVolumeChange} setState={setState} @@ -888,6 +870,10 @@ const VideoPlayer: React.FC = ({ handleDownload={handleDownload} toggleFullScreen={toggleFullScreen} onZoomChange={setZoom} + frameRate={frameRate} + totalFrames={totalFrames} + currentFrame={currentFrame} + seekToFrame={seekToFrame} /> )