Files
Blink/src/utils/store/playback.ts
T
1xDed c2ec314b39
Continuous Integration / build_web (push) Failing after 1s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
fix(player): keep 4K HEVC playback off the software encoder
Use an HLS fMP4 profile that copies compatible HEVC video and transcodes only the audio, so servers without hardware acceleration no longer stall on a 4K H.264 transcode. Add an auto/1080p/720p/480p quality selector and restart playback at the same position when the profile changes.
2026-12-05 02:06:12 +03:00

1207 lines
34 KiB
TypeScript

import type { Api } from "@jellyfin/sdk";
import {
type BaseItemDto,
ItemFields,
type MediaSegmentDtoQueryResult,
type MediaStream,
type PlaybackInfoResponse,
PlayMethod,
} from "@jellyfin/sdk/lib/generated-client";
import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api";
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import { getMediaSegmentApi } from "@jellyfin/sdk/lib/utils/api/media-segment-api";
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-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 { addSegmentsFromChapters } from "../methods/mediaSegments";
import { markLocalMediaSwitch } from "../methods/mediaSwitch";
import {
getVideoPlaybackProfile,
setVideoPlaybackQuality,
} from "../playback-profiles";
import {
getPlayerMuted,
getPlayerVolume,
setPlaybackQuality,
setPlayerMuted,
setPlayerVolume,
} from "../storage/player";
import type audioPlaybackInfo from "../types/audioPlaybackInfo";
import type { PlaybackQualityPreset } from "../types/playbackQuality";
import type subtitlePlaybackInfo from "../types/subtitlePlaybackInfo";
import {
generateAudioStreamUrl,
playAudio,
stopPlayback,
} from "./audioPlayback";
import useQueue, { setQueue } from "./queue";
type PlaybackStoreState = {
mediaSource: {
videoTrack: number;
audioTrack: number;
container: string;
id: string | undefined;
subtitle: subtitlePlaybackInfo;
audio: audioPlaybackInfo;
bitrate?: number;
videoCodec?: string;
audioCodec?: string;
playMethod?: PlayMethod;
transcodingUrl?: string;
};
playbackStream: string;
playsessionId: string | undefined | null;
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;
/**
* Used to show the stats for nerds dialog
*/
showStatsForNerds: 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: ReturnType<typeof setTimeout> | null;
};
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;
/**
* Toggle the stats for nerds dialog
*/
toggleShowStatsForNerds: () => 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;
initializeVolume: () => Promise<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;
handleOnSeek: (seconds: number) => void;
};
export const usePlaybackStore = create<
PlaybackStoreState & PlaybackStoreActions
>()(
immer((set, get) => ({
mediaSource: {
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,
showStatsForNerds: false,
},
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
});
setPlayerVolume("video", volume);
setPlayerMuted("video", volume === 0);
get().tiggerVolumeIndicator(); // Trigger volume change indicator
},
increaseVolumeByStep: (step) => {
set((state) => {
const newVolume = Math.min(
1,
Math.max(0, state.playerState.volume + step),
);
state.playerState.volume = newVolume;
setPlayerVolume("video", newVolume);
});
get().tiggerVolumeIndicator(); // Trigger volume change indicator
},
decreaseVolumeByStep: (step) => {
set((state) => {
const newVolume = Math.min(
1,
Math.max(0, state.playerState.volume - step),
);
state.playerState.volume = newVolume;
setPlayerVolume("video", newVolume);
});
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: (ticks) => {
const { nextSegmentIndex, activeSegmentId, metadata } = get();
if (activeSegmentId) {
const activeSegment = metadata.mediaSegments?.Items?.find(
(s) => s.Id === activeSegmentId,
);
if (activeSegment && ticks >= (activeSegment.EndTicks ?? ticks)) {
// If the current time is past the active segment's end time, clear it.
set((state) => {
state.activeSegmentId = null;
});
}
}
if (nextSegmentIndex !== -1) {
const nextSegment = metadata.mediaSegments?.Items?.[nextSegmentIndex];
if (nextSegment && ticks >= (nextSegment.StartTicks ?? ticks + 1)) {
// If the current time is past the next segment's start time, set it as active.
// clearActiveSegment();
set((state) => {
state.activeSegmentId = null;
state.nextSegmentIndex = nextSegmentIndex + 1;
state.activeSegmentId = nextSegment?.Id ?? null;
});
}
}
set((state) => {
state.playerState.currentTime = ticks;
});
},
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,
bitrate?: number,
videoCodec?: string,
audioCodec?: string,
playMethod?: PlayMethod,
transcodingUrl?: string,
) =>
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;
state.mediaSource.bitrate = bitrate;
state.mediaSource.videoCodec = videoCodec;
state.mediaSource.audioCodec = audioCodec;
state.mediaSource.playMethod = playMethod;
state.mediaSource.transcodingUrl = transcodingUrl;
}),
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: () => {
const isMuted = !get().playerState.isPlayerMuted;
set((state) => {
state.playerState.isPlayerMuted = isMuted;
});
setPlayerMuted("video", isMuted);
},
setIsLoading: (isLoading) =>
set((state) => {
state.playerState.isLoading = isLoading;
}),
toggleShowStatsForNerds: () =>
set((state) => {
state.playerState.showStatsForNerds =
!state.playerState.showStatsForNerds;
}),
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);
});
},
initializeVolume: async () => {
const volume = await getPlayerVolume("video");
const isMuted = await getPlayerMuted("video");
set((state) => {
state.playerState.volume = volume;
state.playerState.isPlayerMuted = isMuted;
});
},
// -- 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;
},
},
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;
}
return false;
})[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;
}
return false;
});
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) {
return;
}
get()._playerActions.seekTo(ticksToSec(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;
});
},
handleOnSeek: (seconds) => {
const ticks = secToTicks(seconds);
const segments = get().metadata.mediaSegments?.Items;
if (!segments || segments.length === 0) {
return;
}
const segment = segments.find(
(s) =>
(s.StartTicks ?? ticks) <= ticks && (s.EndTicks ?? ticks) > ticks,
);
const nextIndex = segments.findIndex(
(s) => (s.StartTicks ?? ticks) > ticks,
);
if (segment?.Id) {
// If the segment is found, set it as active
set({
activeSegmentId: segment.Id,
nextSegmentIndex: nextIndex !== -1 ? nextIndex : segments.length,
});
} else {
// If no segment is found, clear the active segment
set({
activeSegmentId: null,
nextSegmentIndex: nextIndex !== -1 ? nextIndex : segments.length,
});
}
},
})),
);
// Initialize volume from storage
// usePlaybackStore.getState().initializeVolume();
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;
// Transfers pass an explicit start position; it must win over the
// item's saved resume point (otherwise the video jumps back).
state.playerState.currentTime =
args.metadata.userDataLastPlayedPositionTicks ??
args.userDataPlayedPositionTicks;
state.userId = args.userId;
state.playerState.isPlayerPlaying = true;
state.playerState.isPlayerReady = false; // Reset player ready state
state.playerState.isBuffering = true;
});
setQueue(args.queueItems, args.queueItemIndex ?? 0);
};
export const initializePlayback = async (args: {
api: Api;
userId: string;
item: BaseItemDto;
mediaSource: PlaybackInfoResponse;
mediaSegments?: MediaSegmentDtoQueryResult;
queueItems: BaseItemDto[];
queueIndex: number;
startPositionTicks?: number;
audioStreamIndex?: number;
subtitleStreamIndex?: number;
}) => {
const {
api,
userId,
item,
mediaSource,
mediaSegments,
queueItems,
queueIndex,
startPositionTicks,
audioStreamIndex,
subtitleStreamIndex,
} = args;
// Only one medium at a time: starting a video stops music playback.
markLocalMediaSwitch();
stopPlayback();
if (!mediaSource.MediaSources?.[0]?.Id) {
throw new Error("Media source is undefined in initializePlayback");
}
const source = mediaSource.MediaSources[0];
const currentUser = (await getUserApi(api).getCurrentUser()).data;
let chapters = item.Chapters;
if (!Array.isArray(chapters) && !mediaSegments?.Items?.length && item.Id) {
try {
const fullItem = (
await getLibraryApi(api).getItems({
ids: [item.Id],
userId,
fields: [ItemFields.Chapters],
})
).data.Items?.[0];
chapters = fullItem?.Chapters;
} catch (error) {
console.warn("Не удалось загрузить главы для сегментов", error);
}
}
const segments = addSegmentsFromChapters(
Array.isArray(chapters) && chapters !== item.Chapters
? { ...item, Chapters: chapters }
: item,
mediaSegments,
item.RunTimeTicks ?? source.RunTimeTicks,
);
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 userSubtitleLanguagePreference =
currentUser?.Configuration?.SubtitleLanguagePreference;
const allSubtitles = source.MediaStreams?.filter(
(stream) => stream.Type === "Subtitle",
);
const preferredSubtitle =
allSubtitles?.find(
(sub) => sub.Language === userSubtitleLanguagePreference,
) || null;
const subtitle = getSubtitle(
subtitleStreamIndex ??
preferredSubtitle?.Index ??
source.DefaultSubtitleStreamIndex ??
-1,
source.MediaStreams,
);
// Audio
const userAudioLanguagePreference =
currentUser?.Configuration?.AudioLanguagePreference;
const allAudioTracks = source.MediaStreams?.filter(
(value) => value.Type === "Audio",
);
const preferredAudioTrack =
allAudioTracks?.find(
(track) => track.Language === userAudioLanguagePreference,
) ||
allAudioTracks?.find((track) => track.IsDefault) ||
allAudioTracks?.[0];
const audio = {
track:
audioStreamIndex ??
preferredAudioTrack?.Index ??
source.DefaultAudioStreamIndex ??
0,
allTracks: allAudioTracks,
};
// URL generation
const urlOptions: URLSearchParams = {
//@ts-expect-error
Static: true,
tag: source.ETag,
mediaSourceId: source.Id,
deviceId: api.deviceInfo.id,
ApiKey: api.accessToken,
};
let playMethod: PlayMethod = PlayMethod.Transcode;
if (source.SupportsDirectPlay) {
playMethod = PlayMethod.DirectPlay;
} else if (source.SupportsDirectStream) {
playMethod = PlayMethod.DirectStream;
}
const urlParams = new URLSearchParams(urlOptions).toString();
let playbackUrl = `${api.basePath}/Videos/${source.Id}/stream.${source.Container}?${urlParams}`;
if (playMethod === PlayMethod.Transcode && source.TranscodingUrl) {
playbackUrl = `${api.basePath}${source.TranscodingUrl}`;
}
const videoTrack = source.MediaStreams?.filter(
(value) => value.Type === "Video",
);
playItem({
metadata: {
itemName: itemName ?? "",
episodeTitle: episodeTitle,
isEpisode: !!item.SeriesId,
itemDuration: item.RunTimeTicks ?? 0,
item: item,
mediaSegments: segments,
userDataLastPlayedPositionTicks:
startPositionTicks ?? item.UserData?.PlaybackPositionTicks ?? 0,
},
mediaSource: {
videoTrack: videoTrack?.[0]?.Index ?? 0,
audioTrack: audio.track,
container: source.Container ?? "",
id: source.Id ?? undefined,
subtitle: {
url: subtitle?.url,
track: subtitle?.track ?? -1,
format: subtitle?.format ?? "nosub",
allTracks: allSubtitles,
enable: subtitle?.enable ?? false,
},
audio: audio,
bitrate: source.Bitrate ?? undefined,
videoCodec: videoTrack?.[0]?.Codec ?? undefined,
audioCodec:
audio.allTracks?.find((t) => t.Index === audio.track)?.Codec ??
undefined,
playMethod: playMethod,
transcodingUrl: source.TranscodingUrl ?? undefined,
},
playbackStream: playbackUrl,
playsessionId: mediaSource.PlaySessionId,
userDataPlayedPositionTicks: item.UserData?.PlaybackPositionTicks ?? 0,
userId,
queueItems: queueItems ?? [],
queueItemIndex: queueIndex,
});
};
/**
* Restarts the current video with another quality preset while keeping the
* playback position, audio and subtitle selection.
*/
export const changePlaybackQuality = async (
quality: PlaybackQualityPreset,
api: Api,
) => {
const state = usePlaybackStore.getState();
const item = state.metadata.item;
const userId = state.userId;
if (!api || !item?.Id || !userId) return;
const positionTicks = state.playerState.currentTime ?? 0;
const wasPlaying = state.playerState.isPlayerPlaying;
setVideoPlaybackQuality(quality);
await setPlaybackQuality(quality);
const { data } = await getMediaInfoApi(api).getPostedPlaybackInfo({
itemId: item.Id,
userId,
mediaSourceId: state.mediaSource.id,
startTimeTicks: positionTicks,
audioStreamIndex: state.mediaSource.audio.track,
subtitleStreamIndex: state.mediaSource.subtitle.track,
playbackInfoDto: {
DeviceProfile: await getVideoPlaybackProfile(
state.mediaSource.videoCodec,
),
},
});
// The old transcode must be stopped before the new one starts, otherwise
// both continue to consume server CPU.
await getSessionApi(api)
.reportPlaybackStopped({
playbackStopInfo: {
Failed: false,
ItemId: item.Id,
MediaSourceId: state.mediaSource.id,
PlaySessionId: state.playsessionId,
PositionTicks: positionTicks,
},
})
.catch((error) => {
console.warn("Не удалось остановить прошлую сессию", error);
});
await initializePlayback({
api,
userId,
item,
mediaSource: data,
mediaSegments: state.metadata.mediaSegments,
queueItems: useQueue.getState().tracks ?? [],
queueIndex: useQueue.getState().currentItemIndex,
startPositionTicks: positionTicks,
audioStreamIndex: state.mediaSource.audio.track,
subtitleStreamIndex: state.mediaSource.subtitle.track,
});
if (!wasPlaying) {
usePlaybackStore.setState((next) => {
next.playerState.isPlayerPlaying = false;
});
}
};
export const playItemFromQueue = async (
index: "next" | "previous" | number,
userId: string | undefined,
api: Api | undefined,
) => {
if (!api) {
console.error("Unable to play item from from queue. No API provided");
return;
}
const { tracks: queueItems, currentItemIndex } = useQueue.getState();
const requestedItemIndex =
index === "next"
? currentItemIndex + 1
: index === "previous"
? currentItemIndex - 1
: index;
const item = queueItems?.[requestedItemIndex];
if (!item?.Id) {
console.error("No item found in queue");
return;
}
if (item.Type === "Audio" && userId) {
const playbackUrl = generateAudioStreamUrl(
item.Id,
userId,
api.deviceInfo.id,
api.basePath,
api.accessToken,
);
playAudio(playbackUrl, item, undefined);
setQueue(queueItems, 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];
const audioStreamIndex =
prevItem?.Id === item.Id
? prevMediaSource.audio.track
: (item.MediaSources?.[0]?.DefaultAudioStreamIndex ?? 0);
const subtitleStreamIndex =
prevItem?.Id === item.Id
? prevMediaSource.subtitle.track
: (item?.MediaSources?.[0]?.DefaultSubtitleStreamIndex ?? -1);
const sourceVideoCodec = item.MediaSources?.[0]?.MediaStreams?.find(
(stream) => stream.Type === "Video",
)?.Codec;
// Prepare promises for parallel execution
const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex,
subtitleStreamIndex,
itemId: item.Id,
startTimeTicks: item.UserData?.PlaybackPositionTicks,
userId: userId,
mediaSourceId: mediaSourceId,
playbackInfoDto: {
DeviceProfile: await getVideoPlaybackProfile(sourceVideoCodec),
},
});
const segmentsPromise = getMediaSegmentApi(api).getItemSegments({
itemId: item.Id,
});
const stopReportPromise = getSessionApi(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;
initializePlayback({
api,
userId,
item,
mediaSource,
mediaSegments,
queueItems: queueItems ?? [],
queueIndex: requestedItemIndex,
audioStreamIndex,
subtitleStreamIndex,
});
return "playing"; // Return any value to end mutation pending status
};
interface PlaybackDataLoadState {
isPending: boolean;
setisPending: (loading: boolean) => void;
}
export const usePlaybackDataLoadStore =
createWithEqualityFn<PlaybackDataLoadState>(
(set) => ({
isPending: false,
setisPending: (loading: boolean) =>
set((state: PlaybackDataLoadState) => ({
...state,
isPending: loading,
})),
}),
shallow,
);
export const changeSubtitleTrack = (
trackIndex: number,
allTracks: MediaStream[],
) => {
const requiredSubtitle = allTracks.filter(
(track) => track.Index === trackIndex,
);
usePlaybackStore.setState((state) => {
state.mediaSource.subtitle = {
url: requiredSubtitle?.[0]?.DeliveryUrl,
track: trackIndex,
format: requiredSubtitle?.[0]?.Codec,
allTracks,
enable: trackIndex !== -1,
};
});
};
export const toggleSubtitleTrack = () => {
usePlaybackStore.setState((state) => {
if (state.mediaSource.subtitle.track !== -1) {
state.mediaSource.subtitle.enable = !state.mediaSource.subtitle.enable;
}
});
};
/**
*
* @param trackIndex index of the new audio track
* @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) => {
const prevState = usePlaybackStore.getState();
if (!prevState.metadata.item?.Id) {
throw new Error("item is undefined in changeAudioTrack");
}
if (!prevState.metadata.item.MediaSources?.[0].Id) {
throw new Error("Media source id is undefined in changeAudioTrack");
}
const positionTicks =
prevState.playerState.currentTime ??
prevState.metadata.item.UserData?.PlaybackPositionTicks ??
0;
const mediaSource = (
await getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex: trackIndex,
subtitleStreamIndex: prevState.mediaSource.subtitle.track,
itemId: prevState.metadata.item.Id,
startTimeTicks: positionTicks,
userId: prevState.userId,
mediaSourceId: prevState.metadata.item.MediaSources?.[0].Id,
playbackInfoDto: {
DeviceProfile: await getVideoPlaybackProfile(
prevState.mediaSource.videoCodec,
),
},
})
).data;
// URL generation
const urlOptions: URLSearchParams = {
//@ts-expect-error
Static: true,
tag: mediaSource.MediaSources?.[0].ETag,
mediaSourceId: mediaSource.MediaSources?.[0].Id,
deviceId: api?.deviceInfo.id,
ApiKey: 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}`;
}
await getSessionApi(api)
.reportPlaybackStopped({
playbackStopInfo: {
Failed: false,
ItemId: prevState.metadata.item.Id,
MediaSourceId: prevState.mediaSource.id,
PlaySessionId: prevState.playsessionId,
PositionTicks: positionTicks,
},
})
.catch((error) => {
console.warn("Не удалось остановить прошлую сессию", error);
});
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;
state.metadata.userDataLastPlayedPositionTicks = positionTicks;
state.playerState.currentTime = positionTicks;
state.playerState.isPlayerReady = false;
state.playerState.isBuffering = true;
});
// const currentItemIndex = useQueue.getState().currentItemIndex;
// playItemFromQueue(currentItemIndex, prevState.userId, api);
};