refactor: use reducers in videplayer to manage state instead of individual useState

This commit is contained in:
Prayag Prajapati committed 2025-03-17 20:00:25 +05:30
1 parent 3f5e764cd7
commit d3d5c5ac54
4 files changed
+611 -304

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- <script src="http://localhost:8097"></script> --> <script src="http://localhost:8097"></script>
<title>Blink</title> <title>Blink</title>
<style> <style>
.app-loading { .app-loading {
+331
View File
@@ -0,0 +1,331 @@
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 { 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>;
};
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;
};
const BubbleSlider = ({
itemDuration,
item,
mediaSource,
api,
chapterMarks,
sliderState,
dispatch,
player,
}: BubbleSliderProps) => {
const positionRef = useRef<{ x: number; y: number }>({
x: 0,
y: 0,
});
const popperRef = useRef<Instance>(null);
const areaRef = useRef<HTMLDivElement>(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);
if (popperRef.current != null) {
popperRef.current.update();
}
};
const sliderDisplayFormat = (value: number) => {
const currentChapter = item?.Chapters?.filter((chapter, index) => {
if (index + 1 === item.Chapters?.length) {
return chapter;
}
if (
(item.Chapters?.[index + 1]?.StartPositionTicks ?? value) - value >=
0 &&
(chapter.StartPositionTicks ?? value) - value < 0
) {
return chapter;
}
});
let trickplayResolution: TrickplayInfo | undefined;
const trickplayResolutions = mediaSource.id
? item?.Trickplay?.[mediaSource.id]
: null;
if (trickplayResolutions) {
let bestWidth: number | undefined;
const maxWidth = window.screen.width * window.devicePixelRatio * 0.2;
for (const [_, trickInfo] of Object.entries(trickplayResolutions)) {
if (
!bestWidth ||
(trickInfo.Width &&
((trickInfo.Width < bestWidth && bestWidth > maxWidth) ||
(trickInfo.Width > bestWidth && bestWidth <= maxWidth)))
) {
bestWidth = trickInfo.Width;
}
}
if (bestWidth) {
trickplayResolution = trickplayResolutions[bestWidth];
}
}
if (
trickplayResolution?.TileWidth &&
trickplayResolution.TileHeight &&
trickplayResolution.Width &&
trickplayResolution.Height
) {
const currentTrickplayImage = trickplayResolution?.Interval
? Math.floor(ticksToMs(value) / trickplayResolution?.Interval)
: 0;
const trickplayImageSize =
trickplayResolution?.TileWidth * trickplayResolution?.TileHeight; // this gives the area of a single tile
const trickplayImageOffset = currentTrickplayImage % trickplayImageSize; // this gives the tile index inside a trickplay image
const index = Math.floor(currentTrickplayImage / trickplayImageSize); // this gives the index of trickplay image
const imageOffsetX =
trickplayImageOffset % trickplayResolution?.TileWidth; // this gives the x coordinate of tile in trickplay image
const imageOffsetY = Math.floor(
trickplayImageOffset / trickplayResolution?.TileWidth,
); // this gives the y coordinate of tile in trickplay image
const backgroundOffsetX = -(imageOffsetX * trickplayResolution?.Width);
const backgroundOffsetY = -(imageOffsetY * trickplayResolution?.Height);
const imgUrlParamsObject: Record<string, string> = {
api_key: String(api?.accessToken),
MediaSourceId: mediaSource.id ?? "",
};
const imgUrlParams = new URLSearchParams(imgUrlParamsObject).toString();
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/${item?.Id}/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/${item?.Id}/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>
);
}
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}>
{ticksDisplay(value)}
</Typography>
</div>
);
}
return (
<div className="flex flex-column video-osb-bubble ">
<Typography variant="h6" px="12px" py={1}>
{ticksDisplay(value)}
</Typography>
</div>
);
};
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,
);
},
},
// disablePortal: true,
},
tooltip: {
className: "glass",
style: {
width: "34em",
overflow: "hidden",
padding: "12px",
borderRadius: "20px",
},
},
}}
>
<Slider
value={
sliderState.isSeeking ? sliderState.sliderSeek : sliderState.progress
}
max={itemDuration}
step={1}
onChange={(_, newValue) => {
dispatch({
type: VideoPlayerActionKind.SET_SEEKING,
payload: true,
});
Array.isArray(newValue)
? dispatch({
type: VideoPlayerActionKind.SET_SLIDER_SEEK,
payload: newValue[0],
})
: dispatch({
type: VideoPlayerActionKind.SET_SLIDER_SEEK,
payload: 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,
});
if (Array.isArray(newValue)) {
player.current?.seekTo(ticksToSec(newValue[0]), "seconds");
} else {
player.current?.seekTo(ticksToSec(newValue), "seconds");
}
}}
sx={{
"& .MuiSlider-thumb": {
width: 14,
height: 14,
transition: "0.1s ease-in-out",
opacity: 0,
"&.Mui-active": {
width: 20,
height: 20,
opacity: 1,
},
},
"&:hover .MuiSlider-thumb": {
opacity: 1,
},
"& .MuiSlider-rail": {
opacity: 0.28,
background: "white",
},
}}
marks={chapterMarks}
valueLabelDisplay="off"
ref={areaRef}
onMouseMove={handleSliderHover}
/>
</Tooltip>
);
};
export default BubbleSlider;
+137 -303
View File
@@ -2,6 +2,7 @@ import { WebviewWindow as appWindow } from "@tauri-apps/api/webviewWindow";
import React, { import React, {
type ChangeEventHandler, type ChangeEventHandler,
type MouseEventHandler, type MouseEventHandler,
useReducer,
useTransition, useTransition,
} from "react"; } from "react";
import { useLayoutEffect, useMemo } from "react"; import { useLayoutEffect, useMemo } from "react";
@@ -23,7 +24,7 @@ import {
usePlaybackStore, usePlaybackStore,
} from "@/utils/store/playback"; } from "@/utils/store/playback";
import { secToTicks, ticksToMs, ticksToSec } from "@/utils/date/time"; import { secToTicks, ticksToSec } from "@/utils/date/time";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api"; import { getPlaystateApi } from "@jellyfin/sdk/lib/utils/api/playstate-api";
@@ -32,22 +33,12 @@ import "./videoPlayer.scss";
import { endsAt } from "@/utils/date/time"; import { endsAt } from "@/utils/date/time";
import { import { PlayMethod, RepeatMode } from "@jellyfin/sdk/lib/generated-client";
PlayMethod,
RepeatMode,
type TrickplayInfo,
} from "@jellyfin/sdk/lib/generated-client";
import { AnimatePresence, motion } from "framer-motion"; import { AnimatePresence, motion } from "framer-motion";
import { useBackdropStore } from "@/utils/store/backdrop"; import { useBackdropStore } from "@/utils/store/backdrop";
import { import { Button, LinearProgress, Popover, TextField } from "@mui/material";
Button,
LinearProgress,
Popover,
TextField,
Tooltip,
} from "@mui/material";
import JASSUB from "jassub"; import JASSUB from "jassub";
//@ts-ignore //@ts-ignore
import workerUrl from "jassub/dist/jassub-worker.js?url"; import workerUrl from "jassub/dist/jassub-worker.js?url";
@@ -70,10 +61,14 @@ import { toNumber } from "lodash";
import type { OnProgressProps } from "react-player/base"; import type { OnProgressProps } from "react-player/base";
import type subtitlePlaybackInfo from "@/utils/types/subtitlePlaybackInfo"; import type subtitlePlaybackInfo from "@/utils/types/subtitlePlaybackInfo";
import type { Instance } from "@popperjs/core";
//@ts-ignore //@ts-ignore
import font from "./Noto-Sans-Indosphere.ttf?url"; import font from "./Noto-Sans-Indosphere.ttf?url";
import BubbleSlider from "@/components/bubbleSlider";
import videoPlayerReducer, {
VideoPlayerActionKind,
} from "@/utils/reducers/videoPlayerReducer";
const ticksDisplay = (ticks: number) => { const ticksDisplay = (ticks: number) => {
const time = Math.round(ticks / 10000); const time = Math.round(ticks / 10000);
let formatedTime = ""; let formatedTime = "";
@@ -203,15 +198,43 @@ function VideoPlayer() {
const [showVolumeControl, setShowVolumeControl] = useState(false); const [showVolumeControl, setShowVolumeControl] = useState(false);
// Control States // Control States
const [isReady, setIsReady] = useState(false);
const [playing, setPlaying] = useState(true); const [
const [isSeeking, setIsSeeking] = useState(false); {
const [sliderProgress, setSliderProgress] = useState(startPosition); ref,
const [progress, setProgress] = useState(startPosition); isPlayerReady,
const [appFullscreen, setAppFullscreen] = useState(false); isPlayerPlaying,
isPlayerMuted,
isPlayerFullscreen,
playerVolume,
isSeeking,
sliderSeek,
progress,
isHovering,
},
dispatch,
] = useReducer(videoPlayerReducer, {
ref: player,
isPlayerReady: false,
isPlayerPlaying: true,
isPlayerMuted: false,
isPlayerFullscreen: false,
playerVolume: 1,
isSeeking: false,
sliderSeek: startPosition,
progress: startPosition,
isHovering: false,
});
// const [isReady, setIsReady] = useState(false);
// const [playing, setPlaying] = useState(true);
// const [isSeeking, setIsSeeking] = useState(false);
// const [sliderProgress, setSliderProgress] = useState(startPosition);
// const [progress, setProgress] = useState(startPosition);
// const [appFullscreen, setAppFullscreen] = useState(false);
// const [showSubtitles, setShowSubtitles] = useState(mediaSource.subtitle.enable); // const [showSubtitles, setShowSubtitles] = useState(mediaSource.subtitle.enable);
const [volume, setVolume] = useState(1); // const [volume, setVolume] = useState(1);
const [muted, setMuted] = useState(false); // const [muted, setMuted] = useState(false);
const setBackdrop = useBackdropStore((s) => s.setBackdrop); const setBackdrop = useBackdropStore((s) => s.setBackdrop);
useEffect(() => setBackdrop("", ""), []); useEffect(() => setBackdrop("", ""), []);
@@ -219,10 +242,10 @@ function VideoPlayer() {
const [clickTimeout, setClickTimeout] = useState<NodeJS.Timeout>(null!); const [clickTimeout, setClickTimeout] = useState<NodeJS.Timeout>(null!);
const handleReady = async () => { const handleReady = async () => {
if (api && !isReady) { if (api && !isPlayerReady) {
player.current?.seekTo(ticksToSec(startPosition), "seconds"); player.current?.seekTo(ticksToSec(startPosition), "seconds");
console.log("Seeking to", ticksToSec(startPosition)); console.log("Seeking to", ticksToSec(startPosition));
setIsReady(true); dispatch({ type: VideoPlayerActionKind.SET_PLAYER_READY, payload: true });
// Report Jellyfin server: Playback has begin // Report Jellyfin server: Playback has begin
getPlaystateApi(api).reportPlaybackStart({ getPlaystateApi(api).reportPlaybackStart({
playbackStartInfo: { playbackStartInfo: {
@@ -237,22 +260,25 @@ function VideoPlayer() {
PlaybackStartTimeTicks: startPosition, PlaybackStartTimeTicks: startPosition,
PositionTicks: startPosition, PositionTicks: startPosition,
RepeatMode: RepeatMode.RepeatNone, RepeatMode: RepeatMode.RepeatNone,
VolumeLevel: volume, VolumeLevel: playerVolume,
}, },
}); });
} }
}; };
const handleProgress = async (event: OnProgressProps) => { const handleProgress = async (event: OnProgressProps) => {
setProgress(secToTicks(event.playedSeconds)); dispatch({
type: VideoPlayerActionKind.SET_PROGRESS,
payload: secToTicks(event.playedSeconds),
});
if (!api) return null; if (!api) return null;
// Report Jellyfin server: Playback progress // Report Jellyfin server: Playback progress
getPlaystateApi(api).reportPlaybackProgress({ getPlaystateApi(api).reportPlaybackProgress({
playbackProgressInfo: { playbackProgressInfo: {
AudioStreamIndex: mediaSource.audioTrack, AudioStreamIndex: mediaSource.audioTrack,
CanSeek: true, CanSeek: true,
IsMuted: muted, IsMuted: isPlayerMuted,
IsPaused: !playing, IsPaused: !isPlayerPlaying,
ItemId: item?.Id, ItemId: item?.Id,
MediaSourceId: mediaSource.id, MediaSourceId: mediaSource.id,
PlayMethod: PlayMethod.DirectPlay, PlayMethod: PlayMethod.DirectPlay,
@@ -260,7 +286,7 @@ function VideoPlayer() {
PlaybackStartTimeTicks: startPosition, PlaybackStartTimeTicks: startPosition,
PositionTicks: secToTicks(event.playedSeconds), PositionTicks: secToTicks(event.playedSeconds),
RepeatMode: RepeatMode.RepeatNone, RepeatMode: RepeatMode.RepeatNone,
VolumeLevel: Math.floor(volume * 100), VolumeLevel: Math.floor(playerVolume * 100),
}, },
}); });
}; };
@@ -308,7 +334,7 @@ function VideoPlayer() {
break; break;
case "F8": case "F8":
case " ": case " ":
setPlaying((state) => !state); dispatch({ type: VideoPlayerActionKind.TOGGLE_PLAYER_PLAYING });
break; break;
case "ArrowUp": case "ArrowUp":
// setVolume((state) => (state <= 0.9 ? state + 0.1 : state)); // setVolume((state) => (state <= 0.9 ? state + 0.1 : state));
@@ -318,10 +344,7 @@ function VideoPlayer() {
break; break;
case "F": case "F":
case "f": case "f":
setAppFullscreen((state) => { dispatch({ type: VideoPlayerActionKind.TOGGLE_PLAYER_FULLSCREEN });
appWindow.getCurrent().setFullscreen(!state);
return !state;
});
break; break;
case "P": case "P":
case "p": case "p":
@@ -329,7 +352,7 @@ function VideoPlayer() {
break; break;
case "M": case "M":
case "m": case "m":
// setIsMuted((state) => !state); dispatch({ type: VideoPlayerActionKind.TOGGLE_PLAYER_MUTED });
break; break;
case "F7": case "F7":
playItemFromQueue("previous", user?.Id, api); playItemFromQueue("previous", user?.Id, api);
@@ -358,10 +381,16 @@ function VideoPlayer() {
const handleMouseWheel = (event: WheelEvent) => { const handleMouseWheel = (event: WheelEvent) => {
if (event.deltaY < 0) { if (event.deltaY < 0) {
// increase volume // increase volume
setVolume((state) => Math.min(1, state + VOLUME_SCROLL_INTERVAL)); dispatch({
type: VideoPlayerActionKind.SET_PLAYER_VOLUME_UP_BY_STEP,
payload: VOLUME_SCROLL_INTERVAL,
});
} else if (event.deltaY > 0) { } else if (event.deltaY > 0) {
// decrease volume // decrease volume
setVolume((state) => Math.max(0, state - VOLUME_SCROLL_INTERVAL)); dispatch({
type: VideoPlayerActionKind.SET_PLAYER_VOLUME_DOWN_BY_STEP,
payload: VOLUME_SCROLL_INTERVAL,
});
} }
}; };
@@ -376,8 +405,8 @@ function VideoPlayer() {
// Set playing state to true when a new item is loaded // Set playing state to true when a new item is loaded
useLayoutEffect(() => { useLayoutEffect(() => {
setPlaying(true); dispatch({ type: VideoPlayerActionKind.SET_PLAYER_PLAYING, payload: true });
setIsReady(false); dispatch({ type: VideoPlayerActionKind.SET_PLAYER_READY, payload: false });
}, [item?.Id]); }, [item?.Id]);
// Manage Subtitle playback // Manage Subtitle playback
@@ -519,135 +548,6 @@ function VideoPlayer() {
setShowChapterList(e.currentTarget); setShowChapterList(e.currentTarget);
}, []); }, []);
const sliderDisplayFormat = (value: number) => {
const currentChapter = item?.Chapters?.filter((chapter, index) => {
if (index + 1 === item.Chapters?.length) {
return chapter;
}
if (
(item.Chapters?.[index + 1]?.StartPositionTicks ?? value) - value >=
0 &&
(chapter.StartPositionTicks ?? value) - value < 0
) {
return chapter;
}
});
let trickplayResolution: TrickplayInfo | undefined;
const trickplayResolutions = mediaSource.id
? item?.Trickplay?.[mediaSource.id]
: null;
if (trickplayResolutions) {
let bestWidth: number | undefined;
const maxWidth = window.screen.width * window.devicePixelRatio * 0.2;
for (const [_, trickInfo] of Object.entries(trickplayResolutions)) {
if (
!bestWidth ||
(trickInfo.Width &&
((trickInfo.Width < bestWidth && bestWidth > maxWidth) ||
(trickInfo.Width > bestWidth && bestWidth <= maxWidth)))
) {
bestWidth = trickInfo.Width;
}
}
if (bestWidth) {
trickplayResolution = trickplayResolutions[bestWidth];
}
}
if (
trickplayResolution?.TileWidth &&
trickplayResolution.TileHeight &&
trickplayResolution.Width &&
trickplayResolution.Height
) {
const currentTrickplayImage = trickplayResolution?.Interval
? Math.floor(ticksToMs(value) / trickplayResolution?.Interval)
: 0;
const trickplayImageSize =
trickplayResolution?.TileWidth * trickplayResolution?.TileHeight; // this gives the area of a single tile
const trickplayImageOffset = currentTrickplayImage % trickplayImageSize; // this gives the tile index inside a trickplay image
const index = Math.floor(currentTrickplayImage / trickplayImageSize); // this gives the index of trickplay image
const imageOffsetX =
trickplayImageOffset % trickplayResolution?.TileWidth; // this gives the x coordinate of tile in trickplay image
const imageOffsetY = Math.floor(
trickplayImageOffset / trickplayResolution?.TileWidth,
); // this gives the y coordinate of tile in trickplay image
const backgroundOffsetX = -(imageOffsetX * trickplayResolution?.Width);
const backgroundOffsetY = -(imageOffsetY * trickplayResolution?.Height);
const imgUrlParamsObject: Record<string, string> = {
api_key: String(api?.accessToken),
MediaSourceId: mediaSource.id ?? "",
};
const imgUrlParams = new URLSearchParams(imgUrlParamsObject).toString();
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/${item?.Id}/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/${item?.Id}/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>
);
}
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}>
{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 [showVolumeIndicator, setVolumeIndicator] = useState(false); const [showVolumeIndicator, setVolumeIndicator] = useState(false);
useEffect(() => { useEffect(() => {
setVolumeIndicator(true); setVolumeIndicator(true);
@@ -655,7 +555,7 @@ function VideoPlayer() {
setVolumeIndicator(false); setVolumeIndicator(false);
}, 1000); }, 1000);
return () => clearTimeout(timeout); return () => clearTimeout(timeout);
}, [volume]); }, [playerVolume]);
const handlePlaybackEnded = () => { const handlePlaybackEnded = () => {
if (queue?.[currentQueueItemIndex + 1].Id) { if (queue?.[currentQueueItemIndex + 1].Id) {
@@ -691,7 +591,10 @@ function VideoPlayer() {
startAudioTrackChange(() => { startAudioTrackChange(() => {
if (api && mediaSource.audio.allTracks) { if (api && mediaSource.audio.allTracks) {
changeAudioTrack(toNumber(e.target.value), api, progress); changeAudioTrack(toNumber(e.target.value), api, progress);
setIsReady(false); dispatch({
type: VideoPlayerActionKind.SET_PLAYER_READY,
payload: false,
});
// setSettingsMenu(null); // setSettingsMenu(null);
} }
}); });
@@ -729,27 +632,6 @@ function VideoPlayer() {
player.current?.seekTo(ticksToSec(next?.StartPositionTicks ?? 0)); player.current?.seekTo(ticksToSec(next?.StartPositionTicks ?? 0));
}, [progress, playsessionId]); }, [progress, playsessionId]);
const positionRef = React.useRef<{ x: number; y: number }>({
x: 0,
y: 0,
});
const popperRef = React.useRef<Instance>(null);
const areaRef = React.useRef<HTMLDivElement>(null);
const [hoverProgress, setHoverProgress] = useState(0);
const handleSliderHover = (event: React.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);
if (popperRef.current != null) {
popperRef.current.update();
}
};
return ( return (
<div className="video-player"> <div className="video-player">
<AnimatePresence> <AnimatePresence>
@@ -822,11 +704,11 @@ function VideoPlayer() {
className="video-volume-indicator glass" className="video-volume-indicator glass"
> >
<div className="material-symbols-rounded"> <div className="material-symbols-rounded">
{volume > 0.7 ? "volume_up" : "volume_down"} {playerVolume > 0.7 ? "volume_up" : "volume_down"}
</div> </div>
<LinearProgress <LinearProgress
style={{ width: "100%" }} style={{ width: "100%" }}
value={volume * 100} value={playerVolume * 100}
variant="determinate" variant="determinate"
/> />
</motion.div> </motion.div>
@@ -834,7 +716,7 @@ function VideoPlayer() {
</AnimatePresence> </AnimatePresence>
<motion.div <motion.div
className={ className={
hoveringOsd || !playing || isSeeking hoveringOsd || !isPlayerPlaying || isSeeking
? "video-player-osd hovering" ? "video-player-osd hovering"
: "video-player-osd" : "video-player-osd"
} }
@@ -844,7 +726,7 @@ function VideoPlayer() {
opacity: 0, opacity: 0,
}} }}
animate={{ animate={{
opacity: hoveringOsd || !playing || isSeeking ? 1 : 0, opacity: hoveringOsd || !isPlayerPlaying || isSeeking ? 1 : 0,
}} }}
style={{ style={{
zIndex: 2, zIndex: 2,
@@ -857,15 +739,12 @@ function VideoPlayer() {
if (event.detail === 1) { if (event.detail === 1) {
setClickTimeout( setClickTimeout(
setTimeout(() => { setTimeout(() => {
setPlaying((state) => !state); dispatch({ type: VideoPlayerActionKind.TOGGLE_PLAYER_PLAYING });
}, 200), }, 200),
); );
} else if (event.detail === 2) { } else if (event.detail === 2) {
clearTimeout(clickTimeout); clearTimeout(clickTimeout);
setAppFullscreen((state) => { dispatch({ type: VideoPlayerActionKind.TOGGLE_PLAYER_FULLSCREEN });
appWindow.getCurrent().setFullscreen(!state);
return !state;
});
} }
}} }}
> >
@@ -950,93 +829,25 @@ function VideoPlayer() {
</Typography> </Typography>
<div className="video-player-osd-controls"> <div className="video-player-osd-controls">
<div className="video-player-osd-controls-progress"> <div className="video-player-osd-controls-progress">
<Tooltip {item && api && (
// title={sliderDisplayFormat( <BubbleSlider
// positionRef.current.x - areaRef.current!.getBoundingClientRect().x, itemDuration={itemDuration}
// )} item={item}
key={`${positionRef.current}`} mediaSource={mediaSource}
title={sliderDisplayFormat(hoverProgress)} api={api}
placement="top" chapterMarks={chapterMarks}
slotProps={{ sliderState={{
popper: { isSeeking,
popperRef, sliderSeek,
anchorEl: { progress,
getBoundingClientRect: () => {
return new DOMRect(
positionRef.current.x,
areaRef.current!.getBoundingClientRect().y,
0,
0,
);
},
},
disablePortal: true,
},
tooltip: {
className: "glass",
style: {
width: "34em",
overflow: "hidden",
padding: "12px",
borderRadius: "20px",
},
},
}}
>
<Slider
value={isSeeking ? sliderProgress : progress}
max={itemDuration}
step={1}
onChange={(_, newValue) => {
setIsSeeking(true);
Array.isArray(newValue)
? setSliderProgress(newValue[0])
: setSliderProgress(newValue);
}} }}
onChangeCommitted={(_, newValue) => { dispatch={dispatch}
setIsSeeking(false); player={player}
Array.isArray(newValue)
? setProgress(newValue[0])
: setProgress(newValue);
if (Array.isArray(newValue)) {
player.current?.seekTo(
ticksToSec(newValue[0]),
"seconds",
);
} else {
console.log("Seeking to", ticksToSec(newValue));
player.current?.seekTo(ticksToSec(newValue), "seconds");
}
}}
sx={{
"& .MuiSlider-thumb": {
width: 14,
height: 14,
transition: "0.1s ease-in-out",
opacity: 0,
"&.Mui-active": {
width: 20,
height: 20,
opacity: 1,
},
},
"&:hover .MuiSlider-thumb": {
opacity: 1,
},
"& .MuiSlider-rail": {
opacity: 0.28,
background: "white",
},
}}
marks={chapterMarks}
valueLabelDisplay="off"
ref={areaRef}
onMouseMove={handleSliderHover}
/> />
</Tooltip> )}
<div className="video-player-osd-controls-progress-text"> <div className="video-player-osd-controls-progress-text">
<Typography> <Typography>
{ticksDisplay(isSeeking ? sliderProgress : progress)} {ticksDisplay(isSeeking ? sliderSeek : progress)}
</Typography> </Typography>
<Typography>{ticksDisplay(itemDuration)}</Typography> <Typography>{ticksDisplay(itemDuration)}</Typography>
</div> </div>
@@ -1060,9 +871,15 @@ function VideoPlayer() {
first_page first_page
</span> </span>
</IconButton> </IconButton>
<IconButton onClick={() => setPlaying((state) => !state)}> <IconButton
onClick={() =>
dispatch({
type: VideoPlayerActionKind.TOGGLE_PLAYER_PLAYING,
})
}
>
<span className="material-symbols-rounded fill"> <span className="material-symbols-rounded fill">
{playing ? "pause" : "play_arrow"} {isPlayerPlaying ? "pause" : "play_arrow"}
</span> </span>
</IconButton> </IconButton>
<IconButton <IconButton
@@ -1090,7 +907,7 @@ function VideoPlayer() {
<PlayNextButton /> <PlayNextButton />
<Typography variant="subtitle1"> <Typography variant="subtitle1">
{isSeeking {isSeeking
? endsAt(itemDuration - sliderProgress) ? endsAt(itemDuration - sliderSeek)
: endsAt(itemDuration - progress)} : endsAt(itemDuration - progress)}
</Typography> </Typography>
</div> </div>
@@ -1118,32 +935,50 @@ function VideoPlayer() {
onMouseLeave={() => setShowVolumeControl(false)} onMouseLeave={() => setShowVolumeControl(false)}
> >
<Typography textAlign="center"> <Typography textAlign="center">
{muted ? 0 : Math.round(volume * 100)} {isPlayerMuted ? 0 : Math.round(playerVolume * 100)}
</Typography> </Typography>
<Slider <Slider
step={0.01} step={0.01}
max={1} max={1}
size="small" size="small"
value={muted ? 0 : volume} value={isPlayerMuted ? 0 : playerVolume}
onChange={(_, newVal) => { onChange={(_, newValue) => {
Array.isArray(newVal) Array.isArray(newValue)
? setVolume(newVal[0]) ? dispatch({
: setVolume(newVal); type: VideoPlayerActionKind.SET_PLAYER_VOLUME,
if (newVal === 0) setMuted(true); payload: newValue[0],
else setMuted(false); })
: 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> </motion.div>
<IconButton <IconButton
onClick={() => setMuted((state) => !state)} onClick={() =>
dispatch({
type: VideoPlayerActionKind.TOGGLE_PLAYER_MUTED,
})
}
onMouseMoveCapture={() => { onMouseMoveCapture={() => {
setShowVolumeControl(true); setShowVolumeControl(true);
}} }}
> >
<span className="material-symbols-rounded"> <span className="material-symbols-rounded">
{muted {isPlayerMuted
? "volume_off" ? "volume_off"
: volume < 0.4 : playerVolume < 0.4
? "volume_down" ? "volume_down"
: "volume_up"} : "volume_up"}
</span> </span>
@@ -1199,14 +1034,13 @@ function VideoPlayer() {
</IconButton> </IconButton>
<IconButton <IconButton
onClick={async () => { onClick={async () => {
setAppFullscreen((state) => { dispatch({
appWindow.getCurrent().setFullscreen(!state); type: VideoPlayerActionKind.TOGGLE_PLAYER_FULLSCREEN,
return !state;
}); });
}} }}
> >
<span className="material-symbols-rounded fill"> <span className="material-symbols-rounded fill">
{appFullscreen ? "fullscreen_exit" : "fullscreen"} {isPlayerFullscreen ? "fullscreen_exit" : "fullscreen"}
</span> </span>
</IconButton> </IconButton>
</div> </div>
@@ -1217,7 +1051,7 @@ function VideoPlayer() {
</motion.div> </motion.div>
<ReactPlayer <ReactPlayer
key={playsessionId} key={playsessionId}
playing={playing} playing={isPlayerPlaying}
url={playbackStream} url={playbackStream}
ref={player} ref={player}
onProgress={handleProgress} onProgress={handleProgress}
@@ -1237,7 +1071,7 @@ function VideoPlayer() {
position: "fixed", position: "fixed",
zIndex: 1, zIndex: 1,
}} }}
volume={muted ? 0 : volume} volume={isPlayerMuted ? 0 : playerVolume}
onReady={handleReady} onReady={handleReady}
onBuffer={() => setLoading(true)} onBuffer={() => setLoading(true)}
onBufferEnd={() => setLoading(false)} onBufferEnd={() => setLoading(false)}
+142
View File
@@ -0,0 +1,142 @@
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
import type ReactPlayer from "react-player";
type VideoPlayerState = {
ref: React.RefObject<ReactPlayer | null>;
isPlayerReady: boolean;
isPlayerPlaying: boolean;
isPlayerMuted: boolean;
isPlayerFullscreen: boolean;
/**
* Volume of the player
* @type {number} 0 to 1
*/
playerVolume: number;
isSeeking: boolean;
sliderSeek: number;
/**
* Progress of the video
* @type {number} in C# ticks
*/
progress: number;
isHovering: boolean;
};
export enum VideoPlayerActionKind {
SET_PLAYER_REF = "SET_PLAYER_REF",
SET_PLAYER_READY = "SET_PLAYER_READY",
SET_PLAYER_PLAYING = "SET_PLAYER_PLAYING",
SET_PLAYER_MUTED = "SET_PLAYER_MUTED",
SET_PLAYER_FULLSCREEN = "SET_PLAYER_FULLSCREEN",
SET_PLAYER_VOLUME = "SET_PLAYER_VOLUME",
SET_PLAYER_VOLUME_UP_BY_STEP = "SET_PLAYER_VOLUME_BY_STEP",
SET_PLAYER_VOLUME_DOWN_BY_STEP = "SET_PLAYER_VOLUME_DOWN_STEP",
SET_SEEKING = "SET_SEEKING",
SET_SLIDER_SEEK = "SET_SLIDER_SEEK",
SET_PROGRESS = "SET_PROGRESS",
SET_HOVERING = "SET_HOVERING",
TOGGLE_PLAYER_PLAYING = "TOGGLE_PLAYER_PLAYING",
TOGGLE_PLAYER_FULLSCREEN = "TOGGLE_PLAYER_FULLSCREEN",
TOGGLE_PLAYER_MUTED = "TOGGLE_PLAYER_MUTED",
}
export interface VideoPlayerAction {
type: VideoPlayerActionKind;
payload?: number | boolean | React.RefObject<HTMLVideoElement>;
}
const reducer = (
state: VideoPlayerState,
action: VideoPlayerAction,
): VideoPlayerState => {
switch (action.type) {
case VideoPlayerActionKind.SET_PLAYER_REF:
return {
...state,
ref: action.payload as unknown as React.RefObject<ReactPlayer | null>,
};
case VideoPlayerActionKind.SET_PLAYER_READY:
return {
...state,
isPlayerReady: action.payload as boolean,
};
case VideoPlayerActionKind.SET_PLAYER_PLAYING:
return {
...state,
isPlayerPlaying: action.payload as boolean,
};
case VideoPlayerActionKind.SET_PLAYER_MUTED:
return {
...state,
isPlayerMuted: action.payload as boolean,
};
case VideoPlayerActionKind.SET_PLAYER_FULLSCREEN:
return {
...state,
isPlayerFullscreen: action.payload as boolean,
};
case VideoPlayerActionKind.SET_PLAYER_VOLUME:
return {
...state,
playerVolume: action.payload as number,
};
case VideoPlayerActionKind.SET_SEEKING:
return {
...state,
isSeeking: action.payload as boolean,
};
case VideoPlayerActionKind.SET_SLIDER_SEEK:
return {
...state,
sliderSeek: action.payload as number,
};
case VideoPlayerActionKind.SET_PROGRESS:
return {
...state,
progress: action.payload as number,
};
case VideoPlayerActionKind.SET_HOVERING:
return {
...state,
isHovering: action.payload as boolean,
};
case VideoPlayerActionKind.TOGGLE_PLAYER_PLAYING:
return {
...state,
isPlayerPlaying: !state.isPlayerPlaying,
};
case VideoPlayerActionKind.TOGGLE_PLAYER_FULLSCREEN: {
WebviewWindow.getCurrent().setFullscreen(!state.isPlayerFullscreen);
return {
...state,
isPlayerFullscreen: !state.isPlayerFullscreen,
};
}
case VideoPlayerActionKind.TOGGLE_PLAYER_MUTED:
return {
...state,
isPlayerMuted: !state.isPlayerMuted,
};
case VideoPlayerActionKind.SET_PLAYER_VOLUME_UP_BY_STEP:
return {
...state,
playerVolume: Math.min(
1,
Math.max(0, state.playerVolume + (action.payload as number)),
),
};
case VideoPlayerActionKind.SET_PLAYER_VOLUME_DOWN_BY_STEP:
return {
...state,
playerVolume: Math.min(
1,
Math.max(0, state.playerVolume - (action.payload as number)),
),
};
default:
return state;
}
};
export default reducer;