fix(player): keep 4K HEVC playback off the software encoder
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

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.
This commit is contained in:
1xDed committed 2026-12-05 02:06:12 +03:00
1 parent a390df82e9
commit c2ec314b39
7 files changed
+491 -38

No files matched your search

@@ -7,6 +7,7 @@ import {
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import { toNumber } from "lodash"; import { toNumber } from "lodash";
import { useSnackbar } from "notistack";
import React, { import React, {
type ChangeEventHandler, type ChangeEventHandler,
useCallback, useCallback,
@@ -18,15 +19,23 @@ import React, {
import { useShallow } from "zustand/shallow"; import { useShallow } from "zustand/shallow";
import { import {
getAutoSkipSegments, getAutoSkipSegments,
getPlaybackQuality,
setAutoSkipSegments, setAutoSkipSegments,
} from "@/utils/storage/player"; } from "@/utils/storage/player";
import { useApiInContext } from "@/utils/store/api"; import { useApiInContext } from "@/utils/store/api";
import { import {
changeAudioTrack, changeAudioTrack,
changePlaybackQuality,
changeSubtitleTrack, changeSubtitleTrack,
usePlaybackStore, usePlaybackStore,
} from "@/utils/store/playback"; } from "@/utils/store/playback";
import useSyncPlayback from "@/utils/store/syncPlayback"; import useSyncPlayback from "@/utils/store/syncPlayback";
import {
DEFAULT_PLAYBACK_QUALITY,
isPlaybackQualityPreset,
PLAYBACK_QUALITY_OPTIONS,
type PlaybackQualityPreset,
} from "@/utils/types/playbackQuality";
type VideoPlayerSettingsMenuProps = { type VideoPlayerSettingsMenuProps = {
settingsMenuRef: HTMLButtonElement | null; settingsMenuRef: HTMLButtonElement | null;
@@ -42,6 +51,7 @@ const VideoPlayerSettingsMenu = ({
}, [settingsMenuRef]); }, [settingsMenuRef]);
const api = useApiInContext((state) => state.api); const api = useApiInContext((state) => state.api);
const { enqueueSnackbar } = useSnackbar();
const { const {
mediaSource, mediaSource,
@@ -92,6 +102,39 @@ const VideoPlayerSettingsMenu = ({
}); });
}; };
const [quality, setQuality] = useState<PlaybackQualityPreset>(
DEFAULT_PLAYBACK_QUALITY,
);
const [qualityIsChanging, setQualityIsChanging] = useState(false);
useEffect(() => {
let cancelled = false;
getPlaybackQuality().then((savedQuality) => {
if (!cancelled) setQuality(savedQuality);
});
return () => {
cancelled = true;
};
}, []);
const handleQualityChange: ChangeEventHandler<
HTMLInputElement | HTMLTextAreaElement
> = (e) => {
const nextQuality = e.target.value;
if (!api || !isPlaybackQualityPreset(nextQuality)) return;
setQuality(nextQuality);
setQualityIsChanging(true);
changePlaybackQuality(nextQuality, api)
.then(() => handleClose())
.catch((error) => {
enqueueSnackbar(`Не удалось изменить качество: ${error}`, {
variant: "error",
});
})
.finally(() => setQualityIsChanging(false));
};
const [subtitleIsChanging, startSubtitleChange] = useTransition(); const [subtitleIsChanging, startSubtitleChange] = useTransition();
const handleSubtitleChange: ChangeEventHandler< const handleSubtitleChange: ChangeEventHandler<
HTMLInputElement | HTMLTextAreaElement HTMLInputElement | HTMLTextAreaElement
@@ -154,6 +197,21 @@ const VideoPlayerSettingsMenu = ({
horizontal: "right", horizontal: "right",
}} }}
> >
<TextField
select
label="Качество"
variant="outlined"
value={quality}
onChange={handleQualityChange}
fullWidth
disabled={qualityIsChanging}
>
{PLAYBACK_QUALITY_OPTIONS.map((option) => (
<MenuItem key={option.id} value={option.id}>
{option.label}
</MenuItem>
))}
</TextField>
<TextField <TextField
select select
label="Аудио" label="Аудио"
+5 -2
View File
@@ -12,7 +12,7 @@ import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
import { getMediaSegmentApi } from "@jellyfin/sdk/lib/utils/api/media-segment-api"; import { getMediaSegmentApi } from "@jellyfin/sdk/lib/utils/api/media-segment-api";
import { getPlaylistApi } from "@jellyfin/sdk/lib/utils/api/playlist-api"; import { getPlaylistApi } from "@jellyfin/sdk/lib/utils/api/playlist-api";
import { getShowApi } from "@jellyfin/sdk/lib/utils/api/show-api"; import { getShowApi } from "@jellyfin/sdk/lib/utils/api/show-api";
import playbackProfile from "@/utils/playback-profiles"; import { getVideoPlaybackProfile } from "@/utils/playback-profiles";
export async function getNextEpisode( export async function getNextEpisode(
api: Api, api: Api,
@@ -222,6 +222,9 @@ export async function getPlaybackInfo(
targetItem.MediaSources?.[0].DefaultAudioStreamIndex ?? 0; targetItem.MediaSources?.[0].DefaultAudioStreamIndex ?? 0;
} }
const sourceVideoCodec = targetItem.MediaSources?.[0]?.MediaStreams?.find(
(stream: { Type?: string | null }) => stream.Type === "Video",
)?.Codec;
const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({ const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex: Number(audioStreamIndex), audioStreamIndex: Number(audioStreamIndex),
subtitleStreamIndex: currentSubTrack === "nosub" ? -1 : currentSubTrack, subtitleStreamIndex: currentSubTrack === "nosub" ? -1 : currentSubTrack,
@@ -231,7 +234,7 @@ export async function getPlaybackInfo(
userId: userId, userId: userId,
mediaSourceId: targetItem.MediaSources?.[0]?.Id, mediaSourceId: targetItem.MediaSources?.[0]?.Id,
playbackInfoDto: { playbackInfoDto: {
DeviceProfile: playbackProfile, DeviceProfile: await getVideoPlaybackProfile(sourceVideoCodec),
}, },
}); });
+182 -25
View File
@@ -18,42 +18,199 @@
* most browsers (like H265 or AV1), so the few browsers that support them benefits from less bandwidth * most browsers (like H265 or AV1), so the few browsers that support them benefits from less bandwidth
* usage (although this will rarely happen: The most expected situations when transcoding * usage (although this will rarely happen: The most expected situations when transcoding
* is when the media's codecs are more "powerful" than what the client is capable of, and H265 is * is when the media's codecs are more "powerful" than what the client is capable of, and H265 is
* pretty modern, so it would've been catched-up by MediaCapabilities. However, * pretty modern, so it would've been catched-up by MediaCapabilities. However, we
* we must take into account the playback of really old codecs like MPEG or H263, * must take into account the playback of really old codecs like MPEG or H263,
* whose support are probably likely going to be removed from browsers, * whose support are probably likely going to be removed from browsers,
* so MediaCapabilities reports as unsupported, so we would be going from an "inferior" codec to a * so MediaCapabilities reports as unsupported, so we would be going from an "inferior" codec to a
* "superior" codec in this situation) * "superior" codec in this situation)
*/ */
import type { DeviceProfile } from '@jellyfin/sdk/lib/generated-client'; import {
import { getCodecProfiles } from './helpers/codec-profiles'; type CodecProfile,
import { getDirectPlayProfiles } from './directplay-profile'; CodecType,
import { getTranscodingProfiles } from './transcoding-profile'; type DeviceProfile,
import { getSubtitleProfiles } from './subtitle-profile'; type ProfileCondition,
import { getResponseProfiles } from './response-profile'; ProfileConditionType,
ProfileConditionValue,
} from "@jellyfin/sdk/lib/generated-client";
import { getPlaybackQuality } from "@/utils/storage/player";
import {
DEFAULT_PLAYBACK_QUALITY,
getPlaybackQualityOption,
type PlaybackQualityOption,
type PlaybackQualityPreset,
} from "@/utils/types/playbackQuality";
import { getDirectPlayProfiles } from "./directplay-profile";
import { getCodecProfiles } from "./helpers/codec-profiles";
import { getSupportedFmp4VideoCodecs } from "./helpers/fmp4-video-formats";
import { getResponseProfiles } from "./response-profile";
import { getSubtitleProfiles } from "./subtitle-profile";
import { getTranscodingProfiles } from "./transcoding-profile";
let currentQuality: PlaybackQualityPreset = DEFAULT_PLAYBACK_QUALITY;
const qualityLoaded = getPlaybackQuality()
.then((quality) => {
currentQuality = quality;
})
.catch(() => {
currentQuality = DEFAULT_PLAYBACK_QUALITY;
});
/** /**
* Creates a device profile containing supported codecs for the active Cast device. * The active quality is cached here so playback requests can read the preset
* synchronously after the initial load.
*/
export const getVideoPlaybackQuality = () => currentQuality;
export const setVideoPlaybackQuality = (quality: PlaybackQualityPreset) => {
currentQuality = quality;
};
const addResolutionCap = (
codecProfiles: CodecProfile[],
codec: "h264" | "hevc",
maxWidth: number,
maxHeight: number,
) => {
const sizeConditions: ProfileCondition[] = [
{
Condition: ProfileConditionType.LessThanEqual,
Property: ProfileConditionValue.Width,
Value: maxWidth.toString(),
IsRequired: false,
},
{
Condition: ProfileConditionType.LessThanEqual,
Property: ProfileConditionValue.Height,
Value: maxHeight.toString(),
IsRequired: false,
},
];
for (const codecProfile of codecProfiles) {
if (codecProfile.Type === CodecType.Video && codecProfile.Codec === codec) {
codecProfile.Conditions = [
...(codecProfile.Conditions ?? []).filter(
(condition) =>
condition.Property !== ProfileConditionValue.Width &&
condition.Property !== ProfileConditionValue.Height,
),
...sizeConditions,
];
}
}
};
/**
* Creates a device profile containing supported codecs for the active
* playback quality.
* *
* @param videoTestElement - Dummy video element for compatibility tests * @param videoTestElement - Dummy video element for compatibility tests
*/ */
function getDeviceProfile(videoTestElement: HTMLVideoElement): DeviceProfile { function getDeviceProfile(
// MaxStaticBitrate seems to be for offline sync only videoTestElement: HTMLVideoElement,
return { option: PlaybackQualityOption,
MaxStreamingBitrate: 120_000_000, ): DeviceProfile {
MaxStaticBitrate: 0, const codecProfiles = getCodecProfiles(videoTestElement);
MusicStreamingTranscodingBitrate: Math.min(120_000_000, 192_000),
DirectPlayProfiles: getDirectPlayProfiles(videoTestElement), if (option.h264MaxWidth && option.h264MaxHeight) {
TranscodingProfiles: getTranscodingProfiles(videoTestElement), addResolutionCap(
ContainerProfiles: [], codecProfiles,
CodecProfiles: getCodecProfiles(videoTestElement), "h264",
SubtitleProfiles: getSubtitleProfiles(), option.h264MaxWidth,
//@ts-expect-error option.h264MaxHeight,
ResponseProfiles: getResponseProfiles() );
}; }
if (option.hevcMaxWidth && option.hevcMaxHeight) {
addResolutionCap(
codecProfiles,
"hevc",
option.hevcMaxWidth,
option.hevcMaxHeight,
);
}
// MaxStaticBitrate seems to be for offline sync only
return {
MaxStreamingBitrate: option.maxBitrate,
MaxStaticBitrate: 0,
MusicStreamingTranscodingBitrate: Math.min(option.maxBitrate, 192_000),
DirectPlayProfiles: getDirectPlayProfiles(videoTestElement),
TranscodingProfiles: getTranscodingProfiles(
videoTestElement,
option.preferHevcCopy,
),
ContainerProfiles: [],
CodecProfiles: codecProfiles,
SubtitleProfiles: getSubtitleProfiles(),
//@ts-expect-error
ResponseProfiles: getResponseProfiles(),
};
} }
const videoTestElement = document.createElement('video'); const videoTestElement = document.createElement("video");
const playbackProfile = getDeviceProfile(videoTestElement);
const canCopyHevc = () =>
getSupportedFmp4VideoCodecs(videoTestElement).includes("hevc");
/**
* "Auto" is source-aware: compatible HEVC is copied into HLS fMP4 without
* re-encoding, while H.264 sources are capped at 1080p for software encoding.
*/
const resolveQualityOption = (
quality: PlaybackQualityPreset,
sourceVideoCodec?: string | null,
): PlaybackQualityOption => {
const option = getPlaybackQualityOption(quality);
if (quality !== "auto") {
return option;
}
const isHevc = sourceVideoCodec?.toLowerCase() === "hevc";
if (isHevc && canCopyHevc()) {
return {
...option,
maxBitrate: 25_000_000,
h264MaxWidth: undefined,
h264MaxHeight: undefined,
hevcMaxWidth: 3840,
hevcMaxHeight: 2160,
preferHevcCopy: true,
};
}
return {
...option,
maxBitrate: 8_000_000,
h264MaxWidth: 1920,
h264MaxHeight: 1080,
hevcMaxWidth: 1920,
hevcMaxHeight: 1080,
preferHevcCopy: false,
};
};
/**
* Returns the device profile with the selected video quality. Waits for the
* persisted quality preference during the first call.
*
* @param sourceVideoCodec codec of the item being played, used by "auto"
*/
export const getVideoPlaybackProfile = async (
sourceVideoCodec?: string | null,
): Promise<DeviceProfile> => {
await qualityLoaded;
return getDeviceProfile(
videoTestElement,
resolveQualityOption(currentQuality, sourceVideoCodec),
);
};
const playbackProfile = getDeviceProfile(
videoTestElement,
getPlaybackQualityOption(DEFAULT_PLAYBACK_QUALITY),
);
export default playbackProfile; export default playbackProfile;
@@ -2,6 +2,11 @@
* @deprecated - Check @/utils/playback-profiles/index * @deprecated - Check @/utils/playback-profiles/index
*/ */
import {
DlnaProfileType,
EncodingContext,
type TranscodingProfile,
} from "@jellyfin/sdk/lib/generated-client";
import { import {
isAndroid, isAndroid,
isApple, isApple,
@@ -10,12 +15,8 @@ import {
isTizen, isTizen,
isTv, isTv,
} from "@/utils/browser-detection"; } from "@/utils/browser-detection";
import {
DlnaProfileType,
EncodingContext,
type TranscodingProfile,
} from "@jellyfin/sdk/lib/generated-client";
import { getSupportedAudioCodecs } from "./helpers/audio-formats"; import { getSupportedAudioCodecs } from "./helpers/audio-formats";
import { getSupportedFmp4VideoCodecs } from "./helpers/fmp4-video-formats";
import { getSupportedMP4AudioCodecs } from "./helpers/mp4-audio-formats"; import { getSupportedMP4AudioCodecs } from "./helpers/mp4-audio-formats";
import { import {
getSupportedMP4VideoCodecs, getSupportedMP4VideoCodecs,
@@ -37,6 +38,7 @@ import { getSupportedTsVideoCodecs } from "./helpers/ts-video-formats";
*/ */
export function getTranscodingProfiles( export function getTranscodingProfiles(
videoTestElement: HTMLVideoElement, videoTestElement: HTMLVideoElement,
preferHevcCopy = false,
): TranscodingProfile[] { ): TranscodingProfile[] {
const TranscodingProfiles: TranscodingProfile[] = []; const TranscodingProfiles: TranscodingProfile[] = [];
const physicalAudioChannels = isTv() ? 6 : 2; const physicalAudioChannels = isTv() ? 6 : 2;
@@ -85,6 +87,28 @@ export function getTranscodingProfiles(
const hlsInTsVideoCodecs = getSupportedTsVideoCodecs(videoTestElement); const hlsInTsVideoCodecs = getSupportedTsVideoCodecs(videoTestElement);
const hlsInTsAudioCodecs = getSupportedTsAudioCodecs(videoTestElement); const hlsInTsAudioCodecs = getSupportedTsAudioCodecs(videoTestElement);
const hlsInFmp4VideoCodecs = getSupportedFmp4VideoCodecs(videoTestElement);
// Prefer HLS fMP4 with HEVC video copy on Apple platforms. The server then
// only transcodes the audio, which works even without hardware encoding.
if (
preferHevcCopy &&
canPlayHls &&
isApple() &&
hlsInFmp4VideoCodecs.includes("hevc")
) {
TranscodingProfiles.push({
Container: "mp4",
Type: DlnaProfileType.Video,
AudioCodec: "aac",
VideoCodec: hlsInFmp4VideoCodecs.join(","),
Context: EncodingContext.Streaming,
Protocol: "hls",
MaxAudioChannels: physicalAudioChannels.toString(),
MinSegments: 2,
BreakOnNonKeyFrames: hlsBreakOnNonKeyFrames,
});
}
if ( if (
canPlayHls && canPlayHls &&
+23 -2
View File
@@ -1,9 +1,17 @@
import { load } from "@tauri-apps/plugin-store"; import { load } from "@tauri-apps/plugin-store";
import {
DEFAULT_PLAYBACK_QUALITY,
isPlaybackQualityPreset,
type PlaybackQualityPreset,
} from "../types/playbackQuality";
import type { VideoFitMode } from "../types/videoFitMode"; import type { VideoFitMode } from "../types/videoFitMode";
const PlayerStore = await load(".player.dat", { autoSave: true }); const PlayerStore = await load(".player.dat", { autoSave: true });
export const setPlayerVolume = async (type: "audio" | "video", volume: number) => { export const setPlayerVolume = async (
type: "audio" | "video",
volume: number,
) => {
await PlayerStore.set(`${type}.volume`, volume); await PlayerStore.set(`${type}.volume`, volume);
await PlayerStore.save(); await PlayerStore.save();
}; };
@@ -13,7 +21,10 @@ export const getPlayerVolume = async (type: "audio" | "video") => {
return value ?? 0.8; return value ?? 0.8;
}; };
export const setPlayerMuted = async (type: "audio" | "video", muted: boolean) => { export const setPlayerMuted = async (
type: "audio" | "video",
muted: boolean,
) => {
await PlayerStore.set(`${type}.muted`, muted); await PlayerStore.set(`${type}.muted`, muted);
await PlayerStore.save(); await PlayerStore.save();
}; };
@@ -42,3 +53,13 @@ export const getVideoFitMode = async (): Promise<VideoFitMode> => {
const value = await PlayerStore.get<VideoFitMode>("video.fitMode"); const value = await PlayerStore.get<VideoFitMode>("video.fitMode");
return value === "fill" || value === "stretch" ? value : "fit"; return value === "fill" || value === "stretch" ? value : "fit";
}; };
export const setPlaybackQuality = async (quality: PlaybackQualityPreset) => {
await PlayerStore.set("video.quality", quality);
await PlayerStore.save();
};
export const getPlaybackQuality = async (): Promise<PlaybackQualityPreset> => {
const value = await PlayerStore.get<PlaybackQualityPreset>("video.quality");
return isPlaybackQualityPreset(value) ? value : DEFAULT_PLAYBACK_QUALITY;
};
+107 -4
View File
@@ -21,14 +21,19 @@ import { secToTicks, ticksToSec } from "../date/time";
import getSubtitle from "../methods/getSubtitles"; import getSubtitle from "../methods/getSubtitles";
import { addSegmentsFromChapters } from "../methods/mediaSegments"; import { addSegmentsFromChapters } from "../methods/mediaSegments";
import { markLocalMediaSwitch } from "../methods/mediaSwitch"; import { markLocalMediaSwitch } from "../methods/mediaSwitch";
import playbackProfile from "../playback-profiles"; import {
getVideoPlaybackProfile,
setVideoPlaybackQuality,
} from "../playback-profiles";
import { import {
getPlayerMuted, getPlayerMuted,
getPlayerVolume, getPlayerVolume,
setPlaybackQuality,
setPlayerMuted, setPlayerMuted,
setPlayerVolume, setPlayerVolume,
} from "../storage/player"; } from "../storage/player";
import type audioPlaybackInfo from "../types/audioPlaybackInfo"; import type audioPlaybackInfo from "../types/audioPlaybackInfo";
import type { PlaybackQualityPreset } from "../types/playbackQuality";
import type subtitlePlaybackInfo from "../types/subtitlePlaybackInfo"; import type subtitlePlaybackInfo from "../types/subtitlePlaybackInfo";
import { import {
generateAudioStreamUrl, generateAudioStreamUrl,
@@ -702,6 +707,7 @@ export const playItem = (args: {
state.userId = args.userId; state.userId = args.userId;
state.playerState.isPlayerPlaying = true; state.playerState.isPlayerPlaying = true;
state.playerState.isPlayerReady = false; // Reset player ready state state.playerState.isPlayerReady = false; // Reset player ready state
state.playerState.isBuffering = true;
}); });
setQueue(args.queueItems, args.queueItemIndex ?? 0); setQueue(args.queueItems, args.queueItemIndex ?? 0);
@@ -884,6 +890,75 @@ export const initializePlayback = async (args: {
}); });
}; };
/**
* 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 ( export const playItemFromQueue = async (
index: "next" | "previous" | number, index: "next" | "previous" | number,
userId: string | undefined, userId: string | undefined,
@@ -949,6 +1024,10 @@ export const playItemFromQueue = async (
? prevMediaSource.subtitle.track ? prevMediaSource.subtitle.track
: (item?.MediaSources?.[0]?.DefaultSubtitleStreamIndex ?? -1); : (item?.MediaSources?.[0]?.DefaultSubtitleStreamIndex ?? -1);
const sourceVideoCodec = item.MediaSources?.[0]?.MediaStreams?.find(
(stream) => stream.Type === "Video",
)?.Codec;
// Prepare promises for parallel execution // Prepare promises for parallel execution
const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({ const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex, audioStreamIndex,
@@ -958,7 +1037,7 @@ export const playItemFromQueue = async (
userId: userId, userId: userId,
mediaSourceId: mediaSourceId, mediaSourceId: mediaSourceId,
playbackInfoDto: { playbackInfoDto: {
DeviceProfile: playbackProfile, DeviceProfile: await getVideoPlaybackProfile(sourceVideoCodec),
}, },
}); });
@@ -1059,16 +1138,22 @@ export const changeAudioTrack = async (trackIndex: number, api: Api) => {
if (!prevState.metadata.item.MediaSources?.[0].Id) { if (!prevState.metadata.item.MediaSources?.[0].Id) {
throw new Error("Media source id is undefined in changeAudioTrack"); throw new Error("Media source id is undefined in changeAudioTrack");
} }
const positionTicks =
prevState.playerState.currentTime ??
prevState.metadata.item.UserData?.PlaybackPositionTicks ??
0;
const mediaSource = ( const mediaSource = (
await getMediaInfoApi(api).getPostedPlaybackInfo({ await getMediaInfoApi(api).getPostedPlaybackInfo({
audioStreamIndex: trackIndex, audioStreamIndex: trackIndex,
subtitleStreamIndex: prevState.mediaSource.subtitle.track, subtitleStreamIndex: prevState.mediaSource.subtitle.track,
itemId: prevState.metadata.item.Id, itemId: prevState.metadata.item.Id,
startTimeTicks: prevState.metadata.item.UserData?.PlaybackPositionTicks, startTimeTicks: positionTicks,
userId: prevState.userId, userId: prevState.userId,
mediaSourceId: prevState.metadata.item.MediaSources?.[0].Id, mediaSourceId: prevState.metadata.item.MediaSources?.[0].Id,
playbackInfoDto: { playbackInfoDto: {
DeviceProfile: playbackProfile, DeviceProfile: await getVideoPlaybackProfile(
prevState.mediaSource.videoCodec,
),
}, },
}) })
).data; ).data;
@@ -1091,12 +1176,30 @@ export const changeAudioTrack = async (trackIndex: number, api: Api) => {
playbackUrl = `${api.basePath}${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) => { usePlaybackStore.setState((state) => {
state.mediaSource.audio.track = trackIndex; state.mediaSource.audio.track = trackIndex;
state.mediaSource.id = mediaSource.MediaSources?.[0].Id ?? ""; state.mediaSource.id = mediaSource.MediaSources?.[0].Id ?? "";
state.mediaSource.container = mediaSource.MediaSources?.[0].Container ?? ""; state.mediaSource.container = mediaSource.MediaSources?.[0].Container ?? "";
state.playbackStream = playbackUrl; state.playbackStream = playbackUrl;
state.playsessionId = mediaSource.PlaySessionId; 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; // const currentItemIndex = useQueue.getState().currentItemIndex;
// playItemFromQueue(currentItemIndex, prevState.userId, api); // playItemFromQueue(currentItemIndex, prevState.userId, api);
+87
View File
@@ -0,0 +1,87 @@
export type PlaybackQualityPreset =
| "auto"
| "original"
| "1080p"
| "720p"
| "480p";
export type PlaybackQualityOption = {
id: PlaybackQualityPreset;
label: string;
maxBitrate: number;
/** Resolution cap for H.264 (transcoding fallback). */
h264MaxWidth?: number;
h264MaxHeight?: number;
/** Resolution cap for HEVC. Omit to let compatible HEVC copy through. */
hevcMaxWidth?: number;
hevcMaxHeight?: number;
/** Offer HLS fMP4 with HEVC copy before the H.264/TS fallback. */
preferHevcCopy?: boolean;
};
/**
* Video quality presets used in the Jellyfin device profile.
*
* The "auto" preset prefers copying the original HEVC video into HLS fMP4 and
* transcoding only the audio. This keeps playback possible on servers without
* hardware acceleration. H.264 sources are capped at 1080p because a 4K H.264
* software transcode cannot keep up with real time on such servers.
*/
export const PLAYBACK_QUALITY_OPTIONS: PlaybackQualityOption[] = [
{
id: "auto",
label: "Авто · без перекодирования видео",
maxBitrate: 25_000_000,
h264MaxWidth: 1920,
h264MaxHeight: 1080,
hevcMaxWidth: 3840,
hevcMaxHeight: 2160,
preferHevcCopy: true,
},
{
id: "1080p",
label: "1080p · 8 Мбит/с",
maxBitrate: 8_000_000,
h264MaxWidth: 1920,
h264MaxHeight: 1080,
hevcMaxWidth: 1920,
hevcMaxHeight: 1080,
},
{
id: "720p",
label: "720p · 4 Мбит/с",
maxBitrate: 4_000_000,
h264MaxWidth: 1280,
h264MaxHeight: 720,
hevcMaxWidth: 1280,
hevcMaxHeight: 720,
},
{
id: "480p",
label: "480p · 1,5 Мбит/с",
maxBitrate: 1_500_000,
h264MaxWidth: 854,
h264MaxHeight: 480,
hevcMaxWidth: 854,
hevcMaxHeight: 480,
},
{
id: "original",
label: "Оригинал (как есть)",
maxBitrate: 120_000_000,
preferHevcCopy: true,
},
];
export const DEFAULT_PLAYBACK_QUALITY: PlaybackQualityPreset = "auto";
export const isPlaybackQualityPreset = (
value: unknown,
): value is PlaybackQualityPreset =>
PLAYBACK_QUALITY_OPTIONS.some((option) => option.id === value);
export const getPlaybackQualityOption = (
preset: PlaybackQualityPreset,
): PlaybackQualityOption =>
PLAYBACK_QUALITY_OPTIONS.find((option) => option.id === preset) ??
PLAYBACK_QUALITY_OPTIONS[0];