Files
shared/media-webui/src/lib/features/VideoPage.svelte
T

1059 lines
39 KiB
Svelte
Raw Normal View History

<script lang="ts">
import { ArrowLeft, Film, Maximize2, Minimize2, Pause, Play, Wifi, WifiOff } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
type SyncMode = 'none' | 'local' | 'master' | 'slave'
interface MediaInfo {
id: string
filename: string
title?: string | null
relPath?: string | null
mediaType?: string
hasFunscript?: boolean
funscriptActionCount?: number | null
funscriptAvgSpeed?: number | null
isVr?: boolean
vrFov?: number | null
vrStereo?: string | null
vrProjection?: string | null
width?: number | null
height?: number | null
durationMs?: number | null
sizeBytes?: number | string | null
modifiedMs?: number | string | null
}
interface FunscriptAction {
at: number
pos: number
}
interface FunscriptData {
version?: string
inverted?: boolean
range?: number
actions: FunscriptAction[]
}
interface SyncClient {
clientId: string
userAgent?: string
ipAddress?: string
uiView?: string
uiMediaId?: string | null
remoteControlEnabled?: boolean
controlOwnerClientId?: string | null
}
interface SyncState {
sessionId?: string
mediaId?: string | null
timeMs?: number
paused?: boolean
fps?: number
frame?: number
fromClientId?: string
toClientId?: string
updatedAt?: string
playAt?: string
playAtLocalMs?: number
capturedAtLocalMs?: number
fullscreen?: boolean
goToGrid?: boolean
}
interface SyncMessage {
type?: string
state?: SyncState
clients?: SyncClient[]
ok?: boolean
action?: string
reason?: string
}
let { id }: { id: string } = $props()
let info = $state<MediaInfo | null>(null)
let funscript = $state<FunscriptData | null>(null)
let loading = $state(true)
let funscriptLoading = $state(false)
let error = $state('')
let videoError = $state('')
let videoElement = $state<HTMLVideoElement | null>(null)
let playerFrame = $state<HTMLDivElement | null>(null)
let videoTime = $state(0)
let videoDuration = $state(0)
let videoPlaying = $state(false)
let isFullscreen = $state(false)
let remoteFullscreen = $state(false)
let syncMode = $state<SyncMode>('none')
let syncConnected = $state(false)
let syncError = $state('')
let clientId = $state('')
let clients = $state<SyncClient[]>([])
let controlTargets = $state<string[]>([])
let remoteDriverId = $state('')
let lastRemoteSync = $state<SyncState | null>(null)
let syncSocket: WebSocket | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let scheduledPlayTimer: ReturnType<typeof setTimeout> | null = null
let reconnectDelay = 1000
let disposed = false
let lastSyncSentAt = 0
let suppressPlaybackUntil = 0
const sessionId = 'default'
const hasFunscript = $derived(Boolean(info?.hasFunscript || funscript?.actions?.length))
const effectiveDurationMs = $derived(
Number(info?.durationMs) > 0
? Number(info?.durationMs)
: videoDuration > 0
? videoDuration * 1000
: funscript?.actions?.[funscript.actions.length - 1]?.at || 0,
)
const fullscreenActive = $derived(isFullscreen || remoteFullscreen)
const otherClients = $derived(clients.filter((client) => client.clientId !== clientId))
const selectedMaster = $derived(clients.find((client) => client.clientId === remoteDriverId) || null)
const syncStateLabel = $derived(lastRemoteSync?.paused ? 'Paused' : lastRemoteSync ? 'Playing' : 'Waiting')
const funscriptStats = $derived(getFunscriptStats(info, funscript))
const graphPath = $derived(getGraphPath(funscript?.actions || [], effectiveDurationMs))
const graphPoint = $derived(getGraphPoint(funscript?.actions || [], videoTime * 1000, effectiveDurationMs))
const windowGraphPath = $derived(getWindowGraphPath(funscript?.actions || [], videoTime * 1000, effectiveDurationMs))
const windowGraphPoint = $derived(
getWindowGraphPoint(funscript?.actions || [], videoTime * 1000, effectiveDurationMs),
)
function mediaEndpoint(suffix: string) {
if (suffix === 'stream') {
return `/api/media/stream?mediaKey=${encodeURIComponent(id)}`
}
return `/api/media/${encodeURIComponent(id)}/${suffix}`
}
function formatDuration(ms: number | null | undefined) {
const value = Number(ms)
if (!Number.isFinite(value) || value <= 0) return 'Not available'
const total = Math.round(value / 1000)
const hours = Math.floor(total / 3600)
const minutes = Math.floor((total % 3600) / 60)
const seconds = total % 60
if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
return `${minutes}:${String(seconds).padStart(2, '0')}`
}
function formatBytes(value: number | string | null | undefined) {
const bytes = Number(value)
if (!Number.isFinite(bytes) || bytes < 0) return 'Not available'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let size = bytes
let unit = 0
while (size >= 1024 && unit < units.length - 1) {
size /= 1024
unit += 1
}
return `${size.toFixed(unit === 0 ? 0 : size >= 10 ? 1 : 2)} ${units[unit]}`
}
function formatDate(value: number | string | null | undefined) {
const timestamp = Number(value)
if (!Number.isFinite(timestamp) || timestamp <= 0) return 'Not available'
return new Date(timestamp).toLocaleString()
}
function formatFolder(value: string | null | undefined) {
const path = String(value || '')
const folder = path.replace(/[/\\][^/\\]+$/, '')
return folder || 'Root'
}
function resolutionLabel(height: number | null | undefined) {
const value = Number(height)
if (!Number.isFinite(value) || value <= 0) return ''
if (value >= 4320) return '8K'
if (value >= 2160) return '4K'
if (value >= 1440) return '1440p'
if (value >= 1080) return '1080p'
if (value >= 720) return '720p'
if (value >= 480) return '480p'
return `${Math.round(value)}p`
}
function formatResolution(value: MediaInfo) {
const width = Number(value.width)
const height = Number(value.height)
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
return 'Not available'
}
const label = resolutionLabel(height)
return label ? `${width} × ${height} (${label})` : `${width} × ${height}`
}
function formatVr(value: MediaInfo) {
if (!value.isVr) return 'No'
const details = [
value.vrFov ? `${value.vrFov}°` : '',
value.vrStereo ? value.vrStereo.toUpperCase() : '',
value.vrProjection ? value.vrProjection : '',
].filter(Boolean)
return details.length ? `Yes (${details.join(' · ')})` : 'Yes'
}
function formatSpeed(value: number | null | undefined) {
if (value == null) return 'Not available'
const speed = Number(value)
if (!Number.isFinite(speed) || speed < 0) return 'Not available'
return `${speed.toFixed(speed >= 10 ? 0 : 1)}%/s`
}
function getFunscriptStats(media: MediaInfo | null, data: FunscriptData | null) {
const actions = data?.actions || []
let count = media?.funscriptActionCount == null ? Number.NaN : Number(media.funscriptActionCount)
let speed = media?.funscriptAvgSpeed == null ? Number.NaN : Number(media.funscriptAvgSpeed)
if (!Number.isFinite(count) || count <= 0) count = actions.length
if (!Number.isFinite(speed) || speed < 0) {
let distance = 0
let elapsed = 0
for (let index = 1; index < actions.length; index += 1) {
const previous = actions[index - 1]
const current = actions[index]
const deltaTime = current.at - previous.at
if (deltaTime <= 0) continue
distance += Math.abs(current.pos - previous.pos)
elapsed += deltaTime
}
speed = elapsed > 0 ? (distance / elapsed) * 1000 : Number.NaN
}
return {
count: Number.isFinite(count) && count > 0 ? Math.round(count) : 0,
speed: Number.isFinite(speed) && speed >= 0 ? speed : null,
}
}
function getGraphPath(actions: FunscriptAction[], durationMs: number) {
if (!actions.length) return ''
const end = Math.max(durationMs, actions[actions.length - 1].at, 1)
const stride = Math.max(1, Math.ceil(actions.length / 1600))
const points: FunscriptAction[] = []
for (let index = 0; index < actions.length; index += stride) points.push(actions[index])
const last = actions[actions.length - 1]
if (points[points.length - 1] !== last) points.push(last)
return points
.map((action, index) => {
const x = Math.max(0, Math.min(100, (action.at / end) * 100))
const y = 100 - Math.max(0, Math.min(100, action.pos))
return `${index === 0 ? 'M' : 'L'} ${x.toFixed(3)} ${y.toFixed(3)}`
})
.join(' ')
}
function getGraphPoint(actions: FunscriptAction[], timeMs: number, durationMs: number) {
if (!actions.length) return null
const end = Math.max(durationMs, actions[actions.length - 1].at, 1)
const target = Math.max(0, Math.min(end, timeMs))
const position = getActionPosition(actions, target)
return {
x: Math.max(0, Math.min(100, (target / end) * 100)),
y: 100 - Math.max(0, Math.min(100, position)),
}
}
function getActionPosition(actions: FunscriptAction[], target: number) {
let previous = actions[0]
let current = actions[actions.length - 1]
for (const action of actions) {
if (action.at >= target) {
current = action
break
}
previous = action
}
const span = current.at - previous.at
const ratio = span > 0 ? (target - previous.at) / span : 0
return previous.pos + (current.pos - previous.pos) * Math.max(0, Math.min(1, ratio))
}
function getWindowBounds(timeMs: number, durationMs: number) {
const halfWindow = 5000
const duration = Math.max(durationMs, timeMs, 1)
const center = Math.max(0, Math.min(duration, timeMs))
let start = Math.max(0, center - halfWindow)
let end = Math.min(duration, start + halfWindow * 2)
if (end - start < halfWindow * 2) start = Math.max(0, end - halfWindow * 2)
return { start, end: Math.max(start + 1, end) }
}
function getWindowGraphPath(actions: FunscriptAction[], timeMs: number, durationMs: number) {
if (!actions.length) return ''
const { start, end } = getWindowBounds(timeMs, durationMs)
const visible = actions.filter((action) => action.at >= start && action.at <= end)
const points = visible.length
? visible
: [
actions.reduce((closest, action) =>
Math.abs(action.at - timeMs) < Math.abs(closest.at - timeMs) ? action : closest,
),
]
return points
.map((action, index) => {
const x = Math.max(0, Math.min(100, ((action.at - start) / (end - start)) * 100))
const y = 100 - Math.max(0, Math.min(100, action.pos))
return `${index === 0 ? 'M' : 'L'} ${x.toFixed(3)} ${y.toFixed(3)}`
})
.join(' ')
}
function getWindowGraphPoint(actions: FunscriptAction[], timeMs: number, durationMs: number) {
if (!actions.length) return null
const { start, end } = getWindowBounds(timeMs, durationMs)
const absoluteX = Math.max(0, Math.min(100, ((timeMs - start) / (end - start)) * 100))
return { x: absoluteX, y: 100 - Math.max(0, Math.min(100, getActionPosition(actions, timeMs))) }
}
async function loadData() {
loading = true
error = ''
videoError = ''
try {
const result = await get<MediaInfo>(mediaEndpoint('fileinfo'))
if (result.mediaType && result.mediaType !== 'video') {
throw new Error('This media item is not a video.')
}
info = result
funscriptLoading = true
try {
// The metadata flag can lag behind sidecar discovery, so ask the
// funscript endpoint directly as well. A 404 simply means no script.
funscript = await get<FunscriptData>(mediaEndpoint('funscript'))
} catch {
funscript = null
} finally {
funscriptLoading = false
}
} catch (cause) {
error = cause instanceof Error ? cause.message : 'Unable to load this video.'
} finally {
loading = false
}
}
function getStoredClientId() {
try {
const existing = window.localStorage.getItem('mvClientId')
if (existing) return existing
const created = `web-${Math.random().toString(16).slice(2)}`
window.localStorage.setItem('mvClientId', created)
return created
} catch {
return `web-${Math.random().toString(16).slice(2)}`
}
}
function loadStoredSyncMode() {
try {
const raw = window.localStorage.getItem('mvPrefs')
const saved = raw ? (JSON.parse(raw) as { controlMode?: string }) : null
const value = saved?.controlMode === 'remote' ? 'slave' : saved?.controlMode
if (value === 'none' || value === 'local' || value === 'master' || value === 'slave') {
syncMode = value
}
} catch {
// Ignore unavailable or malformed preferences.
}
}
function saveStoredSyncMode() {
try {
const raw = window.localStorage.getItem('mvPrefs')
const saved = raw ? (JSON.parse(raw) as Record<string, unknown>) : {}
saved.controlMode = syncMode
window.localStorage.setItem('mvPrefs', JSON.stringify(saved))
} catch {
// Ignore unavailable storage.
}
}
function syncUrl() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
return `${protocol}//${window.location.host}/ws`
}
function sendSocketMessage(message: Record<string, unknown>) {
if (!syncSocket || syncSocket.readyState !== WebSocket.OPEN) return false
syncSocket.send(JSON.stringify(message))
return true
}
function sendClientStatus() {
sendSocketMessage({
type: 'client:status',
clientId,
sessionId,
uiView: 'player',
mediaId: id,
remoteControlEnabled: syncMode === 'slave',
})
}
function connectSync() {
if (
disposed ||
(syncSocket && (syncSocket.readyState === WebSocket.OPEN || syncSocket.readyState === WebSocket.CONNECTING))
) {
return
}
let socket: WebSocket
try {
socket = new WebSocket(syncUrl())
} catch {
syncConnected = false
scheduleReconnect()
return
}
syncSocket = socket
socket.addEventListener('open', () => {
if (syncSocket !== socket) return
syncConnected = true
syncError = ''
reconnectDelay = 1000
sendSocketMessage({ type: 'sync:hello', clientId, sessionId })
sendClientStatus()
})
socket.addEventListener('message', (event) => {
let message: SyncMessage
try {
message = JSON.parse(String(event.data)) as SyncMessage
} catch {
return
}
handleSyncMessage(message)
})
socket.addEventListener('close', () => {
if (syncSocket !== socket) return
syncSocket = null
syncConnected = false
if (!disposed) scheduleReconnect()
})
socket.addEventListener('error', () => {
if (syncSocket === socket) syncError = 'Connection error; retrying.'
})
}
function scheduleReconnect() {
if (disposed || reconnectTimer) return
const delay = reconnectDelay
reconnectDelay = Math.min(30000, reconnectDelay * 2)
reconnectTimer = setTimeout(() => {
reconnectTimer = null
connectSync()
}, delay)
}
function handleSyncMessage(message: SyncMessage) {
if (message.type === 'control:ack') {
if (message.ok === false)
syncError = `Control ${message.action || 'update'} failed: ${message.reason || 'unavailable'}`
else syncError = ''
return
}
if (message.type !== 'sync:state' || !message.state) return
clients = Array.isArray(message.clients)
? message.clients.filter((client) => client && typeof client.clientId === 'string')
: []
if (syncMode === 'slave') {
const ownClient = clients.find((client) => client.clientId === clientId)
remoteDriverId = ownClient?.controlOwnerClientId ? String(ownClient.controlOwnerClientId) : ''
}
lastRemoteSync = message.state
if (syncMode === 'slave') void applyRemoteSync(message.state)
}
function endpointLabel(client: SyncClient) {
const value = client.clientId
const separator = value.indexOf('-')
const suffix = separator >= 0 ? value.slice(separator + 1, separator + 6) : value.slice(0, 5)
if (value.startsWith('desktop-')) return `Desktop (${suffix})`
if (value.startsWith('mobile-')) return `Mobile (${suffix})`
if (value.startsWith('web-')) return `Browser (${suffix})`
return value.length > 22 ? `${value.slice(0, 19)}...` : value
}
function endpointDetails(client: SyncClient) {
return [client.uiView, client.ipAddress].filter(Boolean).join(' · ')
}
function sendControlClaim(targetClientId: string) {
sendSocketMessage({ type: 'control:claim', clientId, sessionId, targetClientId })
}
function sendControlRelease(targetClientId: string) {
sendSocketMessage({ type: 'control:release', clientId, sessionId, targetClientId })
}
function setSyncMode(value: string) {
const next: SyncMode = value === 'local' || value === 'master' || value === 'slave' ? value : 'none'
if (syncMode === 'master' && next !== 'master') {
for (const target of controlTargets) sendControlRelease(target)
}
syncMode = next
if (next !== 'master') controlTargets = []
if (next !== 'slave') {
remoteDriverId = ''
remoteFullscreen = false
}
syncError = ''
saveStoredSyncMode()
sendClientStatus()
if (next === 'slave' && lastRemoteSync) void applyRemoteSync(lastRemoteSync)
}
function handleSyncModeChange(event: Event) {
setSyncMode((event.currentTarget as HTMLSelectElement).value)
}
function toggleControlTarget(targetClientId: string, checked: boolean) {
if (syncMode !== 'master') return
if (checked) {
if (!controlTargets.includes(targetClientId)) controlTargets = [...controlTargets, targetClientId]
sendControlClaim(targetClientId)
} else {
controlTargets = controlTargets.filter((target) => target !== targetClientId)
sendControlRelease(targetClientId)
}
}
function isSuppressed() {
return Date.now() < suppressPlaybackUntil
}
function sendPlayback(force = false, extras: Partial<SyncState> = {}) {
if (syncMode !== 'master' || !syncConnected || !clientId) return
const now = Date.now()
if (!force && now - lastSyncSentAt < 200) return
lastSyncSentAt = now
const currentTimeMs = Math.max(0, Math.round((videoElement?.currentTime || 0) * 1000))
const paused = videoElement?.paused ?? true
const payload: Record<string, unknown> = {
type: 'sync:update',
sessionId,
clientId,
mediaId: id,
timeMs: currentTimeMs,
paused,
fps: 30,
frame: Math.max(0, Math.floor((currentTimeMs / 1000) * 30)),
capturedAtLocalMs: now,
...extras,
}
const targets = controlTargets.filter((target) => target.trim())
if (targets.length) {
for (const target of targets) sendSocketMessage({ ...payload, toClientId: target })
} else {
sendSocketMessage(payload)
}
}
function handleVideoPlay() {
videoPlaying = true
if (!isSuppressed()) sendPlayback(true)
}
function handleVideoPause() {
videoPlaying = false
if (!isSuppressed()) sendPlayback(true)
}
function handleVideoTimeUpdate() {
if (!videoElement) return
videoTime = videoElement.currentTime || 0
videoDuration = Number.isFinite(videoElement.duration) ? videoElement.duration : videoDuration
if (!isSuppressed()) sendPlayback(false)
}
function handleVideoSeeked() {
if (!videoElement || isSuppressed()) return
videoTime = videoElement.currentTime || 0
sendPlayback(true)
}
function handleVideoLoadedMetadata() {
if (!videoElement) return
videoDuration = Number.isFinite(videoElement.duration) ? videoElement.duration : 0
if (syncMode === 'slave' && lastRemoteSync) {
void applyRemoteSync(lastRemoteSync)
} else if (syncMode !== 'slave') {
videoElement.play().catch(() => {
const wasMuted = videoElement?.muted ?? false
if (!videoElement) return
videoElement.muted = true
videoElement.play().catch(() => {
if (videoElement) videoElement.muted = wasMuted
})
})
}
}
function handleVideoError() {
videoError = 'The video stream could not be loaded.'
}
function clearScheduledPlay() {
if (scheduledPlayTimer) clearTimeout(scheduledPlayTimer)
scheduledPlayTimer = null
}
function scheduleRemotePlay(timestamp: number) {
clearScheduledPlay()
const delay = Math.max(0, timestamp - Date.now())
scheduledPlayTimer = setTimeout(() => {
scheduledPlayTimer = null
if (syncMode !== 'slave' || !videoElement) return
suppressPlaybackUntil = Date.now() + 1200
void videoElement.play().catch(() => undefined)
}, delay)
}
function remotePlayAt(remote: SyncState) {
const fromServer = remote.playAt ? Date.parse(remote.playAt) : Number.NaN
const fromSender = Number(remote.playAtLocalMs)
if (
Number.isFinite(fromSender) &&
fromSender > 0 &&
Number.isFinite(fromServer) &&
Math.abs(fromSender - fromServer) <= 100
) {
return fromSender
}
return Number.isFinite(fromServer) ? fromServer : Number.NaN
}
async function applyRemoteSync(remote: SyncState) {
if (syncMode !== 'slave' || !remote || remote.fromClientId === clientId) return
const driverId = String(remote.fromClientId || '')
const targeted = String(remote.toClientId || '') === clientId
const fromMaster = Boolean(remoteDriverId && driverId === remoteDriverId)
if (!targeted && !fromMaster) return
if (remote.goToGrid) {
window.location.assign('/')
return
}
if (remote.mediaId && remote.mediaId !== id) {
window.location.assign(`/video/${encodeURIComponent(remote.mediaId)}`)
return
}
if (typeof remote.fullscreen === 'boolean') {
remoteFullscreen = remote.fullscreen
if (!remote.fullscreen && document.fullscreenElement) {
await document.exitFullscreen().catch(() => undefined)
}
}
const video = videoElement
if (!video) return
const timeMs = Math.max(0, Number(remote.timeMs) || 0)
const updatedAt = remote.updatedAt ? Date.parse(remote.updatedAt) : Number.NaN
const driftMs = !remote.paused && Number.isFinite(updatedAt) ? Math.max(0, Date.now() - updatedAt) : 0
const targetSeconds = (timeMs + driftMs) / 1000
const playAt = remote.paused ? Number.NaN : remotePlayAt(remote)
suppressPlaybackUntil = Date.now() + 1400
clearScheduledPlay()
try {
if (!Number.isFinite(video.currentTime) || Math.abs(video.currentTime - targetSeconds) > 0.65) {
video.currentTime = targetSeconds
}
} catch {
// The element may not have metadata yet; loadedmetadata retries this state.
}
if (Number.isFinite(playAt) && playAt > Date.now() + 10) {
video.pause()
scheduleRemotePlay(playAt)
} else if (remote.paused) {
video.pause()
} else {
await video.play().catch(() => undefined)
}
}
async function toggleFullscreen() {
if (document.fullscreenElement) {
await document.exitFullscreen().catch(() => undefined)
return
}
if (playerFrame) await playerFrame.requestFullscreen().catch(() => undefined)
}
function handleFullscreenChange() {
isFullscreen = Boolean(document.fullscreenElement)
if (syncMode === 'master') {
sendPlayback(true, { fullscreen: isFullscreen })
}
}
onMount(() => {
disposed = false
clientId = getStoredClientId()
loadStoredSyncMode()
void loadData()
connectSync()
return () => {
disposed = true
if (reconnectTimer) clearTimeout(reconnectTimer)
reconnectTimer = null
clearScheduledPlay()
syncSocket?.close()
syncSocket = null
}
})
</script>
<svelte:window onfullscreenchange={handleFullscreenChange} />
{#snippet infoRow(label: string, value: string)}
<div class="grid grid-cols-[5.5rem_minmax(0,1fr)] items-start gap-3 text-sm">
<span class="text-muted-fg">{label}</span>
<span class="break-words text-right text-fg">{value}</span>
</div>
{/snippet}
<div class="mb-5 flex justify-end">
<Button variant="secondary" size="sm" onclick={() => window.location.assign('/')}
><ArrowLeft class="size-4" />Library</Button
>
</div>
<div class="space-y-5">
{#if loading}
<div class="media-shimmer h-96 rounded-lg border border-border"></div>
{:else if error}
<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{error}</div>
{:else if info}
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
<div class="min-w-0 space-y-4">
<Card class="overflow-hidden p-0">
<div
bind:this={playerFrame}
class={`relative aspect-video overflow-hidden bg-black ${remoteFullscreen ? 'fixed inset-0 z-50 h-screen w-screen rounded-none' : ''}`}
>
<video
bind:this={videoElement}
class="absolute inset-0 h-full w-full object-contain"
src={mediaEndpoint('stream')}
preload="auto"
playsinline
autoplay={syncMode !== 'slave'}
controls={syncMode !== 'slave'}
onplay={handleVideoPlay}
onpause={handleVideoPause}
ontimeupdate={handleVideoTimeUpdate}
onseeked={handleVideoSeeked}
onloadedmetadata={handleVideoLoadedMetadata}
onerror={handleVideoError}
>
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT" />
</video>
<div class="absolute left-3 top-3 z-10 flex flex-wrap gap-2">
{#if info.isVr}<Badge tone="primary">VR</Badge>{/if}
{#if hasFunscript}<Badge tone="success">Funscript</Badge>{/if}
{#if syncMode === 'slave'}<Badge tone="warning">Slave</Badge>{/if}
</div>
{#if graphPath}
<div
class="pointer-events-none absolute bottom-12 left-3 right-3 z-10 rounded-md border border-white/20 bg-black/65 p-1.5"
>
<div class="mb-1 text-[10px] font-medium uppercase tracking-wide text-white/70">Funscript</div>
<svg
viewBox="0 0 100 100"
preserveAspectRatio="none"
class="h-14 w-full"
role="img"
aria-label="Live funscript graph"
>
<path
d={graphPath}
fill="none"
stroke="var(--color-primary)"
stroke-width="1.5"
vector-effect="non-scaling-stroke"
/>
{#if graphPoint}<circle
cx={graphPoint.x}
cy={graphPoint.y}
r="2"
fill="var(--color-success)"
vector-effect="non-scaling-stroke"
/>{/if}
</svg>
</div>
{/if}
<div class="absolute right-3 top-3 z-10">
<Button
variant="ghost"
size="icon"
class="bg-black/60 text-white hover:bg-black/80"
aria-label={fullscreenActive ? 'Exit fullscreen' : 'Enter fullscreen'}
title={fullscreenActive ? 'Exit fullscreen' : 'Enter fullscreen'}
onclick={() => void toggleFullscreen()}
>
{#if fullscreenActive}<Minimize2 class="size-4" />{:else}<Maximize2 class="size-4" />{/if}
</Button>
</div>
{#if videoError}
<div class="absolute inset-x-4 bottom-16 rounded-md bg-black/75 px-3 py-2 text-center text-sm text-white">
{videoError}
</div>
{/if}
</div>
<div class="flex flex-wrap items-center justify-between gap-3 border-t border-border px-4 py-3">
<div class="flex min-w-0 items-center gap-2 text-sm text-muted-fg">
{#if videoPlaying}<Play class="size-4 text-success" />{:else}<Pause class="size-4" />{/if}
<span>{formatDuration(videoTime * 1000)} / {formatDuration(effectiveDurationMs)}</span>
</div>
<span class="truncate text-xs text-muted-fg">{info.filename}</span>
</div>
</Card>
<Card class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 class="text-sm font-medium text-fg">Funscript Info</h2>
<p class="mt-1 text-xs text-muted-fg">Action data and playback position for this video.</p>
</div>
{#if hasFunscript}<Badge tone="success">Available</Badge>{:else}<Badge tone="neutral">None</Badge>{/if}
</div>
{#if hasFunscript}
<div class="grid gap-2 sm:grid-cols-2">
{@render infoRow(
'Stats',
funscriptStats.count
? `${funscriptStats.count} actions · ${formatSpeed(funscriptStats.speed)}`
: 'Not available',
)}
{@render infoRow('Version', funscript?.version || 'Not specified')}
{@render infoRow('Range', funscript?.range != null ? String(funscript.range) : 'Not specified')}
{@render infoRow(
'Inverted',
funscript?.inverted == null ? 'Not specified' : funscript.inverted ? 'Yes' : 'No',
)}
{#if funscript?.actions?.length}
{@render infoRow(
'Coverage',
`${formatDuration(funscript.actions[0].at)} – ${formatDuration(funscript.actions[funscript.actions.length - 1].at)}`,
)}
{/if}
</div>
{#if funscriptLoading && !graphPath}
<p class="text-sm text-muted-fg">Loading action data...</p>
{:else if graphPath}
<div class="grid gap-3 lg:grid-cols-2">
<div>
<div class="mb-2 flex items-center justify-between text-xs text-muted-fg">
<span>Overview</span><span>{formatDuration(effectiveDurationMs)}</span>
</div>
<svg
viewBox="0 0 100 100"
preserveAspectRatio="none"
class="h-32 w-full rounded-md border border-border bg-bg"
role="img"
aria-label="Funscript overview graph"
>
<path
d="M 0 25 H 100 M 0 50 H 100 M 0 75 H 100"
stroke="currentColor"
stroke-opacity="0.12"
vector-effect="non-scaling-stroke"
/>
<path
d={graphPath}
fill="none"
stroke="var(--color-primary)"
stroke-width="1.5"
vector-effect="non-scaling-stroke"
/>
{#if graphPoint}<circle
cx={graphPoint.x}
cy={graphPoint.y}
r="2"
fill="var(--color-success)"
vector-effect="non-scaling-stroke"
/>{/if}
</svg>
<div class="mt-1 flex justify-between text-[11px] text-muted-fg">
<span>0:00</span><span>Position {formatDuration(videoTime * 1000)}</span><span
>{formatDuration(effectiveDurationMs)}</span
>
</div>
</div>
<div>
<div class="mb-2 flex items-center justify-between text-xs text-muted-fg">
<span>Current 10-second window</span><span>{formatDuration(videoTime * 1000)}</span>
</div>
<svg
viewBox="0 0 100 100"
preserveAspectRatio="none"
class="h-32 w-full rounded-md border border-border bg-bg"
role="img"
aria-label="Current funscript graph"
>
<path
d="M 0 25 H 100 M 0 50 H 100 M 0 75 H 100"
stroke="currentColor"
stroke-opacity="0.12"
vector-effect="non-scaling-stroke"
/>
<path
d={windowGraphPath}
fill="none"
stroke="var(--color-primary)"
stroke-width="1.5"
vector-effect="non-scaling-stroke"
/>
{#if windowGraphPoint}<circle
cx={windowGraphPoint.x}
cy={windowGraphPoint.y}
r="2"
fill="var(--color-success)"
vector-effect="non-scaling-stroke"
/>{/if}
</svg>
<div class="mt-1 flex justify-between text-[11px] text-muted-fg">
<span>-5s</span><span>Now</span><span>+5s</span>
</div>
</div>
</div>
{:else}
<p class="text-sm text-muted-fg">Action data is not available for this funscript.</p>
{/if}
{:else}
<p class="text-sm text-muted-fg">No funscript is associated with this video.</p>
{/if}
</Card>
</div>
<aside class="space-y-4">
<Card class="space-y-4">
<div class="flex items-center justify-between gap-3">
<div>
<h2 class="text-sm font-medium text-fg">Sync Info</h2>
<p class="mt-1 text-xs text-muted-fg">Connect this player to other MediaViewer endpoints.</p>
</div>
{#if syncConnected}<Badge tone="success"><Wifi class="mr-1 size-3" />Connected</Badge>{:else}<Badge
tone="warning"><WifiOff class="mr-1 size-3" />Disconnected</Badge
>{/if}
</div>
<label class="grid gap-1.5 text-xs font-medium text-muted-fg">
Control mode
<select
value={syncMode}
onchange={handleSyncModeChange}
class="h-9 rounded-md border border-border bg-bg px-3 text-sm font-normal text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<option value="none">None</option>
<option value="local">Local</option>
<option value="master">Master</option>
<option value="slave">Slave</option>
</select>
</label>
{@render infoRow('Client', clientId || 'Connecting...')}
{@render infoRow('Session', sessionId)}
{@render infoRow('State', syncStateLabel)}
{#if syncMode === 'slave'}
{@render infoRow('Master', selectedMaster ? endpointLabel(selectedMaster) : remoteDriverId || 'Waiting...')}
{/if}
{#if syncMode === 'none'}
<p class="rounded-md border border-border bg-bg px-3 py-2 text-xs text-muted-fg">Sync is disabled.</p>
{:else if syncMode === 'local'}
<p class="rounded-md border border-border bg-bg px-3 py-2 text-xs text-muted-fg">
Playback stays local; this endpoint will not follow or drive another player.
</p>
{:else if syncMode === 'master'}
<div class="space-y-2 border-t border-border pt-3">
<div class="flex items-center justify-between gap-3">
<p class="text-xs font-medium text-fg">Connected endpoints</p>
<span class="text-xs text-muted-fg">{controlTargets.length} selected</span>
</div>
{#if otherClients.length}
<div class="space-y-1">
{#each otherClients as client (client.clientId)}
<label
class={`flex items-start gap-2 rounded-md border border-transparent p-2 ${client.remoteControlEnabled ? 'cursor-pointer hover:border-border hover:bg-bg' : 'opacity-55'}`}
>
<input
class="mt-1 accent-[var(--color-primary)]"
type="checkbox"
checked={controlTargets.includes(client.clientId)}
disabled={!client.remoteControlEnabled || !syncConnected}
onchange={(event) =>
toggleControlTarget(client.clientId, (event.currentTarget as HTMLInputElement).checked)}
/>
<span class="min-w-0">
<span class="block truncate text-xs font-medium text-fg">{endpointLabel(client)}</span>
<span class="block truncate text-[11px] text-muted-fg"
>{client.remoteControlEnabled ? 'Slave-ready' : 'Not accepting control'}{endpointDetails(
client,
)
? ` · ${endpointDetails(client)}`
: ''}</span
>
</span>
</label>
{/each}
</div>
{:else}
<p class="text-xs text-muted-fg">No other endpoints are connected.</p>
{/if}
</div>
{:else}
<div class="border-t border-border pt-3">
<p class="text-xs text-muted-fg">Waiting for a master endpoint to claim this player.</p>
</div>
{/if}
{#if syncError}<p class="rounded-md border border-danger/30 bg-danger/10 px-3 py-2 text-xs text-danger">
{syncError}
</p>{/if}
</Card>
<Card class="space-y-4">
<div class="flex items-center justify-between gap-3">
<div>
<h2 class="text-sm font-medium text-fg">Video Info</h2>
<p class="mt-1 text-xs text-muted-fg">Metadata previously shown by the player.</p>
</div>
<Film class="size-5 text-primary" />
</div>
<div class="space-y-2">
{@render infoRow('Title', info.title || 'Not specified')}
{@render infoRow('Filename', info.filename)}
{@render infoRow('Folder', formatFolder(info.relPath))}
{@render infoRow('Type', info.mediaType || 'video')}
{@render infoRow('Duration', formatDuration(effectiveDurationMs))}
{@render infoRow('Resolution', formatResolution(info))}
{@render infoRow('VR', formatVr(info))}
{@render infoRow('Size', formatBytes(info.sizeBytes))}
{@render infoRow('Modified', formatDate(info.modifiedMs))}
</div>
</Card>
</aside>
</div>
{/if}
</div>