refactor: improve the playback experience
This commit is contained in:
5 files changed
+334
-268
No files matched your search
@@ -3,7 +3,6 @@ import {
|
||||
BaseItemKind,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api";
|
||||
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
|
||||
import type { SxProps } from "@mui/material";
|
||||
import Button, { type ButtonProps } from "@mui/material/Button";
|
||||
import Fab from "@mui/material/Fab";
|
||||
@@ -19,6 +18,7 @@ import getSubtitle from "@/utils/methods/getSubtitles";
|
||||
import { getNextEpisode, getPlaybackInfo } from "@/utils/methods/playback";
|
||||
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 { playItem } from "@/utils/store/playback";
|
||||
import { setQueue } from "@/utils/store/queue";
|
||||
@@ -85,6 +85,7 @@ const PlayButton = ({
|
||||
// (state) => state.setisPending,
|
||||
// );
|
||||
const playPhotos = usePhotosPlayback((s) => s.playPhotos);
|
||||
const currentUser = useCentralStore((s) => s.currentUser);
|
||||
|
||||
const { enqueueSnackbar } = useSnackbar();
|
||||
|
||||
@@ -173,9 +174,8 @@ const PlayButton = ({
|
||||
}
|
||||
|
||||
// Subtitle
|
||||
const userSubtitleLanguagePreference = (
|
||||
await getUserApi(api).getCurrentUser()
|
||||
).data.Configuration?.SubtitleLanguagePreference;
|
||||
const userSubtitleLanguagePreference =
|
||||
currentUser?.Configuration?.SubtitleLanguagePreference;
|
||||
// Get all subtitle streams
|
||||
const allSubtitles =
|
||||
result?.mediaSource?.MediaSources?.[0]?.MediaStreams?.filter(
|
||||
@@ -195,9 +195,8 @@ const PlayButton = ({
|
||||
);
|
||||
|
||||
// Audio
|
||||
const userAudioLanguagePreference = (
|
||||
await getUserApi(api).getCurrentUser()
|
||||
).data.Configuration?.AudioLanguagePreference;
|
||||
const userAudioLanguagePreference =
|
||||
currentUser?.Configuration?.AudioLanguagePreference;
|
||||
// Get all audio streams
|
||||
const allAudioTracks =
|
||||
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
@@ -321,7 +320,7 @@ const PlayButton = ({
|
||||
userId: userId,
|
||||
enableUserData: true,
|
||||
});
|
||||
|
||||
|
||||
const currentSeason = seasons.data.Items?.find((season) => {
|
||||
return season.UserData?.Played !== true;
|
||||
});
|
||||
@@ -337,7 +336,7 @@ const PlayButton = ({
|
||||
}
|
||||
return { Items: [] };
|
||||
},
|
||||
// enabled: itemType === BaseItemKind.Series,
|
||||
enabled: itemType === BaseItemKind.Series,
|
||||
});
|
||||
|
||||
if (iconOnly) {
|
||||
|
||||
@@ -21,6 +21,37 @@ import { useLibraryStateStore } from "@/utils/store/libraryState";
|
||||
|
||||
export const Route = createFileRoute("/_api/library/$id")({
|
||||
component: Library,
|
||||
loader: async ({ context: { queryClient, api, user }, params }) => {
|
||||
if (!api || !user?.Id) return;
|
||||
const library = await queryClient.ensureQueryData(
|
||||
getLibraryQueryOptions(api, user?.Id, params.id),
|
||||
);
|
||||
|
||||
const collectionType = library.CollectionType;
|
||||
const detectedViewType: BaseItemKind | "Artist" =
|
||||
collectionType === "music"
|
||||
? BaseItemKind.MusicAlbum
|
||||
: collectionType === "movies"
|
||||
? BaseItemKind.Movie
|
||||
: collectionType === "tvshows"
|
||||
? BaseItemKind.Series
|
||||
: collectionType === "boxsets"
|
||||
? BaseItemKind.BoxSet
|
||||
: collectionType === "books"
|
||||
? BaseItemKind.Book
|
||||
: collectionType === "playlists"
|
||||
? BaseItemKind.Playlist
|
||||
: BaseItemKind.Movie;
|
||||
|
||||
useLibraryStateStore.getState().initLibrary(params.id, {
|
||||
currentViewType: detectedViewType,
|
||||
sortBy:
|
||||
getDefaultSortByForCollectionType(collectionType as any) ||
|
||||
ItemSortBy.Name,
|
||||
sortAscending: true,
|
||||
libraryName: library.Name ?? undefined,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
function Library() {
|
||||
@@ -33,7 +64,7 @@ function Library() {
|
||||
const currentLib = useSuspenseQuery(
|
||||
getLibraryQueryOptions(api, user?.Id, id),
|
||||
);
|
||||
const initLibrary = useLibraryStateStore((s) => s.initLibrary);
|
||||
const _initLibrary = useLibraryStateStore((s) => s.initLibrary);
|
||||
const updateLibrary = useLibraryStateStore((s) => s.updateLibrary);
|
||||
const { currentViewType: storeViewType, libraryName: storeLibraryName } =
|
||||
useLibraryStateStore(
|
||||
@@ -50,34 +81,7 @@ function Library() {
|
||||
if (!id || !currentLib.data) return;
|
||||
// Ensure library name is available in Zustand for header consumption
|
||||
updateLibrary(id, { libraryName: currentLib.data.Name ?? undefined });
|
||||
const collectionType = currentLib.data.CollectionType;
|
||||
|
||||
const detectedViewType: BaseItemKind | "Artist" =
|
||||
collectionType === "music"
|
||||
? BaseItemKind.MusicAlbum
|
||||
: collectionType === "movies"
|
||||
? BaseItemKind.Movie
|
||||
: collectionType === "tvshows"
|
||||
? BaseItemKind.Series
|
||||
: collectionType === "boxsets"
|
||||
? BaseItemKind.BoxSet
|
||||
: collectionType === "books"
|
||||
? BaseItemKind.Book
|
||||
: collectionType === "playlists"
|
||||
? BaseItemKind.Playlist
|
||||
: BaseItemKind.Movie;
|
||||
|
||||
// Initialize defaults if state not yet set
|
||||
if (storeViewType === undefined) {
|
||||
initLibrary(id, {
|
||||
currentViewType: detectedViewType,
|
||||
sortBy:
|
||||
getDefaultSortByForCollectionType(collectionType as any) ||
|
||||
ItemSortBy.Name,
|
||||
sortAscending: true,
|
||||
});
|
||||
}
|
||||
}, [id, storeViewType, initLibrary, updateLibrary, currentLib.data]);
|
||||
}, [id, updateLibrary, currentLib.data]);
|
||||
|
||||
const { setPageTitle } = useHeaderStore(
|
||||
useShallow((state) => ({
|
||||
|
||||
@@ -12,12 +12,12 @@ import { PlayMethod, RepeatMode } from "@jellyfin/sdk/lib/generated-client";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { createFileRoute, useRouter } from "@tanstack/react-router";
|
||||
import JASSUB from "jassub";
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
import workerUrl from "jassub/dist/jassub-worker.js?url";
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
import wasmUrl from "jassub/dist/jassub-worker.wasm?url";
|
||||
import { PgsRenderer } from "libpgs";
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
import pgsWorkerUrl from "libpgs/dist/libpgs.worker.js?url";
|
||||
// import type { OnProgressProps } from "react-player";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
@@ -32,7 +32,7 @@ import { useBackdropStore } from "@/utils/store/backdrop";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import useQueue, { clearQueue } from "@/utils/store/queue";
|
||||
import type subtitlePlaybackInfo from "@/utils/types/subtitlePlaybackInfo";
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
import font from "./Noto-Sans-Indosphere.ttf?url";
|
||||
|
||||
/**
|
||||
@@ -42,16 +42,25 @@ function addSubtitleTrackToReactPlayer(
|
||||
videoElem: HTMLMediaElement,
|
||||
subtitleTracks: subtitlePlaybackInfo,
|
||||
baseUrl: string,
|
||||
apiKey?: string,
|
||||
) {
|
||||
if (subtitleTracks.url && subtitleTracks.allTracks) {
|
||||
const reqSubTrack = subtitleTracks.allTracks.filter(
|
||||
const reqSubTrack = subtitleTracks.allTracks.find(
|
||||
(val) => val.Index === subtitleTracks.track,
|
||||
);
|
||||
if (!reqSubTrack) return;
|
||||
|
||||
// Remove existing tracks to ensure clean state
|
||||
const existingTracks = videoElem.querySelectorAll("track");
|
||||
existingTracks.forEach((t) => t.remove());
|
||||
|
||||
const track = document.createElement("track");
|
||||
track.src = `${baseUrl}${subtitleTracks.url}`;
|
||||
const separator = subtitleTracks.url.includes("?") ? "&" : "?";
|
||||
const urlParams = apiKey ? `${separator}api_key=${apiKey}` : "";
|
||||
track.src = `${baseUrl}${subtitleTracks.url}${urlParams}`;
|
||||
track.kind = "subtitles";
|
||||
track.srclang = reqSubTrack[0].Language ?? "en";
|
||||
track.label = reqSubTrack[0].DisplayTitle ?? "Subtitle";
|
||||
track.srclang = reqSubTrack.Language ?? "en";
|
||||
track.label = reqSubTrack.DisplayTitle ?? "Subtitle";
|
||||
track.default = true;
|
||||
track.id = subtitleTracks.url;
|
||||
|
||||
@@ -60,24 +69,10 @@ function addSubtitleTrackToReactPlayer(
|
||||
a.mode = "showing";
|
||||
});
|
||||
track.addEventListener("error", (e) => {
|
||||
console.error(e);
|
||||
console.error("Error loading subtitle track", e);
|
||||
});
|
||||
|
||||
const trackAlreadyExists = videoElem.textTracks.getTrackById(
|
||||
subtitleTracks.url,
|
||||
);
|
||||
if (!trackAlreadyExists?.id) {
|
||||
// console.log(trackAlreadyExists.getTrackById(reqSubTrack[0].Index));
|
||||
videoElem.appendChild(track);
|
||||
}
|
||||
|
||||
for (const i of videoElem.textTracks) {
|
||||
if (i.label === reqSubTrack[0].DisplayTitle) {
|
||||
i.mode = "showing";
|
||||
} else {
|
||||
i.mode = "hidden";
|
||||
}
|
||||
}
|
||||
videoElem.appendChild(track);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,8 +164,14 @@ export function VideoPlayer() {
|
||||
|
||||
const handleReady = async () => {
|
||||
if (api && !isPlayerReady && player.current) {
|
||||
player.current.currentTime = ticksToSec(userDataLastPlayedPositionTicks ?? 0);
|
||||
|
||||
if (player.current.seekTo) {
|
||||
player.current.seekTo(ticksToSec(userDataLastPlayedPositionTicks ?? 0));
|
||||
} else {
|
||||
player.current.currentTime = ticksToSec(
|
||||
userDataLastPlayedPositionTicks ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
if (navigator.mediaSession && mediaSource) {
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: isEpisode ? episodeTitle : (itemName ?? "Blink"),
|
||||
@@ -213,18 +214,33 @@ export function VideoPlayer() {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
registerPlayerActions({
|
||||
seekTo: (seconds: number) => {
|
||||
const internalPlayer = player.current;
|
||||
if (internalPlayer) {
|
||||
internalPlayer.currentTime = seconds;
|
||||
// @ts-expect-error
|
||||
const current = internalPlayer.getCurrentTime
|
||||
? // @ts-ignore
|
||||
internalPlayer.getCurrentTime()
|
||||
: // @ts-ignore
|
||||
(internalPlayer.currentTime ?? 0);
|
||||
|
||||
if (Math.abs(current - seconds) < 0.1) {
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-expect-error
|
||||
if (internalPlayer.seekTo) {
|
||||
// @ts-expect-error
|
||||
internalPlayer.seekTo(seconds, "seconds");
|
||||
} else {
|
||||
internalPlayer.currentTime = seconds;
|
||||
}
|
||||
console.log("Seeking to", seconds, "seconds");
|
||||
} else {
|
||||
console.warn("ReactPlayer is not ready yet");
|
||||
}
|
||||
console.warn("ReactPlayer is not ready yet");
|
||||
// If you want to report the seek action
|
||||
// if (internalPlayer && typeof internalPlayer.seekTo === "function") {
|
||||
// }
|
||||
},
|
||||
getCurrentTime: () => {
|
||||
const internalPlayer = player.current;
|
||||
@@ -257,22 +273,38 @@ export function VideoPlayer() {
|
||||
}
|
||||
};
|
||||
|
||||
const lastReportTimeRef = useRef<number>(0);
|
||||
|
||||
const handleTimeUpdate = useCallback(async () => {
|
||||
const ticks = secToTicks(player.current?.currentTime ?? 0);
|
||||
if (!player.current) return;
|
||||
|
||||
// @ts-expect-error
|
||||
const currentTime = player.current.getCurrentTime
|
||||
? player.current.getCurrentTime()
|
||||
: (player.current.currentTime ?? 0);
|
||||
const ticks = secToTicks(currentTime);
|
||||
const now = Date.now();
|
||||
|
||||
setCurrentTime(ticks);
|
||||
|
||||
if (!api) {
|
||||
console.warn("API is not available, cannot report playback progress.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Report to server every 10s
|
||||
if (now - lastReportTimeRef.current < 10000) {
|
||||
return;
|
||||
}
|
||||
lastReportTimeRef.current = now;
|
||||
|
||||
// Report Jellyfin server: Playback progress
|
||||
getPlaystateApi(api).reportPlaybackProgress({
|
||||
playbackProgressInfo: {
|
||||
AudioStreamIndex: mediaSource.audioTrack,
|
||||
CanSeek: true,
|
||||
IsMuted: isPlayerMuted,
|
||||
IsPaused: player.current?.paused,
|
||||
IsPaused: !isPlayerPlaying,
|
||||
ItemId: itemId,
|
||||
MediaSourceId: mediaSource.id,
|
||||
PlayMethod: PlayMethod.DirectPlay,
|
||||
@@ -283,7 +315,17 @@ export function VideoPlayer() {
|
||||
VolumeLevel: Math.floor(volume * 100),
|
||||
},
|
||||
});
|
||||
}, [setCurrentTime]);
|
||||
}, [
|
||||
setCurrentTime,
|
||||
api,
|
||||
mediaSource,
|
||||
isPlayerMuted,
|
||||
isPlayerPlaying,
|
||||
itemId,
|
||||
playsessionId,
|
||||
userDataLastPlayedPositionTicks,
|
||||
volume,
|
||||
]);
|
||||
|
||||
const handleExitPlayer = useCallback(async () => {
|
||||
appWindow.getCurrent().setFullscreen(false);
|
||||
@@ -363,18 +405,31 @@ export function VideoPlayer() {
|
||||
// Manage Subtitle playback
|
||||
useEffect(() => {
|
||||
if (player.current && mediaSource.subtitle.enable) {
|
||||
// @ts-expect-error
|
||||
let internalPlayer: HTMLMediaElement = player.current;
|
||||
if (player.current.getInternalPlayer) {
|
||||
// @ts-expect-error
|
||||
// @ts-expect-error
|
||||
internalPlayer = player.current.getInternalPlayer() as HTMLMediaElement;
|
||||
}
|
||||
|
||||
if (!internalPlayer) return;
|
||||
|
||||
let jassubRenderer: JASSUB | undefined;
|
||||
let pgsRenderer: PgsRenderer | undefined;
|
||||
const apiKey = api?.accessToken;
|
||||
const separator = mediaSource.subtitle.url?.includes("?") ? "&" : "?";
|
||||
const urlParams = apiKey ? `${separator}api_key=${apiKey}` : "";
|
||||
|
||||
if (
|
||||
mediaSource.subtitle.format === "ass" ||
|
||||
mediaSource.subtitle.format === "ssa"
|
||||
) {
|
||||
jassubRenderer = new JASSUB({
|
||||
//@ts-ignore
|
||||
video: player.current,
|
||||
video: internalPlayer,
|
||||
workerUrl,
|
||||
wasmUrl,
|
||||
subUrl: `${api?.basePath}${mediaSource.subtitle.url}`,
|
||||
subUrl: `${api?.basePath}${mediaSource.subtitle.url}${urlParams}`,
|
||||
availableFonts: { "noto sans": font },
|
||||
fallbackFont: "noto sans",
|
||||
});
|
||||
@@ -383,15 +438,16 @@ export function VideoPlayer() {
|
||||
mediaSource.subtitle.format === "vtt"
|
||||
) {
|
||||
addSubtitleTrackToReactPlayer(
|
||||
player.current as HTMLMediaElement,
|
||||
internalPlayer,
|
||||
mediaSource.subtitle,
|
||||
api?.basePath ?? "",
|
||||
apiKey,
|
||||
);
|
||||
} else if (mediaSource.subtitle.format === "PGSSUB") {
|
||||
pgsRenderer = new PgsRenderer({
|
||||
workerUrl: pgsWorkerUrl,
|
||||
video: player.current as any,
|
||||
subUrl: `${api?.basePath}${mediaSource.subtitle.url}`,
|
||||
video: internalPlayer,
|
||||
subUrl: `${api?.basePath}${mediaSource.subtitle.url}${urlParams}`,
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
@@ -404,10 +460,18 @@ export function VideoPlayer() {
|
||||
};
|
||||
}
|
||||
if (player.current && mediaSource.subtitle.enable === false) {
|
||||
// @ts-ignore internalPlayer here provides the HTML video player element
|
||||
const videoElem: HTMLMediaElement = player.current as HTMLMediaElement;
|
||||
for (const i of videoElem.textTracks) {
|
||||
i.mode = "hidden";
|
||||
// @ts-expect-error
|
||||
let internalPlayer: HTMLMediaElement = player.current;
|
||||
if (player.current.getInternalPlayer) {
|
||||
// @ts-expect-error
|
||||
// @ts-expect-error
|
||||
internalPlayer = player.current.getInternalPlayer() as HTMLMediaElement;
|
||||
}
|
||||
|
||||
if (internalPlayer?.textTracks) {
|
||||
for (const i of internalPlayer.textTracks) {
|
||||
i.mode = "hidden";
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [mediaSource.subtitle?.track, mediaSource.subtitle?.enable]);
|
||||
@@ -533,6 +597,7 @@ export function VideoPlayer() {
|
||||
onPlaying={handleOnBufferEnd}
|
||||
onSeeking={(e) => handleOnSeek(e.currentTarget.currentTime)}
|
||||
playsInline
|
||||
crossOrigin="anonymous"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
BaseItemKind,
|
||||
ItemFields,
|
||||
ItemFilter,
|
||||
ItemSortBy,
|
||||
LocationType,
|
||||
SortOrder,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
@@ -221,7 +220,7 @@ export async function getPlaybackInfo(
|
||||
targetItem.MediaSources?.[0].DefaultAudioStreamIndex ?? 0;
|
||||
}
|
||||
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(audioStreamIndex),
|
||||
subtitleStreamIndex: currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: targetItem.Id,
|
||||
@@ -233,11 +232,17 @@ export async function getPlaybackInfo(
|
||||
},
|
||||
});
|
||||
|
||||
mediaSegments = (
|
||||
await getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: targetItem.Id,
|
||||
})
|
||||
)?.data;
|
||||
const segmentsPromise = getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: targetItem.Id,
|
||||
});
|
||||
|
||||
const [playbackInfoResponse, segmentsResponse] = await Promise.all([
|
||||
playbackInfoPromise,
|
||||
segmentsPromise,
|
||||
]);
|
||||
|
||||
mediaSource = playbackInfoResponse;
|
||||
mediaSegments = segmentsResponse?.data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+171
-178
@@ -531,6 +531,7 @@ export const usePlaybackStore = create<
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})[0];
|
||||
playerActions.seekTo(ticksToSec(next?.StartPositionTicks ?? 0));
|
||||
},
|
||||
@@ -543,6 +544,7 @@ export const usePlaybackStore = create<
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (!chapters?.length) {
|
||||
playerActions.seekTo(0);
|
||||
@@ -646,28 +648,22 @@ export const playItemFromQueue = async (
|
||||
console.error("Unable to play item from from queue. No API provided");
|
||||
return;
|
||||
}
|
||||
const queueItems = useQueue.getState().tracks;
|
||||
const currentItemIndex = useQueue.getState().currentItemIndex;
|
||||
const { tracks: queueItems, currentItemIndex } = useQueue.getState();
|
||||
const requestedItemIndex =
|
||||
index === "next"
|
||||
? currentItemIndex + 1
|
||||
: index === "previous"
|
||||
? currentItemIndex - 1
|
||||
: index;
|
||||
const prevItem = queueItems?.[currentItemIndex];
|
||||
const prevPlaySessionId = usePlaybackStore.getState().playsessionId;
|
||||
const prevMediaSourceId = usePlaybackStore.getState().mediaSource.id;
|
||||
|
||||
const item = queueItems?.[requestedItemIndex];
|
||||
|
||||
const prevMediaSource = usePlaybackStore.getState().mediaSource;
|
||||
|
||||
console.log("requestedItemIndex", queueItems);
|
||||
|
||||
if (!item?.Id) {
|
||||
console.error("No item found in queue");
|
||||
return;
|
||||
}
|
||||
if (item?.Type === "Audio" && userId) {
|
||||
|
||||
if (item.Type === "Audio" && userId) {
|
||||
const playbackUrl = generateAudioStreamUrl(
|
||||
item.Id,
|
||||
userId,
|
||||
@@ -675,153 +671,153 @@ export const playItemFromQueue = async (
|
||||
api.basePath,
|
||||
api.accessToken,
|
||||
);
|
||||
// console.log(item);
|
||||
playAudio(playbackUrl, item, undefined);
|
||||
setQueue(queueItems, requestedItemIndex);
|
||||
} else {
|
||||
if (!userId) {
|
||||
console.error("No user id provided");
|
||||
return;
|
||||
}
|
||||
if (!item.MediaSources?.[0]?.Id) {
|
||||
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({
|
||||
audioStreamIndex:
|
||||
prevItem?.Id === item.Id
|
||||
? prevMediaSource.audio.track
|
||||
: (item.MediaSources?.[0]?.DefaultAudioStreamIndex ?? 0),
|
||||
subtitleStreamIndex:
|
||||
prevItem?.Id === item.Id
|
||||
? prevMediaSource.subtitle.track
|
||||
: (item?.MediaSources?.[0]?.DefaultSubtitleStreamIndex ?? -1),
|
||||
itemId: item.Id,
|
||||
startTimeTicks: item.UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId: item.MediaSources?.[0].Id,
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
})
|
||||
).data;
|
||||
if (!mediaSource.MediaSources?.[0]?.Id) {
|
||||
throw new Error("Media source is undefined in playItemFromQueue");
|
||||
}
|
||||
|
||||
let itemName = item.Name;
|
||||
let episodeTitle = "";
|
||||
if (item.SeriesId && item.SeriesName) {
|
||||
itemName = item.SeriesName;
|
||||
episodeTitle = `S${item.ParentIndexNumber ?? 0}:E${
|
||||
item.IndexNumber ?? 0
|
||||
} ${item.Name}`;
|
||||
}
|
||||
|
||||
// Subtitle
|
||||
const subtitle = getSubtitle(
|
||||
mediaSource.MediaSources?.[0].DefaultSubtitleStreamIndex ?? "nosub",
|
||||
mediaSource.MediaSources?.[0].MediaStreams,
|
||||
);
|
||||
|
||||
console.log("subtitle", mediaSource);
|
||||
|
||||
// Audio
|
||||
const audio = {
|
||||
track: mediaSource.MediaSources?.[0].DefaultAudioStreamIndex ?? 0,
|
||||
allTracks: mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Audio",
|
||||
),
|
||||
};
|
||||
|
||||
// URL generation
|
||||
const urlOptions: URLSearchParams = {
|
||||
//@ts-ignore
|
||||
Static: true,
|
||||
tag: mediaSource.MediaSources?.[0].ETag,
|
||||
mediaSourceId: mediaSource.MediaSources?.[0].Id,
|
||||
deviceId: api?.deviceInfo.id,
|
||||
api_key: api?.accessToken,
|
||||
};
|
||||
const urlParams = new URLSearchParams(urlOptions).toString();
|
||||
let playbackUrl = `${api?.basePath}/Videos/${mediaSource.MediaSources?.[0].Id}/stream.${mediaSource.MediaSources?.[0].Container}?${urlParams}`;
|
||||
if (
|
||||
mediaSource.MediaSources?.[0].SupportsTranscoding &&
|
||||
mediaSource.MediaSources?.[0].TranscodingUrl
|
||||
) {
|
||||
playbackUrl = `${api.basePath}${mediaSource.MediaSources[0].TranscodingUrl}`;
|
||||
}
|
||||
|
||||
const videoTrack = mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Video",
|
||||
);
|
||||
|
||||
const mediaSegments = (
|
||||
await getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: item.Id ?? "",
|
||||
})
|
||||
)?.data;
|
||||
|
||||
// Report playback stop to jellyfin server for previous episode allowing next episode to report playback
|
||||
await getPlaystateApi(api).reportPlaybackStopped({
|
||||
playbackStopInfo: {
|
||||
Failed: false,
|
||||
ItemId: prevItem?.Id,
|
||||
MediaSourceId: prevMediaSourceId,
|
||||
PlaySessionId: prevPlaySessionId,
|
||||
},
|
||||
});
|
||||
|
||||
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,
|
||||
queueItems: queueItems,
|
||||
queueItemIndex: requestedItemIndex,
|
||||
});
|
||||
return "playing";
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
console.error("No user id provided");
|
||||
return;
|
||||
}
|
||||
|
||||
const mediaSourceId = item.MediaSources?.[0]?.Id;
|
||||
if (!mediaSourceId) {
|
||||
console.error("No media source id found");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!item.Name || !item.RunTimeTicks) {
|
||||
throw new Error("Item data incomplete in playItemFromQueue");
|
||||
}
|
||||
|
||||
const { playsessionId: prevPlaySessionId, mediaSource: prevMediaSource } =
|
||||
usePlaybackStore.getState();
|
||||
const prevItem = queueItems?.[currentItemIndex];
|
||||
|
||||
// Prepare promises for parallel execution
|
||||
const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex:
|
||||
prevItem?.Id === item.Id
|
||||
? prevMediaSource.audio.track
|
||||
: (item.MediaSources?.[0]?.DefaultAudioStreamIndex ?? 0),
|
||||
subtitleStreamIndex:
|
||||
prevItem?.Id === item.Id
|
||||
? prevMediaSource.subtitle.track
|
||||
: (item?.MediaSources?.[0]?.DefaultSubtitleStreamIndex ?? -1),
|
||||
itemId: item.Id,
|
||||
startTimeTicks: item.UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId: mediaSourceId,
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
|
||||
const segmentsPromise = getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: item.Id,
|
||||
});
|
||||
|
||||
const stopReportPromise = getPlaystateApi(api).reportPlaybackStopped({
|
||||
playbackStopInfo: {
|
||||
Failed: false,
|
||||
ItemId: prevItem?.Id,
|
||||
MediaSourceId: prevMediaSource.id,
|
||||
PlaySessionId: prevPlaySessionId,
|
||||
},
|
||||
});
|
||||
|
||||
// Await all promises
|
||||
const [playbackInfoResponse, segmentsResponse] = await Promise.all([
|
||||
playbackInfoPromise,
|
||||
segmentsPromise,
|
||||
stopReportPromise,
|
||||
]);
|
||||
|
||||
const mediaSource = playbackInfoResponse.data;
|
||||
const mediaSegments = segmentsResponse.data;
|
||||
|
||||
if (!mediaSource.MediaSources?.[0]?.Id) {
|
||||
throw new Error("Media source is undefined in playItemFromQueue");
|
||||
}
|
||||
|
||||
const source = mediaSource.MediaSources[0];
|
||||
|
||||
let itemName = item.Name;
|
||||
let episodeTitle = "";
|
||||
if (item.SeriesId && item.SeriesName) {
|
||||
itemName = item.SeriesName;
|
||||
episodeTitle = `S${item.ParentIndexNumber ?? 0}:E${
|
||||
item.IndexNumber ?? 0
|
||||
} ${item.Name}`;
|
||||
}
|
||||
|
||||
// Subtitle
|
||||
const subtitle = getSubtitle(
|
||||
source.DefaultSubtitleStreamIndex ?? "nosub",
|
||||
source.MediaStreams,
|
||||
);
|
||||
|
||||
// Audio
|
||||
const audio = {
|
||||
track: source.DefaultAudioStreamIndex ?? 0,
|
||||
allTracks: source.MediaStreams?.filter((value) => value.Type === "Audio"),
|
||||
};
|
||||
|
||||
// URL generation
|
||||
const urlOptions: URLSearchParams = {
|
||||
//@ts-expect-error
|
||||
Static: true,
|
||||
tag: source.ETag,
|
||||
mediaSourceId: source.Id,
|
||||
deviceId: api.deviceInfo.id,
|
||||
api_key: api.accessToken,
|
||||
};
|
||||
const urlParams = new URLSearchParams(urlOptions).toString();
|
||||
let playbackUrl = `${api.basePath}/Videos/${source.Id}/stream.${source.Container}?${urlParams}`;
|
||||
if (source.SupportsTranscoding && source.TranscodingUrl) {
|
||||
playbackUrl = `${api.basePath}${source.TranscodingUrl}`;
|
||||
}
|
||||
|
||||
const videoTrack = source.MediaStreams?.filter(
|
||||
(value) => value.Type === "Video",
|
||||
);
|
||||
|
||||
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: source.Container ?? "",
|
||||
id: source.Id,
|
||||
subtitle: {
|
||||
url: subtitle?.url,
|
||||
track: subtitle?.track ?? -1,
|
||||
format: subtitle?.format ?? "nosub",
|
||||
allTracks: source.MediaStreams?.filter(
|
||||
(value) => value.Type === "Subtitle",
|
||||
),
|
||||
enable: subtitle?.enable ?? false,
|
||||
},
|
||||
audio: audio,
|
||||
},
|
||||
playbackStream: playbackUrl,
|
||||
playsessionId: mediaSource.PlaySessionId,
|
||||
userDataPlayedPositionTicks: item.UserData?.PlaybackPositionTicks ?? 0,
|
||||
userId,
|
||||
queueItems: queueItems,
|
||||
queueItemIndex: requestedItemIndex,
|
||||
});
|
||||
|
||||
return "playing"; // Return any value to end mutation pending status
|
||||
};
|
||||
|
||||
@@ -850,24 +846,23 @@ export const changeSubtitleTrack = (
|
||||
const requiredSubtitle = allTracks.filter(
|
||||
(track) => track.Index === trackIndex,
|
||||
);
|
||||
const prevState = usePlaybackStore.getState();
|
||||
prevState.mediaSource.subtitle = {
|
||||
url: requiredSubtitle?.[0]?.DeliveryUrl,
|
||||
track: trackIndex,
|
||||
format: requiredSubtitle?.[0]?.Codec,
|
||||
allTracks,
|
||||
enable: trackIndex !== -1,
|
||||
};
|
||||
usePlaybackStore.setState(prevState);
|
||||
usePlaybackStore.setState((state) => {
|
||||
state.mediaSource.subtitle = {
|
||||
url: requiredSubtitle?.[0]?.DeliveryUrl,
|
||||
track: trackIndex,
|
||||
format: requiredSubtitle?.[0]?.Codec,
|
||||
allTracks,
|
||||
enable: trackIndex !== -1,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export const toggleSubtitleTrack = () => {
|
||||
const prevState = usePlaybackStore.getState();
|
||||
if (prevState.mediaSource.subtitle.track !== -1) {
|
||||
prevState.mediaSource.subtitle.enable =
|
||||
!prevState.mediaSource.subtitle.enable;
|
||||
usePlaybackStore.setState(prevState);
|
||||
}
|
||||
usePlaybackStore.setState((state) => {
|
||||
if (state.mediaSource.subtitle.track !== -1) {
|
||||
state.mediaSource.subtitle.enable = !state.mediaSource.subtitle.enable;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -898,14 +893,10 @@ export const changeAudioTrack = async (trackIndex: number, api: Api) => {
|
||||
},
|
||||
})
|
||||
).data;
|
||||
prevState.mediaSource.audio.track = trackIndex;
|
||||
prevState.mediaSource.id = mediaSource.MediaSources?.[0].Id ?? "";
|
||||
prevState.mediaSource.container =
|
||||
mediaSource.MediaSources?.[0].Container ?? "";
|
||||
|
||||
// URL generation
|
||||
const urlOptions: URLSearchParams = {
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
Static: true,
|
||||
tag: mediaSource.MediaSources?.[0].ETag,
|
||||
mediaSourceId: mediaSource.MediaSources?.[0].Id,
|
||||
@@ -921,11 +912,13 @@ export const changeAudioTrack = async (trackIndex: number, api: Api) => {
|
||||
playbackUrl = `${api.basePath}${mediaSource.MediaSources[0].TranscodingUrl}`;
|
||||
}
|
||||
|
||||
prevState.playbackStream = playbackUrl;
|
||||
// prevState.item = startPosition;
|
||||
prevState.playsessionId = mediaSource.PlaySessionId;
|
||||
|
||||
usePlaybackStore.setState(prevState);
|
||||
usePlaybackStore.setState((state) => {
|
||||
state.mediaSource.audio.track = trackIndex;
|
||||
state.mediaSource.id = mediaSource.MediaSources?.[0].Id ?? "";
|
||||
state.mediaSource.container = mediaSource.MediaSources?.[0].Container ?? "";
|
||||
state.playbackStream = playbackUrl;
|
||||
state.playsessionId = mediaSource.PlaySessionId;
|
||||
});
|
||||
// const currentItemIndex = useQueue.getState().currentItemIndex;
|
||||
// playItemFromQueue(currentItemIndex, prevState.userId, api);
|
||||
};
|
||||
Reference in new issue
Block a user