refactor: improve UI and fix videoplayer bugs

This commit is contained in:
--remove-section committed 2025-12-20 15:00:41 +05:30
1 parent 3000146e66
commit 6576bfe5f3
12 files changed
+523 -174

No files matched your search

+11 -1
View File
@@ -248,12 +248,16 @@ const PlayButton = ({
(value) => value.Type === "Video",
);
const isDirectPlay =
!result.mediaSource.MediaSources?.[0].SupportsTranscoding ||
!result.mediaSource.MediaSources?.[0].TranscodingUrl;
playItem({
metadata: {
itemName: itemName ?? "",
episodeTitle: episodeTitle,
isEpisode: !!item.SeriesId,
itemDuration: item.RunTimeTicks ?? 0,
itemDuration: playItemValue?.RunTimeTicks ?? item.RunTimeTicks ?? 0,
item: playItemValue ?? item,
mediaSegments: result.mediaSegments,
userDataLastPlayedPositionTicks: startPosition ?? 0,
@@ -274,6 +278,12 @@ const PlayButton = ({
enable: subtitle?.enable ?? false,
},
audio: audio,
bitrate: result.mediaSource.MediaSources?.[0].Bitrate,
videoCodec: videoTrack?.[0]?.Codec,
audioCodec: audio.allTracks?.find((t) => t.Index === audio.track)
?.Codec,
isDirectPlay: isDirectPlay,
transcodingUrl: result.mediaSource.MediaSources?.[0].TranscodingUrl,
},
playbackStream: playbackUrl,
playsessionId: result.mediaSource.PlaySessionId,
@@ -8,11 +8,12 @@ const EndsAtDisplay = () => {
const { currentTime, itemDuration } = usePlaybackStore(
useShallow((state) => ({
currentTime: state.playerState.currentTime,
itemDuration: state.metadata.itemDuration,
itemDuration:
state.metadata.itemDuration ?? state.metadata.item?.RunTimeTicks,
})),
);
if (!itemDuration) return null;
if (!itemDuration) return <Typography variant="subtitle1">--:--</Typography>;
const remaining = itemDuration - (currentTime ?? 0);
@@ -0,0 +1,53 @@
import { Button, Typography } from "@mui/material";
import React from "react";
interface ErrorDisplayProps {
error: any;
onRetry?: () => void;
onExit?: () => void;
}
const ErrorDisplay = ({ error, onRetry, onExit }: ErrorDisplayProps) => {
if (!error) return null;
return (
<div
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
backgroundColor: "rgba(0, 0, 0, 0.8)",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
zIndex: 100,
color: "white",
gap: "1rem",
}}
>
<Typography variant="h5" color="error">
Playback Error
</Typography>
<Typography variant="body1">
{error.message || "An unknown error occurred during playback."}
</Typography>
<div style={{ display: "flex", gap: "1rem" }}>
{onRetry && (
<Button variant="contained" color="primary" onClick={onRetry}>
Retry
</Button>
)}
{onExit && (
<Button variant="outlined" color="secondary" onClick={onExit}>
Exit
</Button>
)}
</div>
</div>
);
};
export default ErrorDisplay;
@@ -4,12 +4,13 @@ import { useShallow } from "zustand/shallow";
import ticksDisplay from "@/utils/methods/ticksDisplay";
import { usePlaybackStore } from "@/utils/store/playback";
const ProgressDislay = () => {
const ProgressDisplay = () => {
const { currentTime, itemDuration, isUserSeeking, seekValue } =
usePlaybackStore(
useShallow((state) => ({
currentTime: state.playerState.currentTime,
itemDuration: state.metadata.itemDuration,
itemDuration:
state.metadata.itemDuration ?? state.metadata.item?.RunTimeTicks,
isUserSeeking: state.playerState.isUserSeeking,
seekValue: state.playerState.seekValue,
})),
@@ -19,9 +20,9 @@ const ProgressDislay = () => {
<Typography>
{ticksDisplay(isUserSeeking ? (seekValue ?? 0) : (currentTime ?? 0))}
</Typography>
<Typography>{ticksDisplay(itemDuration)}</Typography>
<Typography>{ticksDisplay(itemDuration ?? 0)}</Typography>
</div>
);
};
export default ProgressDislay;
export default ProgressDisplay;
@@ -0,0 +1,165 @@
import { IconButton, Paper, Typography } from "@mui/material";
import React, { type RefObject, useEffect, useState } from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
interface StatsForNerdsProps {
playerRef: RefObject<HTMLVideoElement>;
}
const StatsForNerds = ({ playerRef }: StatsForNerdsProps) => {
const {
showStatsForNerds,
toggleShowStatsForNerds,
itemId,
mediaSourceId,
playsessionId,
volume,
isBuffering,
playbackStream,
mediaSource,
} = usePlaybackStore(
useShallow((state) => ({
showStatsForNerds: state.playerState.showStatsForNerds,
toggleShowStatsForNerds: state.toggleShowStatsForNerds,
itemId: state.metadata.item?.Id,
mediaSourceId: state.mediaSource.id,
playsessionId: state.playsessionId,
volume: state.playerState.volume,
isBuffering: state.playerState.isBuffering,
playbackStream: state.playbackStream,
mediaSource: state.mediaSource,
})),
);
const [videoStats, setVideoStats] = useState<{
resolution: string;
droppedFrames: number;
totalFrames: number;
buffered: string;
}>({
resolution: "-",
droppedFrames: 0,
totalFrames: 0,
buffered: "-",
});
useEffect(() => {
if (!showStatsForNerds) return;
const interval = setInterval(() => {
if (playerRef.current) {
const internalPlayer = playerRef.current as HTMLVideoElement;
if (internalPlayer) {
const quality = internalPlayer.getVideoPlaybackQuality?.();
let bufferedEnd = 0;
if (internalPlayer.buffered.length > 0) {
// Find the buffered range that covers the current time
for (let i = 0; i < internalPlayer.buffered.length; i++) {
if (
internalPlayer.buffered.start(i) <=
internalPlayer.currentTime &&
internalPlayer.buffered.end(i) >= internalPlayer.currentTime
) {
bufferedEnd = internalPlayer.buffered.end(i);
break;
}
}
}
setVideoStats({
resolution:
internalPlayer.videoWidth && internalPlayer.videoHeight
? `${internalPlayer.videoWidth}x${internalPlayer.videoHeight}`
: "-",
droppedFrames: quality?.droppedVideoFrames ?? 0,
totalFrames: quality?.totalVideoFrames ?? 0,
buffered: `${(bufferedEnd - internalPlayer.currentTime).toFixed(2)}s`,
});
}
}
}, 1000);
return () => clearInterval(interval);
}, [showStatsForNerds, playerRef]);
if (!showStatsForNerds) return null;
return (
<Paper
className="glass"
sx={{
position: "absolute",
top: "2em",
left: "2em",
padding: "1em",
color: "white",
zIndex: 100,
maxWidth: "400px",
fontSize: "0.8rem",
fontFamily: "monospace",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "0.5em",
}}
>
<Typography variant="subtitle2" fontWeight="bold">
Stats for Nerds
</Typography>
<IconButton
size="small"
onClick={toggleShowStatsForNerds}
sx={{ color: "white" }}
>
<span
className="material-symbols-rounded"
style={{ fontSize: "1.2rem" }}
>
close
</span>
</IconButton>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "auto 1fr",
gap: "0.5em 1em",
}}
>
<span>Video ID:</span> <span>{itemId}</span>
<span>Media Source ID:</span> <span>{mediaSourceId}</span>
<span>Play Session ID:</span> <span>{playsessionId}</span>
<span>Playback Method:</span>{" "}
<span>{mediaSource.isDirectPlay ? "Direct Play" : "Transcoding"}</span>
<span>Container:</span> <span>{mediaSource.container}</span>
<span>Video Codec:</span> <span>{mediaSource.videoCodec}</span>
<span>Audio Codec:</span> <span>{mediaSource.audioCodec}</span>
<span>Bitrate:</span>{" "}
<span>
{mediaSource.bitrate
? `${(mediaSource.bitrate / 1000000).toFixed(2)} Mbps`
: "-"}
</span>
<span>Stream URL:</span>{" "}
<span style={{ wordBreak: "break-all" }}>{playbackStream}</span>
<span>Resolution:</span> <span>{videoStats.resolution}</span>
<span>Volume:</span> <span>{Math.round(volume * 100)}%</span>
<span>Buffer Health:</span> <span>{videoStats.buffered}</span>
<span>Dropped Frames:</span>{" "}
<span>
{videoStats.droppedFrames} / {videoStats.totalFrames}
</span>
<span>Is Buffering:</span> <span>{isBuffering ? "Yes" : "No"}</span>
</div>
</Paper>
);
};
export default StatsForNerds;
@@ -1,7 +1,14 @@
import type { TrickplayInfo } from "@jellyfin/sdk/lib/generated-client";
import { Slider, Tooltip, Typography } from "@mui/material";
import type { Instance } from "@popperjs/core";
import React, { type MouseEvent, useMemo, useRef, useState } from "react";
import React, {
type MouseEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { useShallow } from "zustand/shallow";
import { ticksToMs } from "@/utils/date/time";
import { useApiInContext } from "@/utils/store/api";
@@ -69,24 +76,54 @@ const BubbleSlider = () => {
});
const popperRef = useRef<Instance>(null);
const areaRef = useRef<HTMLDivElement>(null);
const rafRef = useRef<number | null>(null);
const [hoverProgress, setHoverProgress] = useState(0);
const handleSliderHover = (event: MouseEvent) => {
positionRef.current = { x: event.clientX, y: event.clientY };
const rect = areaRef.current!.getBoundingClientRect();
const width = rect.width;
const distX = event.clientX - rect.left;
const percentageCovered = distX / width;
setHoverProgress(percentageCovered * (itemDuration ?? 0));
if (popperRef.current != null) {
popperRef.current.update();
}
};
useEffect(() => {
return () => {
if (rafRef.current) {
cancelAnimationFrame(rafRef.current);
}
};
}, []);
const handleSliderHover = useCallback(
(event: MouseEvent) => {
const clientX = event.clientX;
const clientY = event.clientY;
if (
positionRef.current.x === clientX &&
positionRef.current.y === clientY
) {
return;
}
positionRef.current = { x: clientX, y: clientY };
if (rafRef.current) return;
rafRef.current = requestAnimationFrame(() => {
if (areaRef.current) {
const rect = areaRef.current.getBoundingClientRect();
const width = rect.width;
const distX = clientX - rect.left;
const percentageCovered = distX / width;
setHoverProgress(percentageCovered * (itemDuration ?? 0));
if (popperRef.current != null) {
popperRef.current.update();
}
}
rafRef.current = null;
});
},
[itemDuration],
);
const chapterMarks = useMemo(() => {
const marks: { value: number }[] = [];
itemChapters?.map((val) => {
itemChapters?.forEach((val) => {
marks.push({ value: val.StartPositionTicks ?? 0 });
});
return marks;
@@ -95,14 +132,15 @@ const BubbleSlider = () => {
const sliderDisplayFormat = (value: number) => {
const currentChapter = itemChapters?.filter((chapter, index) => {
if (index + 1 === itemChapters?.length) {
return chapter;
return true;
}
if (
(itemChapters?.[index + 1]?.StartPositionTicks ?? value) - value >= 0 &&
(chapter.StartPositionTicks ?? value) - value < 0
) {
return chapter;
return true;
}
return false;
});
let trickplayResolution: TrickplayInfo | undefined;
@@ -126,6 +164,8 @@ const BubbleSlider = () => {
trickplayResolution = trickplayResolutions[bestWidth];
}
}
let trickplayStyle: React.CSSProperties | undefined;
if (
trickplayResolution?.TileWidth &&
trickplayResolution.TileHeight &&
@@ -155,101 +195,105 @@ const BubbleSlider = () => {
};
const imgUrlParams = new URLSearchParams(imgUrlParamsObject).toString();
const imageAspectRatio =
const _imageAspectRatio =
trickplayResolution.Width / trickplayResolution.Height;
if (currentChapter?.[0]?.Name) {
return (
<div className="flex flex-column video-osb-bubble">
<div
className="video-osd-trickplayBubble"
style={{
background: `url(${api?.basePath}/Videos/${itemId}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
backgroundPositionX: `${backgroundOffsetX}px`,
backgroundPositionY: `${backgroundOffsetY}px`,
width: "100%",
aspectRatio: imageAspectRatio,
}}
/>
<Typography variant="h6" px="12px" pt={1}>
{currentChapter?.[0]?.Name}
</Typography>
<Typography px="12px" pb={1}>
{ticksDisplay(value)}
</Typography>
</div>
);
}
return (
<div className="flex flex-column video-osb-bubble">
<div
className="video-osd-trickplayBubble"
style={{
background: `url(${api?.basePath}/Videos/${itemId}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
backgroundPositionX: `${backgroundOffsetX}px`,
backgroundPositionY: `${backgroundOffsetY}px`,
width: "100%",
aspectRatio: imageAspectRatio,
}}
/>
<Typography variant="h6" px="12px" py={1}>
{ticksDisplay(value)}
</Typography>
</div>
);
trickplayStyle = {
background: `url(${api?.basePath}/Videos/${itemId}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
backgroundPositionX: `${backgroundOffsetX}px`,
backgroundPositionY: `${backgroundOffsetY}px`,
width: `${trickplayResolution.Width}px`,
height: `${trickplayResolution.Height}px`,
borderBottom: "1px solid rgba(255,255,255,0.1)",
borderRadius: 0,
};
}
if (currentChapter?.[0]?.Name) {
return (
<div className="flex flex-column video-osb-bubble">
<Typography variant="h6" px="12px" pt={1}>
{currentChapter?.[0]?.Name}
</Typography>
<Typography px={2} pb={1}>
const chapterName = currentChapter?.[0]?.Name;
return (
<div
className="flex flex-column video-osb-bubble"
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
width: "100%",
}}
>
{trickplayStyle && (
<div className="video-osd-trickplayBubble" style={trickplayStyle} />
)}
<div
style={{
padding: "8px 12px",
textAlign: "center",
width: "100%",
boxSizing: "border-box",
}}
>
{chapterName && (
<Typography
variant="subtitle2"
sx={{
fontWeight: "bold",
mb: 0.5,
color: "white",
textShadow: "0 2px 4px rgba(0,0,0,0.5)",
}}
>
{chapterName}
</Typography>
)}
<Typography
variant="body2"
sx={{
color: "rgba(255,255,255,0.9)",
fontVariantNumeric: "tabular-nums",
fontWeight: 500,
}}
>
{ticksDisplay(value)}
</Typography>
</div>
);
}
return (
<div className="flex flex-column video-osb-bubble ">
<Typography variant="h6" px="12px" py={1}>
{ticksDisplay(value)}
</Typography>
</div>
);
};
const virtualAnchorEl = useMemo(() => {
return {
getBoundingClientRect: () => {
return new DOMRect(
positionRef.current.x,
areaRef.current?.getBoundingClientRect().y ?? 0,
0,
0,
);
},
};
}, []);
return (
<Tooltip
// title={sliderDisplayFormat(
// positionRef.current.x - areaRef.current!.getBoundingClientRect().x,
// )}
key={`${positionRef.current}`}
title={sliderDisplayFormat(hoverProgress)}
placement="top"
slotProps={{
popper: {
popperRef,
anchorEl: {
getBoundingClientRect: () => {
return new DOMRect(
positionRef.current.x,
areaRef.current!.getBoundingClientRect().y,
0,
0,
);
},
},
anchorEl: virtualAnchorEl,
// disablePortal: true,
},
tooltip: {
// className: "glass",
className: "glass",
style: {
width: "34em",
width: "auto",
maxWidth: "none",
overflow: "hidden",
padding: "12px",
borderRadius: "20px",
padding: "0",
borderRadius: "12px",
},
},
}}
@@ -16,16 +16,29 @@
flex-direction: column;
align-self: stretch;
justify-content: space-between;
padding: 1em 2em;
background: linear-gradient(to top, rgb(0 0 0 / 0.7) 5vh, transparent 26vh 90vh, rgb(0 0 0 / 0.7));
padding: 2em 3em;
background: linear-gradient(
to bottom,
rgba(0, 0, 0, 0.8) 0%,
rgba(0, 0, 0, 0) 25%,
rgba(0, 0, 0, 0) 75%,
rgba(0, 0, 0, 0.9) 100%
);
&.hovering {
cursor: default;
}
&-controls {
display: flex;
flex-direction: column;
gap: 1em;
&-timeline-text {
display: flex;
align-items: stretch;
justify-content: space-between;
margin-top: 0.5em;
font-weight: 500;
opacity: 0.9;
}
&-progress {
display: flex;
@@ -45,7 +58,7 @@
}
&-buttons {
display: flex;
gap: 0.4em;
gap: 0.5em;
align-items: center;
}
}
@@ -1,7 +1,7 @@
import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api";
import { IconButton, Typography } from "@mui/material";
import { IconButton, Slider, Typography } from "@mui/material";
import { WebviewWindow as appWindow } from "@tauri-apps/api/webviewWindow";
import { motion } from "motion/react";
import { AnimatePresence, motion } from "motion/react";
import React, {
type MouseEvent,
useCallback,
@@ -30,7 +30,7 @@ import VideoPlayerSettingsMenu from "./settingsMenu";
import "./controls.scss";
import { clearQueue } from "@/utils/store/queue";
import ProgressDislay from "./ProgressDisplay";
import ProgressDisplay from "./ProgressDisplay";
/**
* Constant for the volume change interval when using the mouse wheel.
@@ -65,6 +65,7 @@ const VideoPlayerControls = ({
// seekValue,
isPlayerMuted,
volume,
setVolume,
toggleIsPlayerMuted,
increaseVolumeByStep,
decreaseVolumeByStep,
@@ -86,6 +87,7 @@ const VideoPlayerControls = ({
seekValue: state.playerState.seekValue,
isPlayerMuted: state.playerState.isPlayerMuted,
volume: state.playerState.volume,
setVolume: state.setVolume,
toggleIsPlayerMuted: state.toggleIsPlayerMuted,
increaseVolumeByStep: state.increaseVolumeByStep,
decreaseVolumeByStep: state.decreaseVolumeByStep,
@@ -115,6 +117,7 @@ const VideoPlayerControls = ({
}, [increaseVolumeByStep, decreaseVolumeByStep]);
const [clickTimeout, setClickTimeout] = useState<NodeJS.Timeout | null>(null);
const [showVolumeControl, setShowVolumeControl] = useState(false);
const [settingsMenuRef, setSettingsMenuRef] =
useState<HTMLButtonElement | null>(null);
@@ -228,7 +231,7 @@ const VideoPlayerControls = ({
<div className="video-player-osd-controls">
<div className="video-player-osd-controls-timeline">
<BubbleSlider />
<ProgressDislay />
<ProgressDisplay />
</div>
<div className="flex flex-row flex-justify-spaced-between">
<div className="video-player-osd-controls-buttons">
@@ -245,68 +248,41 @@ const VideoPlayerControls = ({
<EndsAtDisplay />
</div>
<div className="video-player-osd-controls-buttons">
{/* <motion.div
style={{
width: "13em",
padding: "0.5em 1.5em",
paddingLeft: "0.8em",
gap: "0.4em",
background: "black",
borderRadius: "100px",
display: "grid",
justifyContent: "center",
alignItems: "center",
gridTemplateColumns: "2em 1fr",
opacity: 0,
}}
animate={{
opacity: showVolumeControl ? 1 : 0,
}}
whileHover={{
opacity: 1,
}}
onMouseLeave={() => setShowVolumeControl(false)}
>
<Typography textAlign="center">
{isPlayerMuted ? 0 : Math.round(playerVolume * 100)}
</Typography>
<Slider
step={0.01}
max={1}
size="small"
value={isPlayerMuted ? 0 : playerVolume}
onChange={async (_, newValue) => {
if (api && Array.isArray(newValue)) {
dispatch({
type: VideoPlayerActionKind.SET_PLAYER_VOLUME,
payload: newValue[0],
});
} else {
dispatch({
type: VideoPlayerActionKind.SET_PLAYER_VOLUME,
payload: newValue,
});
}
if (newValue === 0)
dispatch({
type: VideoPlayerActionKind.SET_PLAYER_MUTED,
payload: true,
});
else
dispatch({
type: VideoPlayerActionKind.SET_PLAYER_MUTED,
payload: true,
});
<div
className="video-player-osd-controls-buttons"
onMouseLeave={() => setShowVolumeControl(false)}
>
<AnimatePresence>
{showVolumeControl && (
<motion.div
initial={{ width: 0, opacity: 0, marginRight: 0 }}
animate={{ width: 100, opacity: 1, marginRight: 10 }}
exit={{ width: 0, opacity: 0, marginRight: 0 }}
style={{
overflow: "hidden",
display: "flex",
alignItems: "center",
}}
/>
</motion.div> */}
{/* TODO: Volume menu */}
>
<Slider
size="small"
value={isPlayerMuted ? 0 : volume}
max={1}
step={0.01}
onChange={(_, newValue) => {
const val = Array.isArray(newValue)
? newValue[0]
: newValue;
setVolume(val);
}}
sx={{ width: 100, color: "white" }}
/>
</motion.div>
)}
</AnimatePresence>
<IconButton
onClick={toggleIsPlayerMuted}
// onMouseMoveCapture={() => {
// setShowVolumeControl(true);
// }}
onMouseEnter={() => setShowVolumeControl(true)}
>
<span className="material-symbols-rounded">
{isPlayerMuted
@@ -1,4 +1,10 @@
import { MenuItem, Popover, TextField } from "@mui/material";
import {
MenuItem,
Popover,
Switch,
TextField,
Typography,
} from "@mui/material";
import { toNumber } from "lodash";
import React, {
type ChangeEventHandler,
@@ -29,10 +35,17 @@ const VideoPlayerSettingsMenu = ({
const api = useApiInContext((state) => state.api);
const { mediaSource, setIsBuffering } = usePlaybackStore(
const {
mediaSource,
setIsBuffering,
showStatsForNerds,
toggleShowStatsForNerds,
} = usePlaybackStore(
useShallow((state) => ({
mediaSource: state.mediaSource,
setIsBuffering: state.setIsBuffering,
showStatsForNerds: state.playerState.showStatsForNerds,
toggleShowStatsForNerds: state.toggleShowStatsForNerds,
})),
);
@@ -131,6 +144,10 @@ const VideoPlayerSettingsMenu = ({
</MenuItem>
))}
</TextField>
<MenuItem onClick={toggleShowStatsForNerds}>
<Typography flexGrow={1}>Stats for Nerds</Typography>
<Switch checked={showStatsForNerds} />
</MenuItem>
</Popover>
);
};