mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 22:14:50 +00:00
The single-file player fullscreened the inner video-area element, which is not an ancestor of the control bar, so the bar was never visible in fullscreen. Fullscreen the player root instead so the floating control bar is included and the existing show-on-move / hide-after-idle logic works (YouTube-style). Also make the control-bar colors theme-aware in all cases. The fullscreen floating overlay now uses bg-card/90 + backdrop-blur + foreground text instead of a hardcoded dark overlay, so it follows the app light/dark theme. The former themedChrome prop is renamed to floatOverlayInFullScreen (default true = single-file floating overlay; compare passes false to keep its bar in-flow).
634 lines
19 KiB
TypeScript
634 lines
19 KiB
TypeScript
import type { AssetInfo } from '@shumai/dtos'
|
|
import { client } from '@/ui/api/client'
|
|
import { cn } from '@/ui/lib/utils'
|
|
import { Play } from 'lucide-react'
|
|
import React, { useCallback, useEffect, 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 { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
|
|
|
|
import type { Annotation } from '@/ui/types'
|
|
import DrawingCanvas from '../drawing-canvas'
|
|
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
|
|
|
interface VideoPlayerProps {
|
|
data: AssetInfo
|
|
playerRef?: React.RefObject<Player | null>
|
|
onPlay?: () => void
|
|
onPause?: () => void
|
|
onTimeUpdate?: (time: number) => void
|
|
annotations?: Annotation[]
|
|
startTime?: number
|
|
shareId?: string
|
|
children?: React.ReactNode
|
|
}
|
|
|
|
const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
|
data,
|
|
playerRef: passedPlayerRef,
|
|
onPlay,
|
|
onPause,
|
|
onTimeUpdate,
|
|
annotations,
|
|
startTime,
|
|
shareId,
|
|
children,
|
|
}) => {
|
|
const localPlayerRef = useRef<Player | null>(null)
|
|
const playerRef = passedPlayerRef || 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)
|
|
|
|
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 videoDuration = dbTotalFrames / frameRate
|
|
const frameDuration = 1 / frameRate
|
|
|
|
const totalFrames =
|
|
containerDuration - videoDuration > 0.5 * frameDuration
|
|
? Math.round(containerDuration * frameRate)
|
|
: dbTotalFrames
|
|
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
|
|
|
|
const currentTime = currentFrame / frameRate
|
|
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 handleMouseMove = useCallback(() => {
|
|
// Always show controls on movement
|
|
setIsControlsVisible(true)
|
|
|
|
if (controlsTimeoutRef.current) {
|
|
clearTimeout(controlsTimeoutRef.current)
|
|
}
|
|
|
|
// Only set auto-hide timer if we are in fullscreen and playing
|
|
// If paused, controls should remain visible so user can see what to do
|
|
if (state.isFullScreen && state.isPlaying) {
|
|
controlsTimeoutRef.current = setTimeout(() => {
|
|
setIsControlsVisible(false)
|
|
}, 2000)
|
|
}
|
|
}, [state.isFullScreen, state.isPlaying])
|
|
|
|
const handleMouseLeave = useCallback(() => {
|
|
// If we leave the player area in fullscreen, hide controls (optional preference, usually good)
|
|
if (state.isFullScreen && state.isPlaying) {
|
|
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
|
setIsControlsVisible(false)
|
|
}
|
|
}, [state.isFullScreen, state.isPlaying])
|
|
|
|
// Clean up timeout on unmount or state change
|
|
useEffect(() => {
|
|
return () => {
|
|
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
|
}
|
|
}, [])
|
|
|
|
// Ensure controls are visible when pausing or entering fullscreen initially
|
|
useEffect(() => {
|
|
if (!state.isPlaying) {
|
|
setIsControlsVisible(true)
|
|
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
|
} else {
|
|
// If we just started playing (or re-entered playing state), trigger the timer logic
|
|
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}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default VideoPlayer
|