From c2ec314b39e80b475def54f58efc98fd35e5e822 Mon Sep 17 00:00:00 2001 From: 1xDed Date: Sat, 5 Dec 2026 02:06:12 +0300 Subject: [PATCH] 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. --- .../playback/videoPlayer/settingsMenu.tsx | 58 +++++ src/utils/methods/playback.ts | 7 +- src/utils/playback-profiles/index.ts | 207 +++++++++++++++--- .../playback-profiles/transcoding-profile.ts | 34 ++- src/utils/storage/player.ts | 25 ++- src/utils/store/playback.ts | 111 +++++++++- src/utils/types/playbackQuality.ts | 87 ++++++++ 7 files changed, 491 insertions(+), 38 deletions(-) create mode 100644 src/utils/types/playbackQuality.ts diff --git a/src/components/playback/videoPlayer/settingsMenu.tsx b/src/components/playback/videoPlayer/settingsMenu.tsx index 266d2b4..aaca668 100644 --- a/src/components/playback/videoPlayer/settingsMenu.tsx +++ b/src/components/playback/videoPlayer/settingsMenu.tsx @@ -7,6 +7,7 @@ import { Typography, } from "@mui/material"; import { toNumber } from "lodash"; +import { useSnackbar } from "notistack"; import React, { type ChangeEventHandler, useCallback, @@ -18,15 +19,23 @@ import React, { import { useShallow } from "zustand/shallow"; import { getAutoSkipSegments, + getPlaybackQuality, setAutoSkipSegments, } from "@/utils/storage/player"; import { useApiInContext } from "@/utils/store/api"; import { changeAudioTrack, + changePlaybackQuality, changeSubtitleTrack, usePlaybackStore, } from "@/utils/store/playback"; import useSyncPlayback from "@/utils/store/syncPlayback"; +import { + DEFAULT_PLAYBACK_QUALITY, + isPlaybackQualityPreset, + PLAYBACK_QUALITY_OPTIONS, + type PlaybackQualityPreset, +} from "@/utils/types/playbackQuality"; type VideoPlayerSettingsMenuProps = { settingsMenuRef: HTMLButtonElement | null; @@ -42,6 +51,7 @@ const VideoPlayerSettingsMenu = ({ }, [settingsMenuRef]); const api = useApiInContext((state) => state.api); + const { enqueueSnackbar } = useSnackbar(); const { mediaSource, @@ -92,6 +102,39 @@ const VideoPlayerSettingsMenu = ({ }); }; + const [quality, setQuality] = useState( + 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 handleSubtitleChange: ChangeEventHandler< HTMLInputElement | HTMLTextAreaElement @@ -154,6 +197,21 @@ const VideoPlayerSettingsMenu = ({ horizontal: "right", }} > + + {PLAYBACK_QUALITY_OPTIONS.map((option) => ( + + {option.label} + + ))} + stream.Type === "Video", + )?.Codec; const playbackInfoPromise = getMediaInfoApi(api).getPostedPlaybackInfo({ audioStreamIndex: Number(audioStreamIndex), subtitleStreamIndex: currentSubTrack === "nosub" ? -1 : currentSubTrack, @@ -231,7 +234,7 @@ export async function getPlaybackInfo( userId: userId, mediaSourceId: targetItem.MediaSources?.[0]?.Id, playbackInfoDto: { - DeviceProfile: playbackProfile, + DeviceProfile: await getVideoPlaybackProfile(sourceVideoCodec), }, }); diff --git a/src/utils/playback-profiles/index.ts b/src/utils/playback-profiles/index.ts index 7073744..3f91fc8 100644 --- a/src/utils/playback-profiles/index.ts +++ b/src/utils/playback-profiles/index.ts @@ -18,42 +18,199 @@ * 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 * 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, - * we must take into account the playback of really old codecs like MPEG or H263, + * pretty modern, so it would've been catched-up by MediaCapabilities. However, we + * 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, * so MediaCapabilities reports as unsupported, so we would be going from an "inferior" codec to a * "superior" codec in this situation) */ -import type { DeviceProfile } from '@jellyfin/sdk/lib/generated-client'; -import { getCodecProfiles } from './helpers/codec-profiles'; -import { getDirectPlayProfiles } from './directplay-profile'; -import { getTranscodingProfiles } from './transcoding-profile'; -import { getSubtitleProfiles } from './subtitle-profile'; -import { getResponseProfiles } from './response-profile'; +import { + type CodecProfile, + CodecType, + type DeviceProfile, + type ProfileCondition, + 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 */ -function getDeviceProfile(videoTestElement: HTMLVideoElement): DeviceProfile { - // MaxStaticBitrate seems to be for offline sync only - return { - MaxStreamingBitrate: 120_000_000, - MaxStaticBitrate: 0, - MusicStreamingTranscodingBitrate: Math.min(120_000_000, 192_000), - DirectPlayProfiles: getDirectPlayProfiles(videoTestElement), - TranscodingProfiles: getTranscodingProfiles(videoTestElement), - ContainerProfiles: [], - CodecProfiles: getCodecProfiles(videoTestElement), - SubtitleProfiles: getSubtitleProfiles(), - //@ts-expect-error - ResponseProfiles: getResponseProfiles() - }; +function getDeviceProfile( + videoTestElement: HTMLVideoElement, + option: PlaybackQualityOption, +): DeviceProfile { + const codecProfiles = getCodecProfiles(videoTestElement); + + if (option.h264MaxWidth && option.h264MaxHeight) { + addResolutionCap( + codecProfiles, + "h264", + option.h264MaxWidth, + option.h264MaxHeight, + ); + } + 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 playbackProfile = getDeviceProfile(videoTestElement); +const videoTestElement = document.createElement("video"); + +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 => { + await qualityLoaded; + return getDeviceProfile( + videoTestElement, + resolveQualityOption(currentQuality, sourceVideoCodec), + ); +}; + +const playbackProfile = getDeviceProfile( + videoTestElement, + getPlaybackQualityOption(DEFAULT_PLAYBACK_QUALITY), +); export default playbackProfile; diff --git a/src/utils/playback-profiles/transcoding-profile.ts b/src/utils/playback-profiles/transcoding-profile.ts index e99b338..d5ca6c0 100644 --- a/src/utils/playback-profiles/transcoding-profile.ts +++ b/src/utils/playback-profiles/transcoding-profile.ts @@ -2,6 +2,11 @@ * @deprecated - Check @/utils/playback-profiles/index */ +import { + DlnaProfileType, + EncodingContext, + type TranscodingProfile, +} from "@jellyfin/sdk/lib/generated-client"; import { isAndroid, isApple, @@ -10,12 +15,8 @@ import { isTizen, isTv, } from "@/utils/browser-detection"; -import { - DlnaProfileType, - EncodingContext, - type TranscodingProfile, -} from "@jellyfin/sdk/lib/generated-client"; import { getSupportedAudioCodecs } from "./helpers/audio-formats"; +import { getSupportedFmp4VideoCodecs } from "./helpers/fmp4-video-formats"; import { getSupportedMP4AudioCodecs } from "./helpers/mp4-audio-formats"; import { getSupportedMP4VideoCodecs, @@ -37,6 +38,7 @@ import { getSupportedTsVideoCodecs } from "./helpers/ts-video-formats"; */ export function getTranscodingProfiles( videoTestElement: HTMLVideoElement, + preferHevcCopy = false, ): TranscodingProfile[] { const TranscodingProfiles: TranscodingProfile[] = []; const physicalAudioChannels = isTv() ? 6 : 2; @@ -85,6 +87,28 @@ export function getTranscodingProfiles( const hlsInTsVideoCodecs = getSupportedTsVideoCodecs(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 ( canPlayHls && diff --git a/src/utils/storage/player.ts b/src/utils/storage/player.ts index 1e02de6..0b8511e 100644 --- a/src/utils/storage/player.ts +++ b/src/utils/storage/player.ts @@ -1,9 +1,17 @@ import { load } from "@tauri-apps/plugin-store"; +import { + DEFAULT_PLAYBACK_QUALITY, + isPlaybackQualityPreset, + type PlaybackQualityPreset, +} from "../types/playbackQuality"; import type { VideoFitMode } from "../types/videoFitMode"; 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.save(); }; @@ -13,7 +21,10 @@ export const getPlayerVolume = async (type: "audio" | "video") => { 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.save(); }; @@ -42,3 +53,13 @@ export const getVideoFitMode = async (): Promise => { const value = await PlayerStore.get("video.fitMode"); 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 => { + const value = await PlayerStore.get("video.quality"); + return isPlaybackQualityPreset(value) ? value : DEFAULT_PLAYBACK_QUALITY; +}; diff --git a/src/utils/store/playback.ts b/src/utils/store/playback.ts index bba44ce..e19605f 100644 --- a/src/utils/store/playback.ts +++ b/src/utils/store/playback.ts @@ -21,14 +21,19 @@ import { secToTicks, ticksToSec } from "../date/time"; import getSubtitle from "../methods/getSubtitles"; import { addSegmentsFromChapters } from "../methods/mediaSegments"; import { markLocalMediaSwitch } from "../methods/mediaSwitch"; -import playbackProfile from "../playback-profiles"; +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, @@ -702,6 +707,7 @@ export const playItem = (args: { 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); @@ -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 ( index: "next" | "previous" | number, userId: string | undefined, @@ -949,6 +1024,10 @@ export const playItemFromQueue = async ( ? 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, @@ -958,7 +1037,7 @@ export const playItemFromQueue = async ( userId: userId, mediaSourceId: mediaSourceId, 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) { 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: prevState.metadata.item.UserData?.PlaybackPositionTicks, + startTimeTicks: positionTicks, userId: prevState.userId, mediaSourceId: prevState.metadata.item.MediaSources?.[0].Id, playbackInfoDto: { - DeviceProfile: playbackProfile, + DeviceProfile: await getVideoPlaybackProfile( + prevState.mediaSource.videoCodec, + ), }, }) ).data; @@ -1091,12 +1176,30 @@ export const changeAudioTrack = async (trackIndex: number, api: Api) => { 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); diff --git a/src/utils/types/playbackQuality.ts b/src/utils/types/playbackQuality.ts new file mode 100644 index 0000000..304c937 --- /dev/null +++ b/src/utils/types/playbackQuality.ts @@ -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];