refactor: rewrite video player

This commit is contained in:
Prayag Prajapati committed 2025-06-27 16:55:17 +05:30
1 parent 0f5482627a
commit 7b0b22b611
34 files changed
+3766 -3007

No files matched your search

+8 -4
View File
@@ -1,20 +1,24 @@
import { useBackdropStore } from "@/utils/store/backdrop";
import { AnimatePresence, motion } from "motion/react";
import React, { useLayoutEffect, useState } from "react";
import { useBackdropStore } from "@/utils/store/backdrop";
export default function Backdrop() {
const [backdropLoading, setBackdropLoading] = useState(true);
const [backdropId, backdropUrl] = useBackdropStore((state) => [
state.backdropId,
state.backdropUrl,
]);
// Reset loading status for backdrop
useLayoutEffect(() => {
setBackdropLoading(true);
}, [backdropId]);
if (!backdropUrl) {
return null;
}
return (
<div className="app-backdrop-container">
<AnimatePresence>
+58 -43
View File
@@ -1,11 +1,3 @@
import React, { memo, type MouseEvent } from "react"; // Import memo
import Button, { type ButtonProps } from "@mui/material/Button";
import Fab from "@mui/material/Fab";
import LinearProgress from "@mui/material/LinearProgress";
import Typography from "@mui/material/Typography";
import { generateAudioStreamUrl, playAudio } from "@/utils/store/audioPlayback";
import {
type BaseItemDto,
type BaseItemDtoQueryResult,
@@ -17,31 +9,34 @@ import {
type PlaybackInfoResponse,
SortOrder,
} from "@jellyfin/sdk/lib/generated-client";
import { getDisplayPreferencesApi } from "@jellyfin/sdk/lib/utils/api/display-preferences-api";
import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api";
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import { getMediaSegmentsApi } from "@jellyfin/sdk/lib/utils/api/media-segments-api";
import { getPlaylistsApi } from "@jellyfin/sdk/lib/utils/api/playlists-api";
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api";
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
import { LoadingButton } from "@mui/lab";
import type { SxProps } from "@mui/material";
import Button, { type ButtonProps } from "@mui/material/Button";
import Fab from "@mui/material/Fab";
import LinearProgress from "@mui/material/LinearProgress";
import Typography from "@mui/material/Typography";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import type { AxiosResponse } from "axios";
import { useSnackbar } from "notistack";
import { setQueue } from "@/utils/store/queue";
import { playItem } from "@/utils/store/playback";
import React, { type MouseEvent, memo } from "react"; // Import memo
import type PlayResult from "@//utils/types/playResult";
import { getRuntimeCompact } from "@/utils/date/time";
import getSubtitle from "@/utils/methods/getSubtitles";
import playbackProfile from "@/utils/playback-profiles";
import { useApiInContext } from "@/utils/store/api";
import { generateAudioStreamUrl, playAudio } from "@/utils/store/audioPlayback";
import { useCentralStore } from "@/utils/store/central";
import { usePhotosPlayback } from "@/utils/store/photosPlayback";
import { getDisplayPreferencesApi } from "@jellyfin/sdk/lib/utils/api/display-preferences-api";
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import { getMediaSegmentsApi } from "@jellyfin/sdk/lib/utils/api/media-segments-api";
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
import { LoadingButton } from "@mui/lab";
import type { SxProps } from "@mui/material";
import type { AxiosResponse } from "axios";
import { playItem } from "@/utils/store/playback";
import { setQueue } from "@/utils/store/queue";
type PlayButtonProps = {
item: BaseItemDto;
@@ -89,7 +84,7 @@ const PlayButton = ({
itemType,
currentAudioTrack,
currentSubTrack,
currentVideoTrack,
// currentVideoTrack,
className,
sx,
buttonProps,
@@ -574,26 +569,46 @@ const PlayButton = ({
initVolume = displayPreferences.data.CustomPrefs?.Volume;
}
playItem(
itemName,
episodeTitle,
currentVideoTrack ?? 0,
Number(result.mediaSource.MediaSources?.[0].DefaultAudioStreamIndex),
result?.mediaSource?.MediaSources?.[0].Container ?? "mkv",
playbackUrl,
userId ?? "",
startPosition,
result?.item?.Items?.[episodeIndex].RunTimeTicks,
playItemValue ?? item,
queue,
episodeIndex,
result?.mediaSource?.MediaSources?.[0]?.Id,
result?.mediaSource?.PlaySessionId,
subtitle,
result?.mediaSegments,
audio,
Number(initVolume),
);
const videoTrack =
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
(value) => value.Type === "Video",
);
playItem({
metadata: {
itemName: itemName ?? "",
episodeTitle: episodeTitle,
isEpisode: !!item.SeriesId,
itemDuration: item.RunTimeTicks ?? 0,
item: playItemValue ?? item,
mediaSegments: result.mediaSegments,
userDataLastPlayedPositionTicks: startPosition ?? 0,
},
mediaSource: {
videoTrack: videoTrack?.[0]?.Index ?? 0,
audioTrack: audio.track,
container: result.mediaSource.MediaSources?.[0].Container ?? "",
id: result.mediaSource.MediaSources?.[0]?.Id,
subtitle: {
url: subtitle?.url,
track: subtitle?.track ?? -1,
format: subtitle?.format ?? "nosub",
allTracks:
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
(value) => value.Type === "Subtitle",
),
enable: subtitle?.enable ?? false,
},
audio: audio,
},
playbackStream: playbackUrl,
playsessionId: result.mediaSource.PlaySessionId,
userDataPlayedPositionTicks:
item.UserData?.PlaybackPositionTicks ?? 0,
userId,
queueItems: queue ?? [],
queueItemIndex: episodeIndex,
});
navigate({ to: "/player" });
}
},
@@ -686,7 +701,7 @@ const PlayButton = ({
position: "relative",
}}
>
<LoadingButton
<Button
loading={currentEpisode.isPending}
className={className ?? "play-button"}
variant="contained"
@@ -725,7 +740,7 @@ const PlayButton = ({
: 0
}
/>
</LoadingButton>
</Button>
{(currentEpisode.data?.Items?.[0].UserData?.PlaybackPositionTicks ??
0) > 0 && (
<Typography
@@ -0,0 +1,34 @@
import { CircularProgress } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const LoadingIndicator = () => {
const { isBuffering } = usePlaybackStore(
useShallow((state) => ({
isBuffering: state.playerState.isBuffering,
})),
);
if (!isBuffering) {
return null;
}
return (
<div
style={{
zIndex: 2,
position: "absolute",
height: "100vh",
width: "100vw",
top: 0,
left: 0,
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<CircularProgress size={72} thickness={1.4} />
</div>
);
};
export default LoadingIndicator;
@@ -0,0 +1,27 @@
import { Typography } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import ticksDisplay from "@/utils/methods/ticksDisplay";
import { usePlaybackStore } from "@/utils/store/playback";
const ProgressDislay = () => {
const { currentTime, itemDuration, isUserSeeking, seekValue } =
usePlaybackStore(
useShallow((state) => ({
currentTime: state.playerState.currentTime,
itemDuration: state.metadata.itemDuration,
isUserSeeking: state.playerState.isUserSeeking,
seekValue: state.playerState.seekValue,
})),
);
return (
<div className="video-player-osd-controls-timeline-text">
<Typography>
{ticksDisplay(isUserSeeking ? (seekValue ?? 0) : (currentTime ?? 0))}
</Typography>
<Typography>{ticksDisplay(itemDuration)}</Typography>
</div>
);
};
export default ProgressDislay;
@@ -0,0 +1,36 @@
import { LinearProgress } from "@mui/material";
import { AnimatePresence, motion } from "motion/react";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const VolumeChangeOverlay = () => {
const { playerVolume, showVolumeIndicator } = usePlaybackStore(
useShallow((state) => ({
playerVolume: state.playerState.volume,
showVolumeIndicator: state.isVolumeInidcatorVisible,
})),
);
return (
<AnimatePresence>
{showVolumeIndicator && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="video-volume-indicator glass"
>
<div className="material-symbols-rounded">
{playerVolume > 0.7 ? "volume_up" : "volume_down"}
</div>
<LinearProgress
style={{ width: "100%" }}
value={playerVolume * 100}
variant="determinate"
/>
</motion.div>
)}
</AnimatePresence>
);
};
export default VolumeChangeOverlay;
@@ -1,46 +1,11 @@
import { ticksToMs, ticksToSec } from "@/utils/date/time";
import {
type VideoPlayerAction,
VideoPlayerActionKind,
} from "@/utils/reducers/videoPlayerReducer";
import type audioPlaybackInfo from "@/utils/types/audioPlaybackInfo";
import type subtitlePlaybackInfo from "@/utils/types/subtitlePlaybackInfo";
import type { Api } from "@jellyfin/sdk";
import type {
BaseItemDto,
TrickplayInfo,
} from "@jellyfin/sdk/lib/generated-client";
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 RefObject,
type ActionDispatch,
type MouseEvent,
} from "react";
import { useRef, useState } from "react";
import type ReactPlayer from "react-player";
type BubbleSliderProps = {
itemDuration: number;
item: BaseItemDto;
mediaSource: {
videoTrack: number;
audioTrack: number;
container: string;
id: string | undefined;
subtitle: subtitlePlaybackInfo;
audio: audioPlaybackInfo;
};
api: Api;
chapterMarks: { value: number }[];
sliderState: {
isSeeking: boolean;
sliderSeek: number;
progress: number;
};
dispatch: ActionDispatch<[action: VideoPlayerAction]>;
player: RefObject<ReactPlayer | null>;
};
import React, { type MouseEvent, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/shallow";
import { ticksToMs } from "@/utils/date/time";
import { useApiInContext } from "@/utils/store/api";
import { usePlaybackStore } from "@/utils/store/playback";
const ticksDisplay = (ticks: number) => {
const time = Math.round(ticks / 10000);
@@ -64,16 +29,40 @@ const ticksDisplay = (ticks: number) => {
return formatedTime;
};
const BubbleSlider = ({
itemDuration,
item,
mediaSource,
api,
chapterMarks,
sliderState,
dispatch,
player,
}: BubbleSliderProps) => {
const BubbleSlider = () => {
const api = useApiInContext((state) => state.api);
const {
seekValue,
currentTime,
isUserSeeking,
// setIsUserSeeking,
// setSeekValue,
// seekTo,
itemDuration,
itemChapters,
mediaSource,
itemTrickplay,
itemId,
handleStartSeek,
handleStopSeek,
} = usePlaybackStore(
useShallow((state) => ({
seekValue: state.playerState.seekValue,
currentTime: state.playerState.currentTime,
isUserSeeking: state.playerState.isUserSeeking,
// setIsUserSeeking: state.setIsUserSeeking,
// setSeekValue: state.setSeekValue,
// seekTo: state.seekTo,
itemDuration: state.metadata.item.RunTimeTicks,
itemChapters: state.metadata.item.Chapters,
mediaSource: state.mediaSource,
itemTrickplay: state.metadata.item.Trickplay,
itemId: state.metadata.item.Id,
handleStartSeek: state.handleStartSeek,
handleStopSeek: state.handleStopSeek,
})),
);
const positionRef = useRef<{ x: number; y: number }>({
x: 0,
y: 0,
@@ -89,20 +78,27 @@ const BubbleSlider = ({
const width = rect.width;
const distX = event.clientX - rect.left;
const percentageCovered = distX / width;
setHoverProgress(percentageCovered * itemDuration);
setHoverProgress(percentageCovered * (itemDuration ?? 0));
if (popperRef.current != null) {
popperRef.current.update();
}
};
const chapterMarks = useMemo(() => {
const marks: { value: number }[] = [];
itemChapters?.map((val) => {
marks.push({ value: val.StartPositionTicks ?? 0 });
});
return marks;
}, [itemChapters]);
const sliderDisplayFormat = (value: number) => {
const currentChapter = item?.Chapters?.filter((chapter, index) => {
if (index + 1 === item.Chapters?.length) {
const currentChapter = itemChapters?.filter((chapter, index) => {
if (index + 1 === itemChapters?.length) {
return chapter;
}
if (
(item.Chapters?.[index + 1]?.StartPositionTicks ?? value) - value >=
0 &&
(itemChapters?.[index + 1]?.StartPositionTicks ?? value) - value >= 0 &&
(chapter.StartPositionTicks ?? value) - value < 0
) {
return chapter;
@@ -111,7 +107,7 @@ const BubbleSlider = ({
let trickplayResolution: TrickplayInfo | undefined;
const trickplayResolutions = mediaSource.id
? item?.Trickplay?.[mediaSource.id]
? itemTrickplay?.[mediaSource.id]
: null;
if (trickplayResolutions) {
let bestWidth: number | undefined;
@@ -168,7 +164,7 @@ const BubbleSlider = ({
<div
className="video-osd-trickplayBubble"
style={{
background: `url(${api?.basePath}/Videos/${item?.Id}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
background: `url(${api?.basePath}/Videos/${itemId}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
backgroundPositionX: `${backgroundOffsetX}px`,
backgroundPositionY: `${backgroundOffsetY}px`,
width: "100%",
@@ -189,7 +185,7 @@ const BubbleSlider = ({
<div
className="video-osd-trickplayBubble"
style={{
background: `url(${api?.basePath}/Videos/${item?.Id}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
background: `url(${api?.basePath}/Videos/${itemId}/Trickplay/${trickplayResolution.Width}/${index}.jpg?${imgUrlParams})`,
backgroundPositionX: `${backgroundOffsetX}px`,
backgroundPositionY: `${backgroundOffsetY}px`,
width: "100%",
@@ -259,44 +255,24 @@ const BubbleSlider = ({
}}
>
<Slider
value={
sliderState.isSeeking ? sliderState.sliderSeek : sliderState.progress
}
max={itemDuration}
value={isUserSeeking ? seekValue : currentTime}
max={itemDuration ?? 0}
step={1}
onChange={(_, newValue) => {
dispatch({
type: VideoPlayerActionKind.SET_SEEKING,
payload: true,
});
// setIsUserSeeking(true);
Array.isArray(newValue)
? dispatch({
type: VideoPlayerActionKind.SET_SLIDER_SEEK,
payload: newValue[0],
})
: dispatch({
type: VideoPlayerActionKind.SET_SLIDER_SEEK,
payload: newValue,
});
? handleStartSeek(newValue[0])
: handleStartSeek(newValue);
}}
onChangeCommitted={(_, newValue) => {
dispatch({
type: VideoPlayerActionKind.SET_SEEKING,
payload: false,
});
Array.isArray(newValue)
? dispatch({
type: VideoPlayerActionKind.SET_SLIDER_SEEK,
payload: newValue[0],
})
: dispatch({
type: VideoPlayerActionKind.SET_SLIDER_SEEK,
payload: newValue,
});
// setIsUserSeeking(false);
// Array.isArray(newValue)
// ? setSeekValue(newValue[0])
// : setSeekValue(newValue);
if (Array.isArray(newValue)) {
player.current?.seekTo(ticksToSec(newValue[0]), "seconds");
handleStopSeek(newValue[0]);
} else {
player.current?.seekTo(ticksToSec(newValue), "seconds");
handleStopSeek(newValue);
}
}}
sx={{
@@ -0,0 +1,25 @@
import { IconButton } from "@mui/material";
import React, { useTransition } from "react";
import { useShallow } from "zustand/shallow";
import { toggleSubtitleTrack, usePlaybackStore } from "@/utils/store/playback";
const CaptionsButton = () => {
const { subtitle } = usePlaybackStore(
useShallow((state) => ({ subtitle: state.mediaSource.subtitle })),
);
const [subtitleIsChanging, startSubtitleChange] = useTransition();
return (
<IconButton
disabled={subtitle?.allTracks?.length === 0 || subtitleIsChanging}
onClick={() => startSubtitleChange(toggleSubtitleTrack)}
>
<span className={"material-symbols-rounded"}>
{subtitle?.enable ? "closed_caption" : "closed_caption_disabled"}
</span>
</IconButton>
);
};
export default CaptionsButton;
@@ -0,0 +1,58 @@
import { IconButton, Menu, MenuItem } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { ticksToSec } from "@/utils/date/time";
import { usePlaybackStore } from "@/utils/store/playback";
const ChaptersListButton = () => {
const { itemChapters, seekTo } = usePlaybackStore(
useShallow((state) => ({
itemChapters: state.metadata.item?.Chapters,
seekTo: state.seekTo,
})),
);
const [showChapterList, setShowChapterList] =
React.useState<null | HTMLElement>(null);
const handleShowChapterList = (event: React.MouseEvent<HTMLElement>) => {
setShowChapterList(event.currentTarget);
};
return (
<>
<IconButton
disabled={itemChapters?.length === 0}
onClick={handleShowChapterList}
>
<span className="material-symbols-rounded">list</span>
</IconButton>
<Menu
open={Boolean(showChapterList)}
anchorEl={showChapterList}
onClose={() => setShowChapterList(null)}
anchorOrigin={{
vertical: "top",
horizontal: "center",
}}
transformOrigin={{
vertical: "bottom",
horizontal: "center",
}}
>
{itemChapters?.length &&
itemChapters?.map((chapter) => (
<MenuItem
key={chapter.Name}
onClick={() => {
seekTo(ticksToSec(chapter.StartPositionTicks ?? 0));
setShowChapterList(null); // Close the chapter list menu
}}
>
{chapter.Name}
</MenuItem>
))}
</Menu>
</>
);
};
export default ChaptersListButton;
@@ -0,0 +1,20 @@
import { IconButton } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const ForwardButton = () => {
const { seekForward } = usePlaybackStore(
useShallow((state) => ({
seekForward: state.seekForward,
})),
);
return (
<IconButton onClick={() => seekForward(15)}>
<span className="material-symbols-rounded fill">fast_forward</span>
</IconButton>
);
};
export default ForwardButton;
@@ -0,0 +1,23 @@
import { IconButton } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const FullscreenButton = () => {
const { isPlayerFullscreen, toggleIsPlayerFullscreen } = usePlaybackStore(
useShallow((state) => ({
isPlayerFullscreen: state.playerState.isPlayerFullscreen,
toggleIsPlayerFullscreen: state.toggleIsPlayerFullscreen,
})),
);
return (
<IconButton onClick={toggleIsPlayerFullscreen}>
<span className="material-symbols-rounded fill">
{isPlayerFullscreen ? "fullscreen_exit" : "fullscreen"}
</span>
</IconButton>
);
};
export default FullscreenButton;
@@ -0,0 +1,19 @@
import { IconButton } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const NextChapterButton = () => {
const { seekToNextChapter } = usePlaybackStore(
useShallow((state) => ({
seekToNextChapter: state.seekToNextChapter,
})),
);
return (
<IconButton onClick={() => seekToNextChapter()}>
<span className="material-symbols-rounded fill">last_page</span>
</IconButton>
);
};
export default NextChapterButton;
@@ -0,0 +1,22 @@
import { IconButton } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const PlayPauseButton = () => {
const { isPlayerPlaying, toggleIsPlaying } = usePlaybackStore(
useShallow((state) => ({
isPlayerPlaying: state.playerState.isPlayerPlaying,
toggleIsPlaying: state.toggleIsPlaying,
})),
);
return (
<IconButton onClick={toggleIsPlaying}>
<span className="material-symbols-rounded fill">
{isPlayerPlaying ? "pause" : "play_arrow"}
</span>
</IconButton>
);
};
export default PlayPauseButton;
@@ -0,0 +1,20 @@
import { IconButton } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const PrevChapterButton = () => {
const { seekToPrevChapter } = usePlaybackStore(
useShallow((state) => ({
seekToPrevChapter: state.seekToPrevChapter,
})),
);
return (
<IconButton onClick={seekToPrevChapter}>
<span className="material-symbols-rounded fill">first_page</span>
</IconButton>
);
};
export default PrevChapterButton;
@@ -0,0 +1,23 @@
import { IconButton } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const RewindButton = () => {
const { seekBackward } = usePlaybackStore(
useShallow((state) => ({
seekBackward: state.seekBackward,
})),
);
return (
<IconButton
onClick={() => {
seekBackward(15);
}}
>
<span className="material-symbols-rounded fill">fast_rewind</span>
</IconButton>
);
};
export default RewindButton;
@@ -0,0 +1,41 @@
import { Button } from "@mui/material";
import React from "react";
import { useShallow } from "zustand/shallow";
import { usePlaybackStore } from "@/utils/store/playback";
const SkipSegmentButton = () => {
const { mediaSegments, currentSegmentIndex, skipSegment } = usePlaybackStore(
useShallow((state) => ({
mediaSegments: state.metadata.mediaSegments,
currentSegmentIndex: state.nextSegmentIndex - 1,
skipSegment: state.skipSegment,
})),
);
if (!mediaSegments?.Items?.length || currentSegmentIndex < 0) {
return <></>; // No segments to skip
}
console.log("Current Segment Index:", currentSegmentIndex);
console.log("Media Segments:", mediaSegments);
return (
<Button
variant="outlined"
size="large"
//@ts-ignore
color="white"
style={{
position: "absolute",
bottom: "18vh",
right: "2em",
zIndex: 10000,
}}
onClick={skipSegment}
>
Skip {mediaSegments?.Items?.[currentSegmentIndex].Type}
</Button>
);
};
export default SkipSegmentButton;
@@ -0,0 +1,60 @@
.video-player {
background: black;
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
&-osd {
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
cursor: none;
display: flex;
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));
&.hovering {
cursor: default;
}
&-controls {
&-timeline-text {
display: flex;
align-items: stretch;
justify-content: space-between;
}
&-progress {
display: flex;
flex-direction: column;
gap: 0.2em;
align-items: stretch;
justify-content: center;
margin-bottom: 0.5em;
&-bubble {
width: 14em;
top: 0;
left: 0;
transform-origin: bottom center;
transform: translate(var(--left, 0), var(--top, 0));
position: fixed;
}
}
&-buttons {
display: flex;
gap: 0.4em;
align-items: center;
}
}
.MuiSlider-valueLabel {
padding: 0;
background: transparent;
overflow: hidden;
border-radius: $border-radius-default;
border: 1.2px solid rgb(255 255 255 / 0.1);
}
}
}
@@ -0,0 +1,334 @@
import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api";
import { IconButton, Typography } from "@mui/material";
import { WebviewWindow as appWindow } from "@tauri-apps/api/webviewWindow";
import { motion } from "motion/react";
import React, {
type MouseEvent,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { useShallow } from "zustand/shallow";
import PlayNextButton from "@/components/buttons/playNextButton";
import PlayPreviousButton from "@/components/buttons/playPreviousButtom";
import QueueButton from "@/components/buttons/queueButton";
import BubbleSlider from "@/components/playback/videoPlayer/bubbleSlider";
import { endsAt, secToTicks } from "@/utils/date/time";
import { useApiInContext } from "@/utils/store/api";
import { usePlaybackStore } from "@/utils/store/playback";
import CaptionsButton from "./buttons/CaptionsButton";
import ChaptersListButton from "./buttons/ChaptersListButton";
import ForwardButton from "./buttons/ForwardButton";
import FullscreenButton from "./buttons/FullscreenButton";
import NextChapterButton from "./buttons/NextChapterButton";
import PlayPauseButton from "./buttons/PlayPauseButton";
import PrevChapterButton from "./buttons/PrevChapterButton";
import RewindButton from "./buttons/RewindButton";
import VideoPlayerSettingsMenu from "./settingsMenu";
import "./controls.scss";
import { clearQueue } from "@/utils/store/queue";
import ProgressDislay from "./ProgressDisplay";
/**
* Constant for the volume change interval when using the mouse wheel.
* This value determines how much the volume will change with each scroll step.
*/
const VOLUME_SCROLL_INTERVAL = 0.02;
type VideoPlayerControlsProps = {
isVisible: boolean;
onHover?: (event: MouseEvent<HTMLDivElement>) => void;
onLeave?: (event: MouseEvent<HTMLDivElement>) => void;
};
const VideoPlayerControls = ({
isVisible,
onHover,
onLeave,
}: VideoPlayerControlsProps) => {
const playerOSDRef = useRef<HTMLDivElement>(null);
const api = useApiInContext((state) => state.api);
const {
mediaSourceId,
itemId,
itemDuration,
itemName,
episodeTitle,
playsessionId,
isPlayerPlaying,
toggleIsPlaying,
toggleIsPlayerFullscreen,
isUserSeeking,
// seekValue,
isPlayerMuted,
volume,
toggleIsPlayerMuted,
increaseVolumeByStep,
decreaseVolumeByStep,
getCurrentTime,
} = usePlaybackStore(
useShallow((state) => ({
mediaSourceId: state.mediaSource.id,
itemChapters: state.metadata.item.Chapters,
itemId: state.metadata.item.Id,
itemDuration: state.metadata.itemDuration,
itemName: state.metadata.itemName,
episodeTitle: state.metadata.episodeTitle,
// mediaSegments: state.metadata.mediaSegments,
isPlayerPlaying: state.playerState.isPlayerPlaying,
playsessionId: state.playsessionId,
toggleIsPlaying: state.toggleIsPlaying,
toggleIsPlayerFullscreen: state.toggleIsPlayerFullscreen,
isUserSeeking: state.playerState.isUserSeeking,
seekValue: state.playerState.seekValue,
isPlayerMuted: state.playerState.isPlayerMuted,
volume: state.playerState.volume,
toggleIsPlayerMuted: state.toggleIsPlayerMuted,
increaseVolumeByStep: state.increaseVolumeByStep,
decreaseVolumeByStep: state.decreaseVolumeByStep,
getCurrentTime: state.getCurrentTime,
})),
);
// Volume control with mouse wheel
useEffect(() => {
const handleMouseWheel = (event: WheelEvent) => {
if (event.deltaY < 0) {
increaseVolumeByStep(VOLUME_SCROLL_INTERVAL);
} else if (event.deltaY > 0) {
decreaseVolumeByStep(VOLUME_SCROLL_INTERVAL);
}
};
const currentRef = playerOSDRef.current;
// attach the event listener
currentRef?.addEventListener("wheel", handleMouseWheel);
// remove the event listener
return () => {
currentRef?.removeEventListener("wheel", handleMouseWheel);
};
}, [increaseVolumeByStep, decreaseVolumeByStep]);
const [clickTimeout, setClickTimeout] = useState<NodeJS.Timeout | null>(null);
const [settingsMenuRef, setSettingsMenuRef] =
useState<HTMLButtonElement | null>(null);
// const creditInfo = mediaSegments?.Items?.find(
// (segment) => segment.Type === "Outro",
// );
// Credits and Next Episode Card
// const [forceShowCredits, setForceShowCredits] = useState(false);
// const showUpNextCard = useMemo(() => {
// if (queue?.[currentQueueItemIndex]?.Id === queue?.[queue.length - 1]?.Id) {
// return false; // Check if the current playing episode is last episode in queue
// }
// if (creditInfo) {
// if (
// currentTime >= (creditInfo.StartTicks ?? currentTime + 1) &&
// currentTime < (creditInfo.EndTicks ?? 0)
// )
// return true;
// }
// if (
// Math.ceil(ticksToSec(itemDuration) - ticksToSec(currentTime)) <= 30 &&
// Math.ceil(ticksToSec(itemDuration) - ticksToSec(currentTime)) > 0
// ) {
// return true;
// }
// return false;
// }, [currentTime, creditInfo, itemDuration, queue, currentQueueItemIndex]);
const handleExitPlayer = useCallback(async () => {
appWindow.getCurrent().setFullscreen(false);
history.back();
if (!api) {
throw Error("API is not available, cannot report playback stopped.");
}
// Report Jellyfin server: Playback has ended/stopped
getPlaystateApi(api).reportPlaybackStopped({
playbackStopInfo: {
Failed: false,
ItemId: itemId,
MediaSourceId: mediaSourceId,
PlaySessionId: playsessionId,
PositionTicks: secToTicks(getCurrentTime() ?? 0),
},
});
usePlaybackStore.setState(usePlaybackStore.getInitialState());
clearQueue();
}, [api, mediaSourceId, playsessionId, itemId]);
return (
<motion.div
className={
isVisible || isUserSeeking || !isPlayerPlaying
? "video-player-osd hovering"
: "video-player-osd"
}
onMouseEnter={onHover}
onMouseLeave={onLeave}
ref={playerOSDRef}
initial={{
opacity: 0,
}}
animate={{
opacity: isVisible || isUserSeeking || !isPlayerPlaying ? 1 : 0,
}}
style={{
zIndex: 2,
}}
onClick={(event) => {
if (event.currentTarget !== event.target) {
return;
}
if (event.detail === 1) {
setClickTimeout(
setTimeout(() => {
toggleIsPlaying();
}, 200),
);
} else if (event.detail === 2 && clickTimeout) {
clearTimeout(clickTimeout);
toggleIsPlayerFullscreen();
}
}}
>
<div className="video-player-osd-header flex flex-justify-spaced-between flex-align-center">
<IconButton onClick={handleExitPlayer}>
<span className="material-symbols-rounded">arrow_back</span>
</IconButton>
<IconButton onClick={(e) => setSettingsMenuRef(e.currentTarget)}>
<span className="material-symbols-rounded">settings</span>
</IconButton>
<VideoPlayerSettingsMenu
settingsMenuRef={settingsMenuRef}
handleClose={() => setSettingsMenuRef(null)}
/>
</div>
<div className="video-player-osd-info">
<div>
<Typography variant="h4" fontWeight={500} mb={2}>
{String(itemName)}
</Typography>
{episodeTitle && (
<Typography variant="h6" fontWeight={300} mt={1}>
{String(episodeTitle)}
</Typography>
)}
</div>
<div className="video-player-osd-controls">
<div className="video-player-osd-controls-timeline">
<BubbleSlider />
<ProgressDislay />
</div>
<div className="flex flex-row flex-justify-spaced-between">
<div className="video-player-osd-controls-buttons">
<PlayPreviousButton />
<RewindButton />
<PrevChapterButton />
<PlayPauseButton />
<NextChapterButton />
<ForwardButton />
<PlayNextButton />
<Typography variant="subtitle1">
{endsAt(itemDuration)}
</Typography>
</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,
});
}}
/>
</motion.div> */}
{/* TODO: Volume menu */}
<IconButton
onClick={toggleIsPlayerMuted}
// onMouseMoveCapture={() => {
// setShowVolumeControl(true);
// }}
>
<span className="material-symbols-rounded">
{isPlayerMuted
? "volume_off"
: volume < 0.4
? "volume_down"
: "volume_up"}
</span>
</IconButton>
<QueueButton />
<ChaptersListButton />
<CaptionsButton />
<FullscreenButton />
</div>
</div>
</div>
</div>
</motion.div>
);
};
export default VideoPlayerControls;
@@ -0,0 +1,138 @@
import { MenuItem, Popover, TextField } from "@mui/material";
import { toNumber } from "lodash";
import React, {
type ChangeEventHandler,
useCallback,
useMemo,
useTransition,
} from "react";
import { useShallow } from "zustand/shallow";
import { useApiInContext } from "@/utils/store/api";
import {
changeAudioTrack,
changeSubtitleTrack,
usePlaybackStore,
} from "@/utils/store/playback";
type VideoPlayerSettingsMenuProps = {
settingsMenuRef: HTMLButtonElement | null;
handleClose: () => void;
};
const VideoPlayerSettingsMenu = ({
settingsMenuRef,
handleClose,
}: VideoPlayerSettingsMenuProps) => {
const settingsMenuOpen = useMemo(() => {
return Boolean(settingsMenuRef);
}, [settingsMenuRef]);
const api = useApiInContext((state) => state.api);
const { mediaSource, setIsBuffering } = usePlaybackStore(
useShallow((state) => ({
mediaSource: state.mediaSource,
setIsBuffering: state.setIsBuffering,
})),
);
const [subtitleIsChanging, startSubtitleChange] = useTransition();
const handleSubtitleChange: ChangeEventHandler<
HTMLInputElement | HTMLTextAreaElement
> = useCallback(
(e) => {
startSubtitleChange(() => {
if (mediaSource.subtitle.allTracks) {
changeSubtitleTrack(
toNumber(e.target.value),
mediaSource.subtitle.allTracks,
);
handleClose();
}
});
},
[mediaSource.subtitle?.allTracks],
);
const [audioTackIsChanging, startAudioTrackChange] = useTransition();
const handleAudioTrackChange: ChangeEventHandler<
HTMLInputElement | HTMLTextAreaElement
> = (e) => {
// setPlaying(false);
startAudioTrackChange(() => {
if (api && mediaSource.audio.allTracks) {
changeAudioTrack(toNumber(e.target.value), api);
handleClose();
setIsBuffering(true);
}
});
// setPlaying(true);
};
return (
<Popover
anchorEl={settingsMenuRef}
open={settingsMenuOpen}
onClose={handleClose}
slotProps={{
paper: {
style: {
maxHeight: "20em",
display: "flex",
flexDirection: "column",
gap: "1em",
width: "24em",
padding: "1em",
borderRadius: "12px",
},
className: "glass",
},
}}
anchorOrigin={{
vertical: "bottom",
horizontal: "right",
}}
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
>
<TextField
select
label="Audio"
variant="outlined"
value={mediaSource.audio?.track}
onChange={handleAudioTrackChange}
fullWidth
disabled={audioTackIsChanging}
>
{mediaSource.audio?.allTracks?.map((sub) => (
<MenuItem key={sub.Index} value={sub.Index}>
{sub.DisplayTitle}
</MenuItem>
))}
</TextField>
<TextField
select
label="Subtitles"
variant="outlined"
value={mediaSource.subtitle?.track}
onChange={handleSubtitleChange}
fullWidth
disabled={mediaSource.subtitle?.track === -2 || subtitleIsChanging}
>
<MenuItem key={-1} value={-1}>
No Subtitle
</MenuItem>
{mediaSource.subtitle?.allTracks?.map((sub) => (
<MenuItem key={sub.Index} value={sub.Index}>
{sub.DisplayTitle}
</MenuItem>
))}
</TextField>
</Popover>
);
};
export default VideoPlayerSettingsMenu;
+35 -37
View File
@@ -1,76 +1,74 @@
import * as generatedClient from "@jellyfin/sdk/lib/generated-client";
import {
BaseItemKind,
type CollectionType,
} from "@jellyfin/sdk/lib/generated-client";
import React from "react";
export const getTypeIcon = (
icon:
| generatedClient.BaseItemKind
| generatedClient.CollectionType
| "Home"
| "User"
| "universal",
icon: BaseItemKind | CollectionType | "Home" | "User" | "universal",
) => {
switch (icon) {
case "Home":
return <div className="material-symbols-rounded">home</div>;
case generatedClient.BaseItemKind.Audio:
case BaseItemKind.Audio:
return <div className="material-symbols-rounded">mic</div>;
case generatedClient.BaseItemKind.AudioBook:
case BaseItemKind.AudioBook:
return <div className="material-symbols-rounded">speech_to_text</div>;
case generatedClient.BaseItemKind.Book:
case BaseItemKind.Book:
return <div className="material-symbols-rounded">book</div>;
case "boxsets":
case generatedClient.BaseItemKind.BoxSet:
case BaseItemKind.BoxSet:
return <div className="material-symbols-rounded">video_library</div>;
case "livetv":
case generatedClient.BaseItemKind.TvProgram:
case generatedClient.BaseItemKind.TvChannel:
case generatedClient.BaseItemKind.Program:
case generatedClient.BaseItemKind.Recording:
case generatedClient.BaseItemKind.LiveTvChannel:
case generatedClient.BaseItemKind.LiveTvProgram:
case generatedClient.BaseItemKind.ChannelFolderItem:
case generatedClient.BaseItemKind.Channel:
case BaseItemKind.TvProgram:
case BaseItemKind.TvChannel:
case BaseItemKind.Program:
case BaseItemKind.Recording:
case BaseItemKind.LiveTvChannel:
case BaseItemKind.LiveTvProgram:
case BaseItemKind.ChannelFolderItem:
case BaseItemKind.Channel:
return (
<div className="material-symbols-rounded">settings_input_antenna</div>
);
case "tvshows":
case generatedClient.BaseItemKind.Season:
case generatedClient.BaseItemKind.Series:
case generatedClient.BaseItemKind.Episode:
case BaseItemKind.Season:
case BaseItemKind.Series:
case BaseItemKind.Episode:
return <div className="material-symbols-rounded">tv_gen</div>;
case "playlists":
case generatedClient.BaseItemKind.Playlist:
case generatedClient.BaseItemKind.PlaylistsFolder:
case generatedClient.BaseItemKind.ManualPlaylistsFolder:
case BaseItemKind.Playlist:
case BaseItemKind.PlaylistsFolder:
case BaseItemKind.ManualPlaylistsFolder:
return <div className="material-symbols-rounded">queue_music</div>;
case "movies":
case generatedClient.BaseItemKind.Movie:
case BaseItemKind.Movie:
return <div className="material-symbols-rounded">movie</div>;
case generatedClient.BaseItemKind.MusicAlbum:
case BaseItemKind.MusicAlbum:
return <div className="material-symbols-rounded">album</div>;
case generatedClient.BaseItemKind.MusicArtist:
case BaseItemKind.MusicArtist:
return <div className="material-symbols-rounded">artist</div>;
case generatedClient.BaseItemKind.Genre:
case generatedClient.BaseItemKind.MusicGenre:
case BaseItemKind.Genre:
case BaseItemKind.MusicGenre:
return <div className="material-symbols-rounded">domino_mask</div>;
case "musicvideos":
case generatedClient.BaseItemKind.MusicVideo:
case BaseItemKind.MusicVideo:
return <div className="material-symbols-rounded">music_video</div>;
case "User":
case generatedClient.BaseItemKind.Person:
case BaseItemKind.Person:
return <div className="material-symbols-rounded">person</div>;
case generatedClient.BaseItemKind.Photo:
case BaseItemKind.Photo:
return <div className="material-symbols-rounded">image</div>;
case "photos":
case generatedClient.BaseItemKind.PhotoAlbum:
case BaseItemKind.PhotoAlbum:
return <div className="material-symbols-rounded">photo_library</div>;
case "universal":
case generatedClient.BaseItemKind.Studio:
case BaseItemKind.Studio:
return <div className="material-symbols-rounded">category</div>;
case "trailers":
case generatedClient.BaseItemKind.Trailer:
case BaseItemKind.Trailer:
return <div className="material-symbols-rounded">smart_display</div>;
case generatedClient.BaseItemKind.Video:
case BaseItemKind.Video:
return <div className="material-symbols-rounded">theaters</div>;
case "music":
return <div className="material-symbols-rounded">library_music</div>;
+410 -600
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-61
View File
@@ -66,65 +66,4 @@ video {
&::cue(i) {
text-shadow: 0 2px 10px rgb(0 0 0 / 0.8);
}
}
.video-player {
background: black;
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
&-osd {
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
cursor: none;
display: flex;
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));
&.hovering {
cursor: default;
}
&-controls {
&-progress {
display: flex;
flex-direction: column;
gap: 0.2em;
align-items: stretch;
justify-content: center;
margin-bottom: 0.5em;
&-text {
display: flex;
align-items: stretch;
justify-content: space-between;
}
&-bubble{
width: 14em;
top: 0;
left: 0;
transform-origin:bottom center;
transform: translate(var(--left, 0), var(--top, 0));
position: fixed;
}
}
&-buttons {
display: flex;
gap: 0.4em;
align-items: center;
}
}
.MuiSlider-valueLabel {
padding: 0;
background: transparent;
overflow: hidden;
border-radius: $border-radius-default;
border: 1.2px solid rgb(255 255 255 / 0.1);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Formats a given ticks value into a human-readable time string.
* @param ticks - The ticks value to be formatted, typically in 100-nanosecond intervals.
* @returns Formatted time string in the format HH:MM:SS.
*/
const ticksDisplay = (ticks: number) => {
const time = Math.round(ticks / 10000);
let formatedTime = "";
let timeSec = Math.floor(time / 1000);
let timeMin = Math.floor(timeSec / 60);
timeSec -= timeMin * 60;
timeSec = timeSec === 0 ? 0o0 : timeSec;
const timeHr = Math.floor(timeMin / 60);
timeMin -= timeHr * 60;
formatedTime = `${timeHr.toLocaleString([], {
minimumIntegerDigits: 2,
useGrouping: false,
})}:${timeMin.toLocaleString([], {
minimumIntegerDigits: 2,
useGrouping: false,
})}:${timeSec.toLocaleString([], {
minimumIntegerDigits: 2,
useGrouping: false,
})}`;
return formatedTime;
};
export default ticksDisplay;
+597 -141
View File
@@ -7,8 +7,12 @@ import type {
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import { getMediaSegmentsApi } from "@jellyfin/sdk/lib/utils/api/media-segments-api";
import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api";
import { WebviewWindow as appWindow } from "@tauri-apps/api/webviewWindow";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { shallow } from "zustand/shallow";
import { createWithEqualityFn } from "zustand/traditional";
import { secToTicks, ticksToSec } from "../date/time";
import getSubtitle from "../methods/getSubtitles";
import playbackProfile from "../playback-profiles";
import type audioPlaybackInfo from "../types/audioPlaybackInfo";
@@ -16,9 +20,7 @@ import type subtitlePlaybackInfo from "../types/subtitlePlaybackInfo";
import { generateAudioStreamUrl, playAudio } from "./audioPlayback";
import useQueue, { setQueue } from "./queue";
type PlaybackStore = {
itemName: string | React.Component | undefined | null;
episodeTitle: string | React.Component;
type PlaybackStoreState = {
mediaSource: {
videoTrack: number;
audioTrack: number;
@@ -28,123 +30,549 @@ type PlaybackStore = {
audio: audioPlaybackInfo;
};
playbackStream: string;
userId: string;
startPosition: number;
itemDuration: number;
item: BaseItemDto | null;
playsessionId: string | undefined | null;
intro: MediaSegmentDtoQueryResult | undefined;
volume: number | undefined;
metadata: {
itemName: string;
episodeTitle?: string;
isEpisode: boolean;
/**
* Duration of the item in C# ticks
* This is used to calculate the progress bar and the total duration of the item
*/
itemDuration: number;
item: BaseItemDto;
mediaSegments?: MediaSegmentDtoQueryResult;
userDataLastPlayedPositionTicks?: number;
};
playerState: {
/**
* Persistent volume level between player instances
*/
volume: number;
/**
* Prop for ReactPlayer to mute and unmute audio volume regardless of the volume value
*/
isPlayerMuted: boolean;
isPlayerPlaying: boolean;
/**
* Used to check if ReactPlayer component has finished initial fetch of playbackStream
* true -> Player is ready for playback
* false -> Player is not ready for playback/is still fetching data/possible error while fetching
*/
isPlayerReady: boolean;
isBuffering: boolean;
/**
* Current playback time in C# ticks
* This is used to update the playback time in the UI
* Initially should be set to UserData.PlaybackPositionTicks in seconds
* Source: ReactPlayer's onProgress event
* */
currentTime: number;
/**
* Used to toggle the fullscreen state of the player
* This is used to toggle the fullscreen state of the player
* This should be set to true when the user clicks on the fullscreen button
*/
isPlayerFullscreen: boolean;
/**
* Used to see if user is seeking/scrubbing progress bar
* Used to temporarily switch to seek progress for the progress bar
*/
isUserSeeking: boolean;
/**
* Seek value
* This value should be in C# ticks
*/
seekValue: number;
/**
* Used to display controls/see if user is hovering the media player
*/
isUserHovering: boolean;
/**
* Used to show the buffering spinner in the UI
* This should be set to true when the player is buffering
*/
isLoading: boolean;
};
/**
* Index of the next segment to be played
*/
nextSegmentIndex: number;
/**
* Id of the active segment
* Set if null if no segment is active
*/
activeSegmentId: string | null;
/**
* User id of the user who is currently playing the item
*/
userId: string;
/**
* Volume change indicator
* This is used to show the volume change indicator in the UI
*/
isVolumeInidcatorVisible: boolean;
volumeIndicatorVisibleTimeoutId: NodeJS.Timeout | null;
};
export const usePlaybackStore = createWithEqualityFn<PlaybackStore>(
() => ({
itemName: undefined!,
episodeTitle: "",
type PlaybackStoreActions = {
// Player state related actions
/**
* Set the volume of the player
* This is used to set the volume of the player
* This should be set to a value between 0 and 1
*/
setVolume: (volume: number) => void;
/**
* Increase the volume of the player by a step
* This is used to increase the volume of the player by a step
* This should be set to a value between 0 and 1
*/
increaseVolumeByStep: (step: number) => void;
/**
* Decrease the volume of the player by a step
* This is used to decrease the volume of the player by a step
* This should be set to a value between 0 and 1
*/
decreaseVolumeByStep: (step: number) => void;
/**
* Toggle the player state between playing and paused
* This is used to toggle the player state
*/
toggleIsPlaying: () => void;
/**
* Set the player state to playing
*/
setIsPlaying: (isPlaying: boolean) => void;
/**
* Set the player state to buffering
* This is used to show the buffering spinner in the UI
* This should be set to true when the player is buffering
*/
setIsBuffering: (isBuffering: boolean) => void;
/**
* Set the current time of the player
*/
setCurrentTime: (currentTime: number) => void;
/**
* Set the player state to ready
* This is used to check if the player is ready for playback
* This should be set to true when the player has finished fetching the playback stream
*/
setPlayerReady: (isPlayerReady: boolean) => void;
/**
* Toggle the player state to fullscreen
* This is used to toggle the fullscreen state of the player
* This should be set to true when the user clicks on the fullscreen button
*/
toggleIsPlayerFullscreen: () => void;
/**
* Set the user hover state
* This is used to show/hide the player controls
* This should be set to true when the user hovers over the player
* This should be set to false when the user stops hovering over the player
*/
setIsUserHovering: (isUserHovering: boolean) => void;
/**
* Set the user seeking state
* This is used to temporarily switch to seek progress for the progress bar
* This should be set to true when the user is seeking/scrubbing the progress bar
*/
setIsUserSeeking: (isUserSeeking: boolean) => void;
/**
* Set the seek value
* This is used to update the seek value in the UI
* This should be set to the value of the progress bar when the user is seeking/scrubbing
* This value should be in C# ticks
*/
setSeekValue: (seekValue: number) => void;
/**
* Toggle the player muted state
* This is used to toggle the player muted state
*/
toggleIsPlayerMuted: () => void;
/**
* Set the loading state of the player
* This is used to show/hide the loading spinner in the UI
* This should be set to true when the player is loading
* This should be set to false when the player has finished loading
*/
setIsLoading: (isLoading: boolean) => void;
setPlayerState: (playerState: PlaybackStoreState["playerState"]) => void;
// Playback information related actions
setMetadata: (
itemName: string,
episodeTitle: string,
isEpisode: boolean,
itemDuration: number,
item: BaseItemDto,
mediaSegments?: MediaSegmentDtoQueryResult,
userDataLastPlayedPositionTicks?: number,
) => void;
setMediaSource: (
videoTrack: number,
audioTrack: number,
container: string,
id: string | undefined,
subtitle: subtitlePlaybackInfo,
audio: audioPlaybackInfo,
) => void;
setPlaybackStream: (playbackStream: string) => void;
setPlaysessionId: (playsessionId: string | undefined | null) => void;
setUserId: (userId: string) => void;
setActiveSegment: (segmentIndex: number) => void;
clearActiveSegment: () => void;
/**
* Trigger volume change indicator
* This is used to show the volume change indicator in the UI
*/
tiggerVolumeIndicator: () => void;
// ReactPlayer related actions
_playerActions: {
seekTo: (seconds: number) => void;
getCurrentTime: () => number;
};
registerPlayerActions: (
actions: PlaybackStoreActions["_playerActions"],
) => void;
seekTo: (seconds: number) => void;
seekForward: (seconds: number) => void;
seekBackward: (seconds: number) => void;
getCurrentTime: () => number;
seekToNextChapter: () => void;
seekToPrevChapter: () => void;
handleStartSeek: (ticks: number) => void;
handleStopSeek: (ticks: number) => void;
/**
* Skip current media segment
*/
skipSegment: () => void;
};
export const usePlaybackStore = create<
PlaybackStoreState & PlaybackStoreActions
>()(
immer((set, get) => ({
mediaSource: {
videoTrack: 0,
audioTrack: 0,
container: "",
id: undefined,
subtitle: {
enable: false,
track: undefined!,
format: "ass",
allTracks: undefined,
url: undefined,
},
audio: {
track: undefined!,
allTracks: undefined,
videoTrack: undefined!,
audioTrack: undefined!,
container: undefined!,
id: undefined!,
subtitle: undefined!,
audio: undefined!,
},
playbackStream: undefined!,
playsessionId: undefined!,
metadata: {
itemName: undefined!,
episodeTitle: undefined,
isEpisode: false,
itemDuration: undefined!,
item: undefined!,
mediaSegments: undefined,
userDataLastPlayedPositionTicks: 0,
},
playerState: {
volume: 1,
isPlayerMuted: false,
isPlayerPlaying: true,
isPlayerReady: false,
isPlayerFullscreen: false,
isUserHovering: false,
isBuffering: true,
currentTime: undefined!,
isUserSeeking: false,
seekValue: 0,
isLoading: true,
},
userId: undefined!,
// -- MediaSegment skip feature --
nextSegmentIndex: 0,
activeSegmentId: null,
// -- Volume change indicator --
isVolumeInidcatorVisible: false,
volumeIndicatorVisibleTimeoutId: null,
// -- Player state related actions --
setVolume: (volume) => {
if (volume < 0 || volume > 1) {
console.warn("Volume must be between 0 and 1");
}
set((state) => {
state.playerState.volume = volume;
state.playerState.isPlayerMuted = volume === 0; // Mute if volume is 0
});
get().tiggerVolumeIndicator(); // Trigger volume change indicator
},
increaseVolumeByStep: (step) => {
set((state) => {
state.playerState.volume = Math.min(
1,
Math.max(0, state.playerState.volume + step),
);
});
get().tiggerVolumeIndicator(); // Trigger volume change indicator
},
decreaseVolumeByStep: (step) => {
set((state) => {
state.playerState.volume = Math.min(
1,
Math.max(0, state.playerState.volume - step),
);
});
get().tiggerVolumeIndicator(); // Trigger volume change indicator
},
toggleIsPlaying: () => {
set((state) => {
state.playerState.isPlayerPlaying = !state.playerState.isPlayerPlaying;
});
},
setIsPlaying: (isPlaying) =>
set((state) => {
state.playerState.isPlayerPlaying = isPlaying;
}),
setIsBuffering: (isBuffering) =>
set((state) => {
state.playerState.isBuffering = isBuffering;
}),
setCurrentTime: (currentTime) =>
set((state) => {
state.playerState.currentTime = currentTime;
}),
setPlayerReady: (isPlayerReady) =>
set((state) => {
state.playerState.isPlayerReady = isPlayerReady;
}),
setMetadata: (
itemName: string,
episodeTitle: string,
isEpisode: boolean,
itemDuration: number,
item: BaseItemDto,
mediaSegments?: MediaSegmentDtoQueryResult,
) =>
set((state) => {
state.metadata.itemName = itemName;
state.metadata.episodeTitle = episodeTitle;
state.metadata.isEpisode = isEpisode;
state.metadata.itemDuration = itemDuration;
state.metadata.item = item;
state.metadata.mediaSegments = mediaSegments;
}),
setMediaSource: (
videoTrack: number,
audioTrack: number,
container: string,
id: string | undefined,
subtitle: subtitlePlaybackInfo,
audio: audioPlaybackInfo,
) =>
set((state) => {
state.mediaSource.videoTrack = videoTrack;
state.mediaSource.audioTrack = audioTrack;
state.mediaSource.container = container;
state.mediaSource.id = id;
state.mediaSource.subtitle = subtitle;
state.mediaSource.audio = audio;
}),
setPlaybackStream: (playbackStream: string) =>
set((state) => {
state.playbackStream = playbackStream;
}),
setPlaysessionId: (playsessionId) =>
set((state) => {
state.playsessionId = playsessionId;
}),
toggleIsPlayerFullscreen: async () => {
await appWindow
.getCurrent()
.setFullscreen(!get().playerState.isPlayerFullscreen);
set((state) => {
state.playerState.isPlayerFullscreen =
!state.playerState.isPlayerFullscreen;
});
},
setIsUserHovering: (isUserHovering) =>
set((state) => {
state.playerState.isUserHovering = isUserHovering;
}),
setIsUserSeeking: (isUserSeeking) =>
set((state) => {
state.playerState.isUserSeeking = isUserSeeking;
}),
setSeekValue: (seekValue) =>
set((state) => {
state.playerState.seekValue = seekValue;
}),
toggleIsPlayerMuted: () =>
set((state) => {
state.playerState.isPlayerMuted = !state.playerState.isPlayerMuted;
}),
setIsLoading: (isLoading) =>
set((state) => {
state.playerState.isLoading = isLoading;
}),
setPlayerState: (playerState) =>
set((state) => ({
...state,
playerState: {
...state.playerState,
...playerState,
},
})),
setUserId: (userId) =>
set(() => ({
userId: userId,
})),
setActiveSegment: (segmentIndex) => {
const segment = get().metadata.mediaSegments?.Items?.[segmentIndex];
set((state) => {
state.nextSegmentIndex = segmentIndex + 1;
state.activeSegmentId = segment?.Id ?? null;
});
},
clearActiveSegment: () => {
set((state) => {
state.activeSegmentId = null;
});
},
// -- Volume change indicator Action --
tiggerVolumeIndicator: () => {
const timeoutId = get().volumeIndicatorVisibleTimeoutId;
if (timeoutId) {
clearTimeout(timeoutId); // Volume indicator is already visible
}
set((state) => {
state.isVolumeInidcatorVisible = true;
state.volumeIndicatorVisibleTimeoutId = setTimeout(() => {
set((state) => {
state.isVolumeInidcatorVisible = false;
});
}, 1000);
});
},
// -- ReactPlayer related actions --
_playerActions: {
seekTo: (seconds: number) =>
console.warn(
"ReactPlayer has not yet initialized. Please wait until the player is ready to seek.",
),
getCurrentTime: () => {
console.warn(
"ReactPlayer has not yet initialized. Please wait until the player is ready to get current time.",
);
return 0;
},
},
enableSubtitle: true,
playbackStream: "",
userId: "",
startPosition: 0,
itemDuration: 0,
item: null,
playsessionId: "",
intro: undefined,
volume: 1,
}),
shallow,
registerPlayerActions: (actions) =>
set({
_playerActions: actions,
}),
seekTo: (seconds: number) => {
const playerActions = get()._playerActions;
playerActions.seekTo(seconds);
},
seekForward: (seconds: number) => {
const playerActions = get()._playerActions;
const currentTime = playerActions.getCurrentTime();
playerActions.seekTo(currentTime + seconds);
},
seekBackward: (seconds: number) => {
const playerActions = get()._playerActions;
const currentTime = playerActions.getCurrentTime();
playerActions.seekTo(Math.max(0, currentTime - seconds));
},
getCurrentTime: () => {
const playerActions = get()._playerActions;
return playerActions.getCurrentTime();
},
seekToNextChapter: () => {
const playerActions = get()._playerActions;
const next = get().metadata.item?.Chapters?.filter((chapter) => {
if (
(chapter.StartPositionTicks ?? 0) > playerActions.getCurrentTime()
) {
return true;
}
})[0];
playerActions.seekTo(ticksToSec(next?.StartPositionTicks ?? 0));
},
seekToPrevChapter: () => {
const playerActions = get()._playerActions;
const chapters = get().metadata.item.Chapters?.filter((chapter) => {
if (
(chapter.StartPositionTicks ?? 0) <=
secToTicks(playerActions.getCurrentTime())
) {
return true;
}
});
if (!chapters?.length) {
playerActions.seekTo(0);
}
if (chapters?.length === 1) {
playerActions.seekTo(ticksToSec(chapters[0].StartPositionTicks ?? 0));
} else if ((chapters?.length ?? 0) > 1) {
playerActions.seekTo(
ticksToSec(chapters?.[chapters.length - 2].StartPositionTicks ?? 0),
);
}
},
skipSegment: () => {
const activeSegmentId = get().activeSegmentId;
const activeSegment = get().metadata.mediaSegments?.Items?.find(
(s) => s.Id === activeSegmentId,
);
if (!activeSegment) {
console.warn("No segment to skip");
return;
}
get()._playerActions.seekTo(activeSegment.EndTicks ?? 0);
},
handleStartSeek: (ticks) => {
set((state) => {
state.playerState.isUserSeeking = true;
state.playerState.seekValue = ticks;
});
},
handleStopSeek: (ticks) => {
const playerActions = get()._playerActions;
playerActions.seekTo(ticksToSec(ticks));
// Update current time to the new seek value
set((state) => {
state.playerState.isUserSeeking = false;
state.playerState.currentTime = ticks;
});
},
})),
);
export const playItem = (
itemName: string | React.Component | undefined | null,
episodeTitle: string,
videoTrack: number,
audioTrack: number,
container: string,
playbackStream: string,
userId: string,
startPosition: number | undefined | null,
itemDuration: number | undefined | null,
item: BaseItemDto,
queue: BaseItemDto[] | undefined | null,
queueItemIndex: number,
mediaSourceId: string | undefined | null,
playsessionId: string | undefined | null,
subtitle: subtitlePlaybackInfo | undefined,
intro: MediaSegmentDtoQueryResult | undefined,
audio: audioPlaybackInfo,
volume: number | undefined = 1,
) => {
console.log({
itemName,
episodeTitle,
mediaSource: {
videoTrack,
audioTrack,
container,
id: mediaSourceId,
subtitle,
audio,
},
playbackStream,
userId,
startPosition,
itemDuration,
item,
playsessionId,
intro,
volume,
export const playItem = (args: {
mediaSource: PlaybackStoreState["mediaSource"];
playbackStream: PlaybackStoreState["playbackStream"];
playsessionId: PlaybackStoreState["playsessionId"];
metadata: PlaybackStoreState["metadata"];
userDataPlayedPositionTicks: number;
userId: string;
queueItems: BaseItemDto[];
queueItemIndex: number;
}) => {
usePlaybackStore.setState((state) => {
state.mediaSource = args.mediaSource;
state.playbackStream = args.playbackStream;
state.playsessionId = args.playsessionId;
state.metadata = args.metadata;
state.playerState.currentTime = args.userDataPlayedPositionTicks;
state.userId = args.userId;
});
if (!queue) {
throw new Error("No queue found");
}
if (!mediaSourceId) {
throw new Error("No media source id found");
}
if (!subtitle) {
throw new Error("No subtitle config found");
}
usePlaybackStore.setState({
itemName,
episodeTitle,
mediaSource: {
videoTrack,
audioTrack,
container,
id: mediaSourceId,
subtitle,
audio,
},
playbackStream,
userId,
startPosition: startPosition ?? 0,
itemDuration: itemDuration ?? 0,
item,
playsessionId,
intro,
volume,
});
setQueue(queue, queueItemIndex);
setQueue(args.queueItems, args.queueItemIndex ?? 0);
};
export const playItemFromQueue = async (
@@ -197,6 +625,18 @@ export const playItemFromQueue = async (
console.error("No media source id found");
return;
}
if (!item) {
throw new Error("Item is undefined in playItemFromQueue");
}
if (!item.Name) {
throw new Error("Item name is undefined in playItemFromQueue");
}
if (!item.RunTimeTicks) {
throw new Error("Item run time ticks is undefined in playItemFromQueue");
}
if (!item.Id) {
throw new Error("Item id is undefined in playItemFromQueue");
}
const mediaSource = (
await getMediaInfoApi(api).getPostedPlaybackInfo({
@@ -217,9 +657,13 @@ export const playItemFromQueue = async (
},
})
).data;
if (!mediaSource.MediaSources?.[0]?.Id) {
throw new Error("Media source is undefined in playItemFromQueue");
}
let itemName = item.Name;
let episodeTitle = "";
if (item.SeriesId) {
if (item.SeriesId && item.SeriesName) {
itemName = item.SeriesName;
episodeTitle = `S${item.ParentIndexNumber ?? 0}:E${
item.IndexNumber ?? 0
@@ -264,7 +708,7 @@ export const playItemFromQueue = async (
(value) => value.Type === "Video",
);
const introInfo = (
const mediaSegments = (
await getMediaSegmentsApi(api).getItemSegments({
itemId: item.Id ?? "",
})
@@ -280,25 +724,40 @@ export const playItemFromQueue = async (
},
});
playItem(
itemName,
episodeTitle,
videoTrack?.[0].Index ?? 0,
mediaSource.MediaSources?.[0].DefaultAudioStreamIndex ?? 0,
mediaSource?.MediaSources?.[0].Container ?? "mkv",
playbackUrl,
playItem({
metadata: {
itemName,
episodeTitle: episodeTitle,
isEpisode: !!item.SeriesId,
itemDuration: item.RunTimeTicks,
item: item,
mediaSegments: mediaSegments,
userDataLastPlayedPositionTicks:
item.UserData?.PlaybackPositionTicks ?? 0,
},
mediaSource: {
videoTrack: videoTrack?.[0]?.Index ?? 0,
audioTrack: audio.track,
container: mediaSource.MediaSources?.[0].Container ?? "",
id: mediaSource.MediaSources?.[0]?.Id,
subtitle: {
url: subtitle?.url,
track: subtitle?.track ?? -1,
format: subtitle?.format ?? "nosub",
allTracks: mediaSource.MediaSources?.[0].MediaStreams?.filter(
(value) => value.Type === "Subtitle",
),
enable: subtitle?.enable ?? false,
},
audio: audio,
},
playbackStream: playbackUrl,
playsessionId: mediaSource.PlaySessionId,
userDataPlayedPositionTicks: item.UserData?.PlaybackPositionTicks ?? 0,
userId,
item.UserData?.PlaybackPositionTicks,
item.RunTimeTicks,
item,
queueItems,
requestedItemIndex,
mediaSource.MediaSources?.[0]?.Id,
mediaSource.PlaySessionId,
subtitle,
introInfo,
audio,
);
queueItems: queueItems,
queueItemIndex: requestedItemIndex,
});
}
return "playing"; // Return any value to end mutation pending status
@@ -355,26 +814,23 @@ export const toggleSubtitleTrack = () => {
* @param api api instance
* @param startPosition position of videoPlayer during audio track change (this should be in ticks)
*/
export const changeAudioTrack = async (
trackIndex: number,
api: Api,
startPosition: number,
) => {
export const changeAudioTrack = async (trackIndex: number, api: Api) => {
const prevState = usePlaybackStore.getState();
if (!prevState.item?.Id) {
if (!prevState.metadata.item?.Id) {
throw new Error("item is undefined in changeAudioTrack");
}
if (!prevState.item.MediaSources?.[0].Id) {
if (!prevState.metadata.item.MediaSources?.[0].Id) {
throw new Error("Media source id is undefined in changeAudioTrack");
}
const mediaSource = (
await getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex: trackIndex,
subtitleStreamIndex: prevState.mediaSource.subtitle.track,
itemId: prevState.item.Id,
startTimeTicks: prevState.item.UserData?.PlaybackPositionTicks,
itemId: prevState.metadata.item.Id,
startTimeTicks: prevState.metadata.item.UserData?.PlaybackPositionTicks,
userId: prevState.userId,
mediaSourceId: prevState.item.MediaSources?.[0].Id,
mediaSourceId: prevState.metadata.item.MediaSources?.[0].Id,
playbackInfoDto: {
DeviceProfile: playbackProfile,
},
@@ -404,7 +860,7 @@ export const changeAudioTrack = async (
}
prevState.playbackStream = playbackUrl;
prevState.startPosition = startPosition;
// prevState.item = startPosition;
prevState.playsessionId = mediaSource.PlaySessionId;
usePlaybackStore.setState(prevState);