feat(transcode): add HDR video proxy support and playback (#424)

* feat(transcode): add HDR output proxy support

* fix(transcode): auto-detect MoltenVK Vulkan ICD on macOS for libplacebo filters

* fix(transcode): split filter in generateSprite to ensure poster uses tone-mapped stream

* docs(changelog): update docs/changelog.mdx and ignore in prettier

* fix(transcode): respect video rotation metadata to preserve display aspect ratio

* fix(webui): render native video with hardware EDR acceleration instead of 2D canvas

* fix(webui): show HDR label on mobile video control bar

* fix(share): preserve hdr flag on watermarked video transcodes

* fix(webui): differentiate HDR download options in video player

* fix(transcode): handle Dolby Vision Profile 5 via standard HDR pipeline without libplacebo

* fix(transcode): prepend setparams filter to prevent zscale colorspace path error for DV P5

* refactor(transcode): simplify HDR proxies to always produce HDR without SDR setting
This commit is contained in:
Yiling-J
2026-09-24 14:32:47 +08:00
committed by GitHub
parent f579947770
commit c3375ee935
38 changed files with 1986 additions and 164 deletions
+4 -2
View File
@@ -84,6 +84,7 @@ interface BreadcrumbNavProps {
key: string
width: number
height: number
hdr?: boolean
}>
}
versions?: Array<{
@@ -294,13 +295,14 @@ export function BreadcrumbNav({
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
const label = t.hdr ? `${resolution} (HDR)` : resolution
return (
<DropdownMenuItem
key={resolution}
key={t.key || `${resolution}-${t.hdr ? 'hdr' : 'sdr'}`}
onClick={() => handleDownload(t.key)}
className="flex items-center justify-between"
>
<span>{resolution}</span>
<span>{label}</span>
<span className="text-xs text-muted-foreground">MP4</span>
</DropdownMenuItem>
)
@@ -19,7 +19,7 @@ interface CompareControlBarProps {
onVolumeChange: (volume: number) => void
onToggleMute: () => void
onChangePlaybackRate: (rate: number) => void
onChangeResolution: (resolution: string) => void
onChangeResolution: (resolution: string, hdr?: boolean) => void
onZoomIn: () => void
onZoomOut: () => void
onFit: () => void
@@ -65,6 +65,7 @@ export function CompareControlBar({
isFullScreen,
showFrames: false,
currentResolution: v.currentResolution,
isCurrentHdr: v.isCurrentHdr,
}
// The active-side asset carries the metadata used for timecode display and
@@ -88,7 +89,7 @@ export function CompareControlBar({
toggleMute={onToggleMute}
handleVolumeChange={onVolumeChange}
changePlaybackRate={onChangePlaybackRate}
changeResolution={(res: DisplayTranscode) => onChangeResolution(res.resolution)}
changeResolution={(res: DisplayTranscode) => onChangeResolution(res.resolution, res.hdr)}
handleDownload={(key?: string) => onDownload(key)}
toggleFullScreen={onToggleFullScreen}
onZoomChange={(nz: number) => (nz >= activeState.zoom ? onZoomIn() : onZoomOut())}
@@ -213,7 +213,7 @@ export function CompareViewer({
)
const handleChangeResolution = useCallback(
(resolution: string) => getActive()?.changeResolution(resolution),
(resolution: string, hdr?: boolean) => getActive()?.changeResolution(resolution, hdr),
[getActive],
)
+2 -1
View File
@@ -23,6 +23,7 @@ export interface PaneReportedState {
playbackRate: number
isLooping: boolean
currentResolution: string
isCurrentHdr?: boolean
resolutions: DisplayTranscode[]
buffered: number
}
@@ -45,7 +46,7 @@ export interface ComparePaneHandle {
setVolume: (volume: number) => void
setPlaybackRate: (rate: number) => void
toggleLoop: () => void
changeResolution: (resolution: string) => void
changeResolution: (resolution: string, hdr?: boolean) => void
// Zoom / pan (image + video)
zoomBy: (factor: number) => void
fit: () => void
+37 -52
View File
@@ -19,7 +19,6 @@ interface DrawingCanvasProps {
imageUrl?: string
/** A live canvas to draw instead of an image URL (e.g. a PDF.js page render). */
canvasElement?: HTMLCanvasElement | null
videoElement?: HTMLVideoElement
annotations: Annotation[]
scale: number
offset: { x: number; y: number }
@@ -40,7 +39,6 @@ const DrawingCanvas = ({
mediaDimensions,
imageUrl,
canvasElement,
videoElement,
annotations,
scale,
offset,
@@ -53,7 +51,7 @@ const DrawingCanvas = ({
onAddAnnotation,
}: DrawingCanvasProps) => {
const [loadedImage] = useImage(imageUrl || '', 'anonymous')
const imageRef = useRef<Konva.Image>(null)
const mediaGroupRef = useRef<Konva.Group>(null)
const isDragging = useRef(false)
const lastPos = useRef({ x: 0, y: 0 })
const startPointRef = useRef<{ x: number; y: number } | null>(null)
@@ -66,27 +64,11 @@ const DrawingCanvas = ({
// Force a redraw whenever the live canvas source is swapped, so the layer
// picks up the new page raster (Konva redraws the source each batchDraw).
useEffect(() => {
if (canvasElement && imageRef.current) {
imageRef.current.getLayer()?.batchDraw()
if (canvasElement && mediaGroupRef.current) {
mediaGroupRef.current.getLayer()?.batchDraw()
}
}, [canvasElement])
// Handle Video Redraw
useEffect(() => {
if (videoElement && imageRef.current) {
const layer = imageRef.current.getLayer()
if (!layer) return
const anim = new Konva.Animation(() => {
// Force redraw to update video frame
}, layer)
anim.start()
return () => {
anim.stop()
}
}
}, [videoElement])
// -- Helpers --
const getRelativePointerPosition = (
node: Konva.Node,
@@ -217,7 +199,7 @@ const DrawingCanvas = ({
const handleGlobalMove = (e: MouseEvent | TouchEvent) => {
if (!isDragging.current) return
const stage = imageRef.current?.getStage()
const stage = mediaGroupRef.current?.getStage()
if (!stage) return
const container = stage.container()
const rect = container.getBoundingClientRect()
@@ -255,11 +237,11 @@ const DrawingCanvas = ({
if (activeDrawing) {
if (tool === 'select') return
const pos = getRelativePointerPosition(imageRef.current!, true, stagePos)
const pos = getRelativePointerPosition(mediaGroupRef.current!, true, stagePos)
if (!pos || !startPointRef.current) return
const start = startPointRef.current
const layer = imageRef.current?.getLayer()
const layer = mediaGroupRef.current?.getLayer()
if (tool === 'freehand' && currentLineRef.current) {
const newPoints = currentLineRef.current.points().concat([pos.x, pos.y])
@@ -317,8 +299,8 @@ const DrawingCanvas = ({
const stage = e.target.getStage()
if (!stage) return
// Use imageRef to get coordinates relative to the image (handling zoom/pan)
const pos = getRelativePointerPosition(imageRef.current!)
// Use mediaGroupRef to get coordinates relative to the media (handling zoom/pan)
const pos = getRelativePointerPosition(mediaGroupRef.current!)
if (!pos) return
// Only start drawing if within media bounds
@@ -334,7 +316,7 @@ const DrawingCanvas = ({
isDragging.current = true
startPointRef.current = pos
const layer = imageRef.current?.getLayer()
const layer = mediaGroupRef.current?.getLayer()
if (!layer) return
if (currentTool === 'freehand' && currentLineRef.current) {
@@ -474,32 +456,35 @@ const DrawingCanvas = ({
onTouchStart={handleMouseDown}
>
<Layer>
<KonvaImage
ref={imageRef}
image={videoElement || canvasElement || loadedImage}
width={mediaDimensions.width}
height={mediaDimensions.height}
/>
{annotations.map(renderAnnotation)}
<Group ref={mediaGroupRef} width={mediaDimensions.width} height={mediaDimensions.height}>
{(canvasElement || loadedImage) && (
<KonvaImage
image={canvasElement || loadedImage}
width={mediaDimensions.width}
height={mediaDimensions.height}
/>
)}
{annotations.map(renderAnnotation)}
{/* Draft Shapes */}
<Group listening={false}>
<Line
ref={currentLineRef}
strokeWidth={2.6 / scale}
lineCap="round"
lineJoin="round"
visible={false}
/>
<Rect ref={currentRectRef} strokeWidth={2.6 / scale} visible={false} />
<Arrow
ref={currentArrowRef}
points={[]}
strokeWidth={2.6 / scale}
pointerLength={10 / scale}
pointerWidth={10 / scale}
visible={false}
/>
{/* Draft Shapes */}
<Group listening={false}>
<Line
ref={currentLineRef}
strokeWidth={2.6 / scale}
lineCap="round"
lineJoin="round"
visible={false}
/>
<Rect ref={currentRectRef} strokeWidth={2.6 / scale} visible={false} />
<Arrow
ref={currentArrowRef}
points={[]}
strokeWidth={2.6 / scale}
pointerLength={10 / scale}
pointerWidth={10 / scale}
visible={false}
/>
</Group>
</Group>
</Layer>
</Stage>
@@ -145,6 +145,7 @@ export function MobileFileDetail({
key: t.key,
width: t.width,
height: t.height,
hdr: t.hdr,
})),
}
}, [file.media])
@@ -46,6 +46,7 @@ export interface MobileFileHeaderProps {
key: string
width: number
height: number
hdr?: boolean
}>
}
canEdit?: boolean
@@ -245,13 +246,14 @@ export function MobileFileHeader({
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
const label = t.hdr ? `${resolution} (HDR)` : resolution
return (
<DropdownMenuItem
key={resolution}
key={t.key || `${resolution}-${t.hdr ? 'hdr' : 'sdr'}`}
onClick={() => handleDownload(t.key)}
className="flex items-center justify-between text-xs cursor-pointer"
>
<span>{resolution}</span>
<span>{label}</span>
<span className="text-[10px] text-muted-foreground">MP4</span>
</DropdownMenuItem>
)
@@ -440,6 +440,7 @@ export function PublicShareManager({
key: t.key,
width: t.width,
height: t.height,
hdr: t.hdr,
})),
}
: undefined,
@@ -45,6 +45,28 @@ function computeResolutions(file: AssetInfo): DisplayTranscode[] {
})
}
function getInitialResolution(resolutions: DisplayTranscode[]): DisplayTranscode | null {
if (resolutions.length === 0) return null
if (typeof window === 'undefined') return resolutions[0]
const prefersHdr =
typeof window.matchMedia === 'function' && window.matchMedia('(dynamic-range: high)').matches
const hasHdr = resolutions.some((r) => r.hdr)
const hasSdr = resolutions.some((r) => !r.hdr)
let candidates = resolutions
if (prefersHdr && hasHdr) {
candidates = resolutions.filter((r) => r.hdr)
} else if (!prefersHdr && hasSdr) {
candidates = resolutions.filter((r) => !r.hdr)
}
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
const sorted = [...candidates].sort((a, b) => (a.width ?? 0) - (b.width ?? 0))
const bestFit = sorted.find((r) => (r.width ?? 0) >= screenWidth)
return bestFit || sorted[sorted.length - 1]
}
export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPaneProps>(
function CompareVideoPane(
{
@@ -66,7 +88,6 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
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,
@@ -96,8 +117,9 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const resolutions = computeResolutions(file)
const initialRes = resolutions[0]
const initialRes = getInitialResolution(resolutions)
const [currentResolution, setCurrentResolution] = useState(initialRes?.resolution ?? '')
const [isCurrentHdr, setIsCurrentHdr] = useState(initialRes?.hdr)
const currentSrcRef = useRef(initialRes?.url)
const isAudio = file.proxyType === 'audio'
@@ -137,8 +159,10 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
// 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 ?? '')
currentSrcRef.current = initialRes?.url
const res = getInitialResolution(resolutions)
setCurrentResolution(res?.resolution ?? '')
setIsCurrentHdr(res?.hdr)
currentSrcRef.current = res?.url
}, [file.id])
// Initialize video.js
@@ -146,7 +170,6 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
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)
@@ -160,13 +183,11 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
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
}
})
@@ -178,13 +199,15 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
})
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)
setBuffered(player.bufferedPercent())
})
player.on('loadedmetadata', () => {
setIsPlayerReady(true)
})
player.on('loadstart', () => setIsPlayerReady(false))
player.on('volumechange', () => {
setPlayerVolume(player.volume() || 0)
setPlayerMuted(player.muted() || false)
@@ -223,6 +246,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
playbackRate,
isLooping,
currentResolution,
isCurrentHdr,
resolutions,
buffered,
},
@@ -239,6 +263,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
playbackRate,
isLooping,
currentResolution,
isCurrentHdr,
buffered,
])
@@ -294,14 +319,20 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
)
const changeResolution = useCallback(
(resolution: string) => {
(resolution: string, hdr?: boolean) => {
const player = playerRef.current
if (!player) return
const target = resolutions.find((r) => r.resolution === resolution)
const target =
hdr !== undefined
? resolutions.find(
(r) => r.resolution === resolution && Boolean(r.hdr) === Boolean(hdr),
)
: resolutions.find((r) => r.resolution === resolution)
if (!target) return
const wasPlaying = !player.paused()
const currentT = player.currentTime()
setCurrentResolution(resolution)
setIsCurrentHdr(target.hdr)
currentSrcRef.current = target.url
player.src({ type: 'video/mp4', src: target.url })
player.one('loadedmetadata', () => {
@@ -420,7 +451,28 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
onClick={handleAreaClick}
data-testid="compare-video-area"
>
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{/* Native Video Layer (Hardware-accelerated, full HDR EDR) */}
{!isAudio && (
<div
className="absolute pointer-events-none"
style={{
left: 0,
top: 0,
width: vidW,
height: vidH,
transform: `translate(${panX}px, ${panY}px) scale(${scale})`,
transformOrigin: '0 0',
}}
>
<div
ref={videoContainerRef}
className="w-full h-full [&_.video-js]:!w-full [&_.video-js]:!h-full [&_video]:!w-full [&_video]:!h-full [&_video]:!block [&_video]:!object-contain"
/>
</div>
)}
{isAudio && (
<div ref={videoContainerRef} className="absolute inset-0 pointer-events-none opacity-0" />
)}
{isAudio ? (
<div className="flex flex-col items-center justify-center text-muted-foreground w-full h-full pointer-events-none select-none">
@@ -432,13 +484,11 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
/>
</div>
) : (
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 }}
@@ -93,4 +93,92 @@ describe('MobileVideoControlBar', () => {
fireEvent.click(fsBtn)
expect(toggleFullScreen).toHaveBeenCalledTimes(1)
})
it('renders HDR label on settings button when playing HDR video', () => {
render(
<MobileVideoControlBar
state={{
...defaultState,
currentResolution: '1080p',
isCurrentHdr: true,
}}
zoom={1}
isControlsVisible={true}
buffered={50}
data={mockData}
resolutions={[
{
key: '1080-hdr.mp4',
width: 1920,
height: 1080,
resolution: '1080p',
hdr: true,
} as unknown as DisplayTranscode,
]}
togglePlay={vi.fn()}
toggleLoop={vi.fn()}
toggleMute={vi.fn()}
handleVolumeChange={vi.fn()}
changePlaybackRate={vi.fn()}
changeResolution={vi.fn()}
handleDownload={vi.fn()}
toggleFullScreen={vi.fn()}
onZoomChange={vi.fn()}
onZoomReset={vi.fn()}
frameRate={25}
totalFrames={2500}
currentFrame={250}
seekToFrame={vi.fn()}
/>,
)
const settingsBtn = screen.getByLabelText(/Settings/i)
expect(settingsBtn).toBeDefined()
expect(settingsBtn.textContent).toContain('1080p')
expect(settingsBtn.textContent).toContain('HDR')
})
it('does not render HDR label on settings button when playing SDR video', () => {
render(
<MobileVideoControlBar
state={{
...defaultState,
currentResolution: '1080p',
isCurrentHdr: false,
}}
zoom={1}
isControlsVisible={true}
buffered={50}
data={mockData}
resolutions={[
{
key: '1080.mp4',
width: 1920,
height: 1080,
resolution: '1080p',
hdr: false,
} as unknown as DisplayTranscode,
]}
togglePlay={vi.fn()}
toggleLoop={vi.fn()}
toggleMute={vi.fn()}
handleVolumeChange={vi.fn()}
changePlaybackRate={vi.fn()}
changeResolution={vi.fn()}
handleDownload={vi.fn()}
toggleFullScreen={vi.fn()}
onZoomChange={vi.fn()}
onZoomReset={vi.fn()}
frameRate={25}
totalFrames={2500}
currentFrame={250}
seekToFrame={vi.fn()}
/>,
)
const settingsBtn = screen.getByLabelText(/Settings/i)
expect(settingsBtn).toBeDefined()
expect(settingsBtn.textContent).toContain('1080p')
expect(settingsBtn.textContent).not.toContain('HDR')
})
})
@@ -186,10 +186,19 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
aria-label={m.settings()}
>
<Settings className="h-3.5 w-3.5" />
<span className="text-[11px]">
{!isAudio && state.currentResolution
? state.currentResolution
: `${state.playbackRate}x`}
<span className="flex items-center gap-1 text-[11px]">
<span>
{!isAudio && state.currentResolution
? state.currentResolution === 'Original'
? m.original()
: state.currentResolution
: `${state.playbackRate}x`}
</span>
{!isAudio && state.isCurrentHdr && (
<span className="px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</span>
</button>
</DropdownMenuTrigger>
@@ -199,23 +208,36 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
{m.quality()}
</DropdownMenuLabel>
{resolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => changeResolution(res)}
className={cn(
'flex w-full items-center justify-between text-xs cursor-pointer',
state.currentResolution === res.resolution
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{res.resolution === 'Original' ? m.original() : res.resolution}</span>
<span className="text-[10px] text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
))}
{resolutions.map((res) => {
const itemKey = `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
const isSelected =
state.currentResolution === res.resolution &&
Boolean(state.isCurrentHdr) === Boolean(res.hdr)
return (
<DropdownMenuItem
key={itemKey}
onClick={() => changeResolution(res)}
className={cn(
'flex w-full items-center justify-between text-xs cursor-pointer',
isSelected ? 'text-primary font-medium' : 'text-foreground',
)}
>
<div className="flex items-center gap-1.5">
<span>
{res.resolution === 'Original' ? m.original() : res.resolution}
</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="text-[10px] text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
)
})}
<DropdownMenuSeparator />
</>
)}
@@ -0,0 +1,110 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { VideoControlBar } from './video-control-bar'
import type { AssetInfo } from '@shumai/dtos'
import type { DisplayTranscode, PlayerState } from './video-control-bar'
describe('VideoControlBar', () => {
afterEach(() => {
cleanup()
})
const mockData: AssetInfo = {
id: 'video-1',
name: 'sample.mp4',
proxyType: 'video',
media: {
original: { key: 'files/sample.mp4' },
metadata: {
duration: 100,
frameRate: 25,
},
},
} as AssetInfo
const defaultState: PlayerState = {
isPlaying: false,
progress: 10,
currentTime: 10,
duration: 100,
volume: 1,
isMuted: false,
isLooping: false,
playbackRate: 1,
isFullScreen: false,
showFrames: false,
currentResolution: '1080p',
isCurrentHdr: false,
}
const resolutions: DisplayTranscode[] = [
{
key: '1080.mp4',
width: 1920,
height: 1080,
resolution: '1080p',
hdr: false,
} as unknown as DisplayTranscode,
{
key: '1080-hdr.mp4',
width: 1920,
height: 1080,
resolution: '1080p',
hdr: true,
} as unknown as DisplayTranscode,
]
it('renders download menu with HDR badge on HDR download items', async () => {
const handleDownload = vi.fn()
render(
<VideoControlBar
state={defaultState}
zoom={1}
isControlsVisible={true}
buffered={50}
data={mockData}
resolutions={resolutions}
togglePlay={vi.fn()}
toggleLoop={vi.fn()}
toggleMute={vi.fn()}
handleVolumeChange={vi.fn()}
changePlaybackRate={vi.fn()}
changeResolution={vi.fn()}
handleDownload={handleDownload}
toggleFullScreen={vi.fn()}
onZoomChange={vi.fn()}
onZoomReset={vi.fn()}
frameRate={25}
totalFrames={2500}
currentFrame={250}
seekToFrame={vi.fn()}
allowDownload={true}
/>,
)
const downloadTrigger = screen.getByTitle(/Download/i)
expect(downloadTrigger).toBeDefined()
fireEvent.pointerDown(downloadTrigger, { button: 0, ctrlKey: false })
const menuItems = await screen.findAllByRole('menuitem')
// We expect: 1080p SDR, 1080p HDR, and Original
expect(menuItems.length).toBe(3)
const sdrItem = menuItems.find(
(item) => item.textContent?.includes('1080p') && !item.textContent?.includes('HDR'),
)
const hdrItem = menuItems.find(
(item) => item.textContent?.includes('1080p') && item.textContent?.includes('HDR'),
)
expect(sdrItem).toBeDefined()
expect(hdrItem).toBeDefined()
// Clicking HDR item triggers download with HDR key
fireEvent.click(hdrItem!)
expect(handleDownload).toHaveBeenCalledWith('1080-hdr.mp4')
})
})
@@ -43,6 +43,7 @@ export interface PlayerState {
showFrames: boolean // Toggle between time (02:30) and frames (1234)
currentResolution: string // 'Original' or '720p', '480p' etc.
currentSrc?: string
isCurrentHdr?: boolean
}
export type DisplayTranscode = VideoTranscode & { resolution: string }
@@ -317,35 +318,53 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
{!isAudio && resolutions.length > 0 && (
<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">
<button className="flex items-center gap-1.5 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 === 'Original'
? m.original()
: state.currentResolution}
<span className="flex items-center gap-1">
<span>
{state.currentResolution === 'Original'
? m.original()
: state.currentResolution}
</span>
{state.isCurrentHdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>{m.quality()}</DropdownMenuLabel>
{resolutions.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 === 'Original' ? m.original() : res.resolution}</span>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
))}
{resolutions.map((res) => {
const itemKey = `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
const isSelected =
state.currentResolution === res.resolution &&
Boolean(state.isCurrentHdr) === Boolean(res.hdr)
return (
<DropdownMenuItem
key={itemKey}
onClick={() => changeResolution(res)}
className={cn(
'flex w-full items-center justify-between',
isSelected ? 'text-primary font-medium' : 'text-foreground',
)}
>
<div className="flex items-center gap-1.5">
<span>{res.resolution === 'Original' ? m.original() : res.resolution}</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
)}
@@ -370,16 +389,26 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>{m.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">MP4</span>
</DropdownMenuItem>
))}
{resolutions.map((res) => {
const itemKey = res.key || `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
return (
<DropdownMenuItem
key={itemKey}
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground cursor-pointer"
>
<div className="flex items-center gap-1.5">
<span>{res.resolution}</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="text-xs text-muted-foreground">MP4</span>
</DropdownMenuItem>
)
})}
{data.media?.original?.key && (
<>
<DropdownMenuSeparator />
@@ -182,4 +182,126 @@ describe('VideoViewer', () => {
}),
)
})
it('auto-selects HDR proxy when display supports HDR (dynamic-range: high)', () => {
const originalMatchMedia = window.matchMedia
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: query === '(dynamic-range: high)',
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
const hdrVideo: AssetInfo = {
id: 'video-hdr',
name: 'video-hdr.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p.mp4',
width: 1920,
height: 1080,
hdr: false,
},
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p-hdr.mp4',
width: 1920,
height: 1080,
hdr: true,
},
],
},
} as unknown as AssetInfo
render(<VideoViewer file={hdrVideo} />)
expect(videojsMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
sources: [
{
src: 'https://cdn.example.com/video-1080p-hdr.mp4',
type: 'video/mp4',
},
],
}),
)
window.matchMedia = originalMatchMedia
})
it('auto-selects SDR proxy when display does not support HDR', () => {
const originalMatchMedia = window.matchMedia
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
const hdrVideo: AssetInfo = {
id: 'video-sdr-fallback',
name: 'video-sdr-fallback.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p.mp4',
width: 1920,
height: 1080,
hdr: false,
},
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p-hdr.mp4',
width: 1920,
height: 1080,
hdr: true,
},
],
},
} as unknown as AssetInfo
render(<VideoViewer file={hdrVideo} />)
expect(videojsMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
sources: [
{
src: 'https://cdn.example.com/video-1080p.mp4',
type: 'video/mp4',
},
],
}),
)
window.matchMedia = originalMatchMedia
})
})
@@ -54,17 +54,30 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
// We use a container ref to manually append the video element
const videoContainerRef = useRef<HTMLDivElement>(null)
// Logic to select best resolution based on screen size
// Logic to select best resolution based on screen size and dynamic range
const getInitialResolution = (): DisplayTranscode | null => {
if (resolutions.length === 0) return null
if (typeof window === 'undefined') return resolutions[0]
const prefersHdr =
typeof window.matchMedia === 'function' &&
window.matchMedia('(dynamic-range: high)').matches
const hasHdr = resolutions.some((r) => r.hdr)
const hasSdr = resolutions.some((r) => !r.hdr)
let candidateResolutions = resolutions
if (prefersHdr && hasHdr) {
candidateResolutions = resolutions.filter((r) => r.hdr)
} else if (!prefersHdr && hasSdr) {
candidateResolutions = resolutions.filter((r) => !r.hdr)
}
// Use device pixel ratio for high DPI screens
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
// 1. Sort by width ascending
const sortedResolutions = [...resolutions].sort((a, b) => {
const sortedResolutions = [...candidateResolutions].sort((a, b) => {
const wA = a.width ?? 0
const wB = b.width ?? 0
return wA - wB
@@ -93,6 +106,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
showFrames: false,
currentResolution: initialRes?.resolution ?? '',
currentSrc: initialRes?.url ?? '',
isCurrentHdr: initialRes?.hdr ?? false,
})
const containerRef = useRef<HTMLDivElement>(null)
const rootRef = useRef<HTMLDivElement>(null)
@@ -140,6 +154,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
duration: data.media?.metadata?.duration || 0,
currentResolution: res?.resolution ?? '',
currentSrc: res?.url ?? '',
isCurrentHdr: res?.hdr ?? false,
}))
setHasManuallyZoomed(false)
setIsPlayerReady(false)
@@ -284,8 +299,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
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'
// Keep it in DOM, enable visible rendering
videoElement.style.pointerEvents = 'none'
// Append to our container
@@ -600,6 +614,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
...prev,
currentResolution: res.resolution,
currentSrc: res.url,
isCurrentHdr: res.hdr ?? false,
}))
player.src({ type: 'video/mp4', src: res.url })
@@ -758,8 +773,31 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
data-vjs-player
data-testid="video-area"
>
{/* Hidden VideoJS container */}
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{/* Native Video Layer (Hardware-accelerated, full HDR EDR) */}
{!isAudio && (
<div
className="absolute pointer-events-none"
style={{
left: 0,
top: 0,
width: vidW,
height: vidH,
transform: `translate(${pan.x}px, ${pan.y}px) scale(${scale})`,
transformOrigin: '0 0',
}}
>
<div
ref={videoContainerRef}
className="w-full h-full [&_.video-js]:!w-full [&_.video-js]:!h-full [&_video]:!w-full [&_video]:!h-full [&_video]:!block [&_video]:!object-contain"
/>
</div>
)}
{isAudio && (
<div
ref={videoContainerRef}
className="absolute inset-0 pointer-events-none opacity-0"
/>
)}
{isAudio ? (
<div className="flex flex-col items-center justify-center text-muted-foreground w-full h-full pointer-events-none select-none">
@@ -771,8 +809,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
/>
</div>
) : (
/* Drawing Canvas (Visible) */
videoHtmlEl &&
/* Drawing Canvas (Transparent Overlay for annotations) */
containerSize.width > 0 && (
<DrawingCanvas
width={containerSize.width}
@@ -781,7 +818,6 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
width: vidW,
height: vidH,
}}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={pan}