LD-KickWatch/src/components/StreamVideo.tsx

1078 lines
40 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useEffect, useRef, useState } from 'react';
import {
AlertTriangle,
Clock,
Loader2,
Maximize2,
MessageSquare,
Pause,
Play,
Radio,
RotateCcw,
RotateCw,
Volume2,
VolumeX,
} from 'lucide-react';
import { tauriApi } from '../lib/tauri';
import { computeUptimeSeconds, formatDurationClock, useNowTick } from '../lib/time';
import type { HlsVariant } from '../types';
import { MpvViewport } from './MpvViewport';
export interface StreamLevel {
index: number;
label: string;
}
type Phase = 'resolving' | 'loading' | 'playing' | 'offline' | 'error';
interface StreamVideoProps {
channelName: string;
slotId?: string;
startedAt?: string | null;
muted?: boolean;
/** 0-100 playback volume (persisted by the store) */
volume?: number;
/** -1 = automatic quality */
level?: number;
reloadToken?: number;
onLevels?: (levels: StreamLevel[]) => void;
/** Enables F / M / Space hotkeys, mouse wheel volume, and double-click fullscreen */
enableShortcuts?: boolean;
onToggleFullscreen?: () => void;
onToggleMute?: () => void;
onVolumeChange?: (volume: number) => void;
onToggleChat?: () => void;
isChatOpen?: boolean;
showControls?: boolean;
surfaceVisible?: boolean;
aboveParent?: boolean;
onSurfaceClick?: () => void;
className?: string;
}
/** Kick playback tokens expire after ~10 minutes; refresh comfortably before that. */
const TOKEN_REFRESH_MS = 4 * 60 * 1000;
const MAX_AUTO_RETRIES = 4;
/** Live-edge hysteresis thresholds */
const BEHIND_TRIGGER_LATENCY_SECS = 4.0;
const BEHIND_TRIGGER_DURATION_MS = 3500;
const BEHIND_CLEAR_LATENCY_SECS = 2.2;
function pickAutoVariant(variants: HlsVariant[]): HlsVariant | null {
if (variants.length === 0) return null;
const preferred1080 = variants.find((v) => v.height === 1080);
if (preferred1080) return preferred1080;
const preferred720 = variants.find((v) => v.height === 720);
if (preferred720) return preferred720;
return variants[0];
}
export const StreamVideo: React.FC<StreamVideoProps> = ({
channelName,
slotId = 'main',
startedAt = null,
muted = false,
volume = 100,
level = -1,
reloadToken = 0,
onLevels,
enableShortcuts = false,
onToggleFullscreen,
onToggleMute,
onVolumeChange,
onToggleChat,
isChatOpen = false,
showControls = true,
surfaceVisible = true,
aboveParent = false,
onSurfaceClick,
className = '',
}) => {
const levelsCallbackRef = useRef(onLevels);
levelsCallbackRef.current = onLevels;
const shortcutRefs = useRef({ onToggleFullscreen, onToggleMute, onVolumeChange });
shortcutRefs.current = { onToggleFullscreen, onToggleMute, onVolumeChange };
const masterUrlRef = useRef('');
const activeUrlRef = useRef('');
const loadSeqRef = useRef(0);
const retryRef = useRef(0);
const retryTimerRef = useRef<number | undefined>(undefined);
const hideControlsTimer = useRef<number | undefined>(undefined);
const behindSinceRef = useRef<number | null>(null);
const channelNameRef = useRef(channelName);
channelNameRef.current = channelName;
const volumeRef = useRef(volume);
volumeRef.current = volume;
const mutedRef = useRef(muted);
mutedRef.current = muted;
const levelRef = useRef(level);
levelRef.current = level;
const [variants, setVariants] = useState<HlsVariant[]>([]);
const [phase, setPhase] = useState<Phase>('resolving');
const phaseRef = useRef<Phase>(phase);
phaseRef.current = phase;
const awaitingLoadRef = useRef(false);
const [errorText, setErrorText] = useState('');
const [isBuffering, setIsBuffering] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [isBehindLive, setIsBehindLive] = useState(false);
const [controlsVisible, setControlsVisible] = useState(true);
const [latencySec, setLatencySec] = useState(0);
const [fps, setFps] = useState(0);
const [playbackSpeed, setPlaybackSpeed] = useState(1.0);
const [qualityLabel, setQualityLabel] = useState('');
const [reloadBump, setReloadBump] = useState(0);
const [resolvedStartedAt, setResolvedStartedAt] = useState<string | null>(startedAt);
const [dvrMode, setDvrMode] = useState<'live' | 'vod'>('live');
const [isTimeshifted, setIsTimeshifted] = useState(false);
const [behindLiveSecs, setBehindLiveSecs] = useState(0);
const [ramBackSecs, setRamBackSecs] = useState(0);
const [vodPositionSecs, setVodPositionSecs] = useState(0);
const [vodDurationSecs, setVodDurationSecs] = useState(0);
const [streamUptimeSecs, setStreamUptimeSecs] = useState<number | null>(null);
const [dvrHint, setDvrHint] = useState<string | null>(null);
const [dvrBusy, setDvrBusy] = useState(false);
const [hoverSeek, setHoverSeek] = useState<{ pct: number; secs: number } | null>(null);
const [dragPct, setDragPct] = useState<number | null>(null);
const dvrSupported = slotId === 'main';
const dvrModeRef = useRef<'live' | 'vod'>(dvrMode);
dvrModeRef.current = dvrMode;
const isTimeshiftedRef = useRef(isTimeshifted);
isTimeshiftedRef.current = isTimeshifted;
const isPausedRef = useRef(isPaused);
isPausedRef.current = isPaused;
const behindLiveSecsRef = useRef(behindLiveSecs);
behindLiveSecsRef.current = behindLiveSecs;
const ramBackSecsRef = useRef(ramBackSecs);
ramBackSecsRef.current = ramBackSecs;
const vodPositionSecsRef = useRef(vodPositionSecs);
vodPositionSecsRef.current = vodPositionSecs;
const vodDurationSecsRef = useRef(vodDurationSecs);
vodDurationSecsRef.current = vodDurationSecs;
const streamUptimeSecsRef = useRef<number | null>(streamUptimeSecs);
streamUptimeSecsRef.current = streamUptimeSecs;
const videoHeightRef = useRef<number>(1080);
const dvrHintTimerRef = useRef<number | undefined>(undefined);
const timelineTrackRef = useRef<HTMLDivElement | null>(null);
const draggingRef = useRef(false);
const effectiveStartedAtRef = useRef<string | null>(startedAt ?? resolvedStartedAt);
const effectiveStartedAt = startedAt || resolvedStartedAt;
effectiveStartedAtRef.current = effectiveStartedAt;
const nowMs = useNowTick(phase === 'playing', 1000);
const totalUptimeSecs = computeUptimeSeconds(effectiveStartedAt, streamUptimeSecs, nowMs);
const timelineTotalSecs = Math.max(totalUptimeSecs, vodDurationSecs, ramBackSecs, 1);
const showDvrToast = (msg: string, durationMs: number = 3500) => {
setDvrHint(msg);
if (dvrHintTimerRef.current) window.clearTimeout(dvrHintTimerRef.current);
dvrHintTimerRef.current = window.setTimeout(() => {
setDvrHint(null);
}, durationMs);
};
useEffect(() => {
if (startedAt) setResolvedStartedAt(startedAt);
}, [startedAt]);
// Stop mpv slot cleanly when unmounting
useEffect(() => {
return () => {
loadSeqRef.current += 1;
if (retryTimerRef.current) window.clearTimeout(retryTimerRef.current);
if (hideControlsTimer.current) window.clearTimeout(hideControlsTimer.current);
if (dvrHintTimerRef.current) window.clearTimeout(dvrHintTimerRef.current);
void tauriApi.mpvSetVisible(false, slotId).catch(() => {});
void tauriApi.mpvStop(slotId).catch(() => {});
};
}, [slotId]);
// Reset retry/variant state on fresh channel
useEffect(() => {
retryRef.current = 0;
behindSinceRef.current = null;
setIsBehindLive(false);
setDvrMode('live');
setIsTimeshifted(false);
setBehindLiveSecs(0);
setRamBackSecs(0);
setVodPositionSecs(0);
setVodDurationSecs(0);
setStreamUptimeSecs(null);
setResolvedStartedAt(startedAt);
setDvrHint(null);
setDvrBusy(false);
setVariants([]);
levelsCallbackRef.current?.([]);
}, [channelName]);
// Resolve Kick stream URL + HLS variants and load into native libmpv
useEffect(() => {
let cancelled = false;
const seq = ++loadSeqRef.current;
if (retryTimerRef.current) {
window.clearTimeout(retryTimerRef.current);
retryTimerRef.current = undefined;
}
const startPlayback = async () => {
awaitingLoadRef.current = true;
setPhase('resolving');
setErrorText('');
setIsPaused(false);
setIsBuffering(false);
behindSinceRef.current = null;
setIsBehindLive(false);
masterUrlRef.current = '';
activeUrlRef.current = '';
try {
const info = await tauriApi.getStreamInfo(channelName);
if (cancelled || seq !== loadSeqRef.current) return;
if (!info.is_live) {
awaitingLoadRef.current = false;
await tauriApi.mpvStop(slotId).catch(() => {});
setPhase('offline');
return;
}
if (!info.playback_url) {
awaitingLoadRef.current = false;
setPhase('error');
setErrorText('Kick bu kanal için oynatma adresi döndürmedi.');
return;
}
if (info.started_at) {
setResolvedStartedAt(info.started_at);
}
masterUrlRef.current = info.playback_url;
setPhase('loading');
// Parse variant playlists for the selector while keeping master fallback
let parsedVariants: HlsVariant[] = [];
try {
parsedVariants = await tauriApi.getHlsVariants(info.playback_url);
} catch {
parsedVariants = [];
}
if (cancelled || seq !== loadSeqRef.current) return;
setVariants(parsedVariants);
levelsCallbackRef.current?.(
parsedVariants.map((v) => ({ index: v.index, label: v.label }))
);
const chosenVariant =
levelRef.current >= 0
? parsedVariants.find((v) => v.index === levelRef.current) ??
parsedVariants[levelRef.current] ??
null
: pickAutoVariant(parsedVariants);
const targetUrl = chosenVariant?.url || info.playback_url;
if (chosenVariant?.height) {
videoHeightRef.current = chosenVariant.height;
}
setQualityLabel(chosenVariant?.label || (levelRef.current === -1 ? 'Oto' : ''));
setDvrMode('live');
setIsTimeshifted(false);
setBehindLiveSecs(0);
activeUrlRef.current = targetUrl;
await tauriApi.mpvSetVolume(volumeRef.current, slotId).catch(() => {});
await tauriApi.mpvSetMute(mutedRef.current, slotId).catch(() => {});
await tauriApi.mpvLoadStream(targetUrl, undefined, slotId);
if (cancelled || seq !== loadSeqRef.current) return;
awaitingLoadRef.current = false;
} catch (err: unknown) {
if (cancelled || seq !== loadSeqRef.current) return;
awaitingLoadRef.current = false;
const msg = err instanceof Error ? err.message : String(err);
// Do not retry-loop when libmpv-2.dll is missing
if (!msg.includes('libmpv-2.dll') && retryRef.current < MAX_AUTO_RETRIES) {
retryRef.current += 1;
const delayMs = 1000 * Math.pow(2, retryRef.current - 1);
setPhase('loading');
setErrorText(`Yayına yeniden bağlanılıyor (${retryRef.current}/${MAX_AUTO_RETRIES})…`);
retryTimerRef.current = window.setTimeout(() => {
setReloadBump((v) => v + 1);
}, delayMs);
return;
}
setPhase('error');
setErrorText(msg);
}
};
void startPlayback();
return () => {
cancelled = true;
};
}, [channelName, slotId, reloadToken, reloadBump]);
// Switch quality variant on user selection without resetting retry budget
useEffect(() => {
if (!masterUrlRef.current || variants.length === 0) return;
const chosen =
level >= 0
? variants.find((v) => v.index === level) ?? variants[level] ?? null
: pickAutoVariant(variants);
const nextUrl = chosen?.url || masterUrlRef.current;
if (!nextUrl || nextUrl === activeUrlRef.current) return;
const seq = ++loadSeqRef.current;
activeUrlRef.current = nextUrl;
if (chosen?.height) {
videoHeightRef.current = chosen.height;
}
setQualityLabel(chosen?.label || 'Oto');
setDvrMode('live');
setIsTimeshifted(false);
setBehindLiveSecs(0);
awaitingLoadRef.current = true;
setPhase('loading');
void tauriApi
.mpvLoadStream(nextUrl, undefined, slotId)
.then(() => {
if (seq === loadSeqRef.current) {
awaitingLoadRef.current = false;
}
})
.catch((err: unknown) => {
if (seq !== loadSeqRef.current) return;
awaitingLoadRef.current = false;
setPhase('error');
setErrorText(err instanceof Error ? err.message : String(err));
});
}, [level, variants, slotId]);
// Sync volume & mute to native libmpv
useEffect(() => {
void tauriApi.mpvSetVolume(volume, slotId).catch(() => {});
}, [volume, slotId]);
useEffect(() => {
void tauriApi.mpvSetMute(muted, slotId).catch(() => {});
}, [muted, slotId]);
// Silently refresh Kick signed playback token every 4 minutes
useEffect(() => {
const id = window.setInterval(() => {
void tauriApi
.getStreamInfo(channelName)
.then(async (info) => {
if (!info.is_live) {
await tauriApi.mpvStop(slotId).catch(() => {});
setPhase('offline');
return;
}
if (info.started_at) {
setResolvedStartedAt(info.started_at);
}
if (info.playback_url && info.playback_url !== masterUrlRef.current) {
masterUrlRef.current = info.playback_url;
const freshVariants = await tauriApi
.getHlsVariants(info.playback_url)
.catch(() => [] as HlsVariant[]);
setVariants(freshVariants);
levelsCallbackRef.current?.(
freshVariants.map((v) => ({ index: v.index, label: v.label }))
);
const chosen =
levelRef.current >= 0
? freshVariants.find((v) => v.index === levelRef.current) ??
freshVariants[levelRef.current] ??
null
: pickAutoVariant(freshVariants);
const refreshedUrl = chosen?.url || info.playback_url;
if (refreshedUrl !== activeUrlRef.current) {
activeUrlRef.current = refreshedUrl;
if (
dvrModeRef.current === 'vod' ||
isTimeshiftedRef.current ||
isPausedRef.current
) {
await tauriApi.mpvUpdateLiveUrl(refreshedUrl, slotId);
} else {
await tauriApi.mpvLoadStream(refreshedUrl, undefined, slotId);
}
}
}
})
.catch(() => {
/* keep current playback running on transient API failure */
});
}, TOKEN_REFRESH_MS);
return () => window.clearInterval(id);
}, [channelName, slotId]);
// Consume mpv:stats events for telemetry, live-edge hysteresis, and reconnect
useEffect(() => {
let unmounted = false;
let unlisten: (() => void) | undefined;
void tauriApi
.onMpvStats((stats) => {
if (unmounted || stats.slot_id !== slotId) return;
if (stats.error) {
awaitingLoadRef.current = false;
if (!stats.error.includes('libmpv-2.dll') && retryRef.current < MAX_AUTO_RETRIES) {
retryRef.current += 1;
const delayMs = 1000 * Math.pow(2, retryRef.current - 1);
setPhase('loading');
setErrorText(
`Bağlantı koptu, yeniden deneniyor (${retryRef.current}/${MAX_AUTO_RETRIES})…`
);
if (retryTimerRef.current) window.clearTimeout(retryTimerRef.current);
retryTimerRef.current = window.setTimeout(() => {
setReloadBump((v) => v + 1);
}, delayMs);
const expectedChannel = channelNameRef.current;
const expectedSeq = loadSeqRef.current;
void tauriApi
.getStreamInfo(expectedChannel)
.then((info) => {
if (
unmounted ||
expectedSeq !== loadSeqRef.current ||
channelNameRef.current !== expectedChannel
) {
return;
}
if (!info.is_live) {
if (retryTimerRef.current) {
window.clearTimeout(retryTimerRef.current);
retryTimerRef.current = undefined;
}
void tauriApi.mpvStop(slotId).catch(() => {});
setErrorText('');
setPhase('offline');
}
})
.catch(() => {});
return;
}
setPhase('error');
setErrorText(stats.error);
return;
}
if (stats.is_playing) {
if (awaitingLoadRef.current) {
return;
}
retryRef.current = 0;
setPhase('playing');
setErrorText('');
} else if (!awaitingLoadRef.current && phaseRef.current === 'playing') {
setPhase('loading');
}
setIsBuffering(stats.is_buffering);
setIsPaused(stats.is_paused);
setLatencySec(stats.latency_sec);
setFps(stats.fps);
setPlaybackSpeed(stats.playback_speed);
if (stats.dvr_mode) {
setDvrMode(stats.dvr_mode);
}
if (typeof stats.is_timeshifted === 'boolean') {
setIsTimeshifted(stats.is_timeshifted);
}
if (typeof stats.behind_live_secs === 'number') {
setBehindLiveSecs(stats.behind_live_secs);
}
if (typeof stats.ram_back_secs === 'number') {
setRamBackSecs(stats.ram_back_secs);
}
if (typeof stats.vod_position_secs === 'number') {
setVodPositionSecs(stats.vod_position_secs);
}
if (typeof stats.vod_duration_secs === 'number') {
setVodDurationSecs(stats.vod_duration_secs);
}
if (typeof stats.stream_uptime_secs === 'number' && stats.stream_uptime_secs > 0) {
setStreamUptimeSecs(stats.stream_uptime_secs);
}
if (stats.video_height > 0) {
videoHeightRef.current = stats.video_height;
if (levelRef.current === -1) {
const roundedFps = stats.fps >= 50 ? Math.round(stats.fps) : 0;
setQualityLabel(
roundedFps > 0 ? `${stats.video_height}p${roundedFps}` : `${stats.video_height}p`
);
}
}
// Hysteresis for live-edge button:
// Trigger red immediately when paused / timeshifted / VOD OR when latency exceeds threshold.
const now = performance.now();
if (stats.is_paused || stats.is_timeshifted || stats.dvr_mode === 'vod') {
behindSinceRef.current = null;
setIsBehindLive(true);
} else if (stats.latency_sec > BEHIND_TRIGGER_LATENCY_SECS) {
if (behindSinceRef.current === null) {
behindSinceRef.current = now;
} else if (now - behindSinceRef.current >= BEHIND_TRIGGER_DURATION_MS) {
setIsBehindLive(true);
}
} else {
behindSinceRef.current = null;
if (stats.latency_sec <= BEHIND_CLEAR_LATENCY_SECS) {
setIsBehindLive(false);
}
}
})
.then((fn) => {
if (unmounted) fn();
else unlisten = fn;
})
.catch(() => {});
return () => {
unmounted = true;
unlisten?.();
};
}, [slotId]);
const seekToLiveEdge = (e?: React.MouseEvent) => {
e?.stopPropagation();
behindSinceRef.current = null;
setIsBehindLive(false);
setIsTimeshifted(false);
setBehindLiveSecs(0);
setDvrMode('live');
setIsPaused(false);
setDvrBusy(false);
void tauriApi.mpvSeekLive(slotId).catch(() => {});
};
const triggerVodSeek = async (targetSecs: number) => {
if (!dvrSupported) return;
const clampedTarget = Math.max(0, targetSecs);
setDvrBusy(true);
setIsTimeshifted(true);
setIsBehindLive(true);
setIsPaused(false);
showDvrToast('Geçmiş yayın akışı yükleniyor…', 8000);
try {
await tauriApi.mpvLoadVodDvr(
channelNameRef.current,
clampedTarget,
videoHeightRef.current > 0 ? videoHeightRef.current : null,
slotId
);
setDvrMode('vod');
setDvrHint(null);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
showDvrToast(
msg || 'Bu kanalda geçmiş yayın (DVR) kaydı bulunamadı.',
4000
);
} finally {
setDvrBusy(false);
}
};
const seekByDelta = (deltaSecs: number) => {
if (!dvrSupported || phaseRef.current !== 'playing') return;
if (dvrModeRef.current === 'vod') {
const cur = vodPositionSecsRef.current;
const dur = Math.max(vodDurationSecsRef.current, timelineTotalSecs);
if (deltaSecs > 0 && cur + deltaSecs >= dur - 2.5) {
seekToLiveEdge();
return;
}
setIsTimeshifted(true);
setIsBehindLive(true);
void tauriApi.mpvSeekRelative(deltaSecs, slotId).catch(() => {});
return;
}
const curBehind = behindLiveSecsRef.current;
const ramBack = ramBackSecsRef.current;
if (deltaSecs > 0 && curBehind <= deltaSecs + 1.5) {
seekToLiveEdge();
return;
}
const desiredBehind = Math.max(0, curBehind - deltaSecs);
if (desiredBehind <= Math.max(ramBack - 1.5, 0) || totalUptimeSecs <= ramBack + 3) {
setIsTimeshifted(desiredBehind > 2.5);
setIsBehindLive(desiredBehind > 2.5);
void tauriApi.mpvSeekRelative(deltaSecs, slotId).catch(() => {});
return;
}
const targetPos = Math.max(0, totalUptimeSecs - desiredBehind);
void triggerVodSeek(targetPos);
};
const seekToTimelinePos = (targetSecs: number) => {
if (!dvrSupported || phaseRef.current !== 'playing') return;
const total = Math.max(totalUptimeSecs, vodDurationSecsRef.current, ramBackSecsRef.current, 1);
const clampedTarget = Math.max(0, Math.min(total, targetSecs));
const targetBehind = Math.max(0, total - clampedTarget);
if (targetBehind <= 2.5) {
seekToLiveEdge();
return;
}
if (dvrModeRef.current === 'vod') {
setIsTimeshifted(true);
setIsBehindLive(true);
void tauriApi.mpvSeekBehindLive(targetBehind, slotId).catch(() => {});
return;
}
const ramBack = ramBackSecsRef.current;
if (targetBehind <= Math.max(ramBack - 1.0, 0) || total <= ramBack + 3) {
setIsTimeshifted(true);
setIsBehindLive(true);
void tauriApi.mpvSeekBehindLive(targetBehind, slotId).catch(() => {});
return;
}
void triggerVodSeek(clampedTarget);
};
const seekByDeltaRef = useRef(seekByDelta);
seekByDeltaRef.current = seekByDelta;
// Keyboard shortcuts: Space = pause/resume, F = fullscreen, M = mute, Arrows/J/L = seek
useEffect(() => {
if (!enableShortcuts) return;
const onKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
if (target && ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName)) return;
if (event.ctrlKey || event.altKey || event.metaKey) return;
if (event.code === 'Space') {
event.preventDefault();
setIsPaused((prev) => {
const next = !prev;
void tauriApi.mpvSetPause(next, slotId).catch(() => {});
return next;
});
} else if (event.key === 'f' || event.key === 'F') {
event.preventDefault();
shortcutRefs.current.onToggleFullscreen?.();
} else if (event.key === 'm' || event.key === 'M') {
event.preventDefault();
shortcutRefs.current.onToggleMute?.();
} else if (event.key === 'ArrowLeft' || event.key === 'j' || event.key === 'J') {
event.preventDefault();
seekByDeltaRef.current(-10);
} else if (event.key === 'ArrowRight' || event.key === 'l' || event.key === 'L') {
event.preventDefault();
seekByDeltaRef.current(10);
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [enableShortcuts, slotId]);
const togglePlayPause = (e?: React.MouseEvent) => {
e?.stopPropagation();
const next = !isPaused;
setIsPaused(next);
void tauriApi.mpvSetPause(next, slotId).catch(() => {});
};
const handleRetry = () => {
retryRef.current = 0;
setReloadBump((v) => v + 1);
};
const handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {
if (!enableShortcuts || !shortcutRefs.current.onVolumeChange) return;
const delta = event.deltaY < 0 ? 5 : -5;
const next = Math.max(0, Math.min(100, volumeRef.current + delta));
shortcutRefs.current.onVolumeChange(next);
};
const revealControls = () => {
setControlsVisible(true);
if (hideControlsTimer.current) window.clearTimeout(hideControlsTimer.current);
hideControlsTimer.current = window.setTimeout(() => setControlsVisible(false), 2800);
};
const showSpinner = phase === 'resolving' || phase === 'loading';
const showVideoSurface = phase === 'playing';
const showTimeshiftBadge = isBehindLive || isTimeshifted || dvrMode === 'vod';
const currentPosSecs =
dvrMode === 'vod'
? Math.min(timelineTotalSecs, Math.max(0, vodPositionSecs))
: Math.max(0, timelineTotalSecs - behindLiveSecs);
const progressPct =
dragPct !== null
? dragPct
: Math.max(0, Math.min(100, (currentPosSecs / timelineTotalSecs) * 100));
const ramStartPct =
dvrMode === 'live' && ramBackSecs > 1.5
? Math.max(0, Math.min(100, ((timelineTotalSecs - ramBackSecs) / timelineTotalSecs) * 100))
: 100;
const pctFromPointer = (clientX: number): number => {
const rect = timelineTrackRef.current?.getBoundingClientRect();
if (!rect || rect.width <= 0) return 100;
return Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100));
};
return (
<MpvViewport
slotId={slotId}
visible={surfaceVisible && showVideoSurface}
aboveParent={aboveParent}
className={className}
onClick={onSurfaceClick}
onDoubleClick={enableShortcuts ? () => shortcutRefs.current.onToggleFullscreen?.() : undefined}
onMouseMove={revealControls}
onMouseLeave={() => setControlsVisible(false)}
onWheel={handleWheel}
>
{/* Buffering indicator over live video */}
{phase === 'playing' && isBuffering && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="px-3 py-2 rounded-xl bg-black/70 border border-white/10 flex items-center gap-2 text-xs text-slate-200">
<Loader2 className="w-4 h-4 text-[#60E0B1] animate-spin" />
<span>Ara belleğe alınıyor…</span>
</div>
</div>
)}
{/* Non-blocking DVR toast hint */}
{phase === 'playing' && dvrHint && (
<div className="absolute bottom-20 left-1/2 -translate-x-1/2 z-30 pointer-events-none">
<div className="px-3.5 py-1.5 rounded-xl bg-black/85 border border-[#2E3542] text-xs font-medium text-slate-100 shadow-xl flex items-center gap-2">
{dvrBusy && <Loader2 className="w-3.5 h-3.5 text-[#60E0B1] animate-spin shrink-0" />}
<span>{dvrHint}</span>
</div>
</div>
)}
{/* Custom overlay control bar */}
{showControls &&
phase === 'playing' &&
(controlsVisible || isPaused || dvrBusy || dragPct !== null) && (
<div
onDoubleClick={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
className="absolute inset-x-0 bottom-0 z-20 px-3 pt-10 pb-2.5 bg-gradient-to-t from-black/95 via-black/65 to-transparent"
>
{/* Hybrid DVR Timeline Scrubber */}
{dvrSupported && (
<div
ref={timelineTrackRef}
onPointerDown={(e) => {
e.stopPropagation();
e.currentTarget.setPointerCapture(e.pointerId);
draggingRef.current = true;
const pct = pctFromPointer(e.clientX);
setDragPct(pct);
setHoverSeek({ pct, secs: (pct / 100) * timelineTotalSecs });
}}
onPointerMove={(e) => {
const pct = pctFromPointer(e.clientX);
setHoverSeek({ pct, secs: (pct / 100) * timelineTotalSecs });
if (draggingRef.current) {
setDragPct(pct);
}
}}
onPointerUp={(e) => {
if (!draggingRef.current) return;
draggingRef.current = false;
try {
e.currentTarget.releasePointerCapture(e.pointerId);
} catch {
/* ignore */
}
const pct = pctFromPointer(e.clientX);
setDragPct(null);
seekToTimelinePos((pct / 100) * timelineTotalSecs);
}}
onPointerLeave={() => {
if (!draggingRef.current) {
setHoverSeek(null);
}
}}
className="group/scrubber relative h-5 flex items-center cursor-pointer mb-1.5 select-none"
>
{/* Hover timestamp tooltip */}
{hoverSeek && (
<div
style={{ left: `${Math.max(6, Math.min(94, hoverSeek.pct))}%` }}
className="absolute -top-7 -translate-x-1/2 px-2 py-0.5 rounded-md bg-[#101318]/95 border border-[#2E3542] text-[10px] font-mono text-slate-100 whitespace-nowrap shadow-lg pointer-events-none flex items-center gap-1.5"
>
<span>{formatDurationClock(hoverSeek.secs)}</span>
{timelineTotalSecs - hoverSeek.secs > 3 && (
<span className="text-slate-400">
(-{formatDurationClock(timelineTotalSecs - hoverSeek.secs)})
</span>
)}
<span
className={`px-1 rounded text-[9px] font-semibold ${
dvrMode === 'live' &&
timelineTotalSecs - hoverSeek.secs <= Math.max(ramBackSecs, 0)
? 'bg-[#247553]/40 text-[#60E0B1]'
: timelineTotalSecs - hoverSeek.secs <= 3
? 'bg-emerald-500/20 text-emerald-300'
: 'bg-amber-500/20 text-amber-300'
}`}
>
{timelineTotalSecs - hoverSeek.secs <= 3
? 'CANLI'
: dvrMode === 'live' &&
timelineTotalSecs - hoverSeek.secs <= Math.max(ramBackSecs, 0)
? 'RAM'
: 'ARŞİV'}
</span>
</div>
)}
{/* Base Track */}
<div className="relative w-full h-1.5 group-hover/scrubber:h-2 transition-all rounded-full bg-white/20 overflow-hidden">
{/* RAM Cached Instant-Seek Segment */}
{dvrMode === 'live' && ramStartPct < 100 && (
<div
style={{
left: `${ramStartPct}%`,
width: `${Math.max(0, 100 - ramStartPct)}%`,
}}
className="absolute inset-y-0 bg-[#60E0B1]/35"
/>
)}
{/* Played Progress */}
<div
style={{ width: `${progressPct}%` }}
className="absolute inset-y-0 left-0 bg-gradient-to-r from-[#247553] to-[#4CE0AC]"
/>
</div>
{/* Playhead Thumb */}
<div
style={{ left: `${progressPct}%` }}
className="absolute -translate-x-1/2 w-3 h-3 rounded-full bg-[#4CE0AC] border-2 border-[#0B0D11] shadow-[0_0_8px_rgba(76,224,172,0.75)] opacity-85 group-hover/scrubber:opacity-100 group-hover/scrubber:scale-110 transition-transform pointer-events-none"
/>
</div>
)}
<div className="flex items-center gap-1.5 sm:gap-2 text-slate-200">
<button
onClick={togglePlayPause}
title={isPaused ? 'Oynat (Space)' : 'Duraklat (Space)'}
className="p-1.5 rounded-lg hover:bg-white/10 transition-colors"
>
{isPaused ? <Play className="w-4 h-4" /> : <Pause className="w-4 h-4" />}
</button>
{dvrSupported && (
<>
<button
onClick={(e) => {
e.stopPropagation();
seekByDelta(-10);
}}
title="10 sn geri sar (← / J)"
className="px-1.5 py-1 rounded-lg hover:bg-white/10 text-slate-200 hover:text-[#60E0B1] transition-colors flex items-center gap-1 text-[11px] font-mono font-semibold"
>
<RotateCcw className="w-3.5 h-3.5" />
<span>10s</span>
</button>
<button
onClick={(e) => {
e.stopPropagation();
seekByDelta(10);
}}
disabled={dvrMode === 'live' && behindLiveSecs < 2.0}
title="10 sn ileri sar (→ / L)"
className="px-1.5 py-1 rounded-lg hover:bg-white/10 text-slate-200 hover:text-[#60E0B1] disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-slate-200 transition-colors flex items-center gap-1 text-[11px] font-mono font-semibold"
>
<span>10s</span>
<RotateCw className="w-3.5 h-3.5" />
</button>
</>
)}
<button
onClick={(e) => {
e.stopPropagation();
onToggleMute?.();
}}
title={muted ? 'Sesi aç (M)' : 'Sessize al (M)'}
className="p-1.5 rounded-lg hover:bg-white/10 transition-colors"
>
{muted ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
</button>
<input
type="range"
min={0}
max={100}
value={muted ? 0 : volume}
onClick={(e) => e.stopPropagation()}
onChange={(event) => onVolumeChange?.(Number(event.target.value))}
className="w-14 sm:w-16 accent-[#60E0B1] cursor-pointer"
title={`Ses: %${muted ? 0 : volume}`}
/>
<button
onClick={seekToLiveEdge}
title={showTimeshiftBadge ? 'En güncel yayın anına dön' : 'Canlı yayın kenarındasınız'}
className={`ml-0.5 px-2.5 py-1 rounded-full text-[11px] font-bold border flex items-center gap-1.5 transition-colors shrink-0 ${
showTimeshiftBadge
? 'bg-rose-500/20 border-rose-500/70 text-rose-300 hover:bg-rose-500/30'
: 'bg-[#101318]/85 border-[#2E3542] text-[#60E0B1]'
}`}
>
<span
className={`w-1.5 h-1.5 rounded-full ${
showTimeshiftBadge ? 'bg-rose-500 animate-pulse' : 'bg-[#60E0B1]'
}`}
/>
{showTimeshiftBadge ? (
<span>
CANLI&apos;YA AL
{behindLiveSecs >= 3 ? ` · -${formatDurationClock(behindLiveSecs)}` : ''}
</span>
) : (
<span>CANLI</span>
)}
</button>
{totalUptimeSecs > 0 && (
<span
title="Canlı yayın süresi"
className="hidden sm:inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-black/45 border border-white/10 text-[10px] font-mono text-slate-200 shrink-0"
>
<Clock className="w-3 h-3 text-[#60E0B1]" />
<span>{formatDurationClock(totalUptimeSecs)}</span>
</span>
)}
<span className="text-[10px] font-mono text-slate-300 hidden md:flex items-center gap-1.5 truncate">
{qualityLabel && <span>{qualityLabel}</span>}
{fps > 0 && <span className="text-slate-400">· {Math.round(fps)}fps</span>}
{dvrMode === 'vod' ? (
<span className="px-1.5 py-0.2 rounded bg-amber-500/20 border border-amber-500/40 text-amber-300 font-semibold">
ARŞİV DVR
</span>
) : (
latencySec > 0.1 && (
<span className="text-slate-400">· {latencySec.toFixed(1)}s</span>
)
)}
{playbackSpeed > 1.01 && (
<span className="px-1 py-0.2 rounded bg-[#247553]/40 text-[#60E0B1]">
{playbackSpeed.toFixed(2)}x
</span>
)}
</span>
<div className="ml-auto flex items-center gap-1 shrink-0">
{onToggleChat && (
<button
onClick={(e) => {
e.stopPropagation();
onToggleChat();
}}
title={isChatOpen ? 'Sohbeti Gizle' : 'Sohbeti Göster'}
className={`p-1.5 rounded-lg transition-colors ${
isChatOpen
? 'text-[#60E0B1] bg-[#247553]/30 hover:bg-[#247553]/45'
: 'hover:bg-white/10 text-slate-300'
}`}
>
<MessageSquare className="w-4 h-4" />
</button>
)}
<button
onClick={(e) => {
e.stopPropagation();
onToggleFullscreen?.();
}}
title="Tam Ekran (F)"
className="p-1.5 rounded-lg hover:bg-white/10 transition-colors"
>
<Maximize2 className="w-4 h-4" />
</button>
</div>
</div>
</div>
)}
{/* Opaque backdrop for loading / offline / error states so desktop never shows through */}
{showSpinner && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 pointer-events-none bg-[#0B0D11]">
<Loader2 className="w-8 h-8 text-[#60E0B1] animate-spin" />
<span className="text-xs font-semibold text-slate-300">
{errorText
? errorText
: phase === 'resolving'
? 'Yayın bilgisi alınıyor…'
: dvrBusy || dvrMode === 'vod'
? 'Geçmiş yayın akışı hazırlanıyor…'
: 'D3D11VA donanım oynatıcısı hazırlanıyor…'}
</span>
</div>
)}
{phase === 'offline' && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center bg-[#0B0D11]">
<Radio className="w-10 h-10 text-slate-500" />
<p className="text-sm font-bold text-slate-200">{channelName} şu anda çevrimdışı</p>
<p className="text-xs text-slate-400 max-w-xs">
Kanal canlıya geçtiğinde bildirim alacaksınız. Yayının açılmasını beklemeden kontrol
edebilirsiniz.
</p>
<button
onClick={handleRetry}
className="px-4 py-2 rounded-xl bg-[#1B202A] border border-[#2E3542] text-slate-200 text-xs font-semibold hover:text-white transition-colors flex items-center gap-1.5"
>
<RotateCw className="w-3.5 h-3.5" />
Tekrar Kontrol Et
</button>
</div>
)}
{phase === 'error' && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center bg-[#0B0D11]">
<AlertTriangle className="w-10 h-10 text-amber-400" />
<p className="text-sm font-semibold text-slate-200">Yayın açılamadı</p>
<p className="text-xs text-slate-400 max-w-sm break-words">
{errorText || 'Bilinmeyen bir akış hatası oluştu.'}
</p>
<button
onClick={handleRetry}
className="px-4 py-2 rounded-xl bg-gradient-to-r from-[#247553] to-[#4CE0AC] text-[#101318] text-xs font-bold flex items-center gap-1.5"
>
<RotateCw className="w-3.5 h-3.5" />
Yeniden Dene
</button>
</div>
)}
</MpvViewport>
);
};