From ef003e04a5182c9c850998b579e352f0edd1a80c Mon Sep 17 00:00:00 2001 From: Prayag Prajapati Date: Wed, 24 Apr 2024 16:19:45 +0530 Subject: [PATCH] refactor: implement new playback method for playbutton (wip) --- biome.json | 3 + package.json | 1 - pnpm-lock.yaml | 7 - src/components/buttons/playButton.tsx | 123 ++++-- src/components/card/card.tsx | 1 + src/utils/browser-detection.ts | 314 +++++++++++++++ src/utils/playback-profiles/README.md | 1 + .../playback-profiles/directplay-profile.ts | 108 ++++++ .../helpers/audio-formats.ts | 44 +++ .../helpers/codec-profiles.ts | 363 ++++++++++++++++++ .../helpers/fmp4-audio-formats.ts | 51 +++ .../helpers/fmp4-video-formats.ts | 46 +++ .../playback-profiles/helpers/hls-formats.ts | 89 +++++ .../helpers/mp4-audio-formats.ts | 202 ++++++++++ .../helpers/mp4-video-formats.ts | 184 +++++++++ .../helpers/transcoding-formats.ts | 54 +++ .../helpers/ts-audio-formats.ts | 38 ++ .../helpers/ts-video-formats.ts | 20 + .../helpers/webm-audio-formats.ts | 25 ++ .../helpers/webm-video-formats.ts | 32 ++ src/utils/playback-profiles/index.ts | 58 +++ .../playback-profiles/response-profile.ts | 25 ++ .../playback-profiles/subtitle-profile.ts | 34 ++ .../playback-profiles/transcoding-profile.ts | 136 +++++++ src/utils/types/playResult.ts | 11 + tsconfig.json | 1 + vite.config.js | 5 + 27 files changed, 1926 insertions(+), 50 deletions(-) create mode 100644 src/utils/browser-detection.ts create mode 100644 src/utils/playback-profiles/README.md create mode 100644 src/utils/playback-profiles/directplay-profile.ts create mode 100644 src/utils/playback-profiles/helpers/audio-formats.ts create mode 100644 src/utils/playback-profiles/helpers/codec-profiles.ts create mode 100644 src/utils/playback-profiles/helpers/fmp4-audio-formats.ts create mode 100644 src/utils/playback-profiles/helpers/fmp4-video-formats.ts create mode 100644 src/utils/playback-profiles/helpers/hls-formats.ts create mode 100644 src/utils/playback-profiles/helpers/mp4-audio-formats.ts create mode 100644 src/utils/playback-profiles/helpers/mp4-video-formats.ts create mode 100644 src/utils/playback-profiles/helpers/transcoding-formats.ts create mode 100644 src/utils/playback-profiles/helpers/ts-audio-formats.ts create mode 100644 src/utils/playback-profiles/helpers/ts-video-formats.ts create mode 100644 src/utils/playback-profiles/helpers/webm-audio-formats.ts create mode 100644 src/utils/playback-profiles/helpers/webm-video-formats.ts create mode 100644 src/utils/playback-profiles/index.ts create mode 100644 src/utils/playback-profiles/response-profile.ts create mode 100644 src/utils/playback-profiles/subtitle-profile.ts create mode 100644 src/utils/playback-profiles/transcoding-profile.ts create mode 100644 src/utils/types/playResult.ts diff --git a/biome.json b/biome.json index 73d6a96..dd72257 100644 --- a/biome.json +++ b/biome.json @@ -15,6 +15,9 @@ }, "correctness": { "useExhaustiveDependencies": "off" + }, + "suspicious": { + "noExplicitAny": "off" } } }, diff --git a/package.json b/package.json index 0d84ee9..3d8e048 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,6 @@ "react-router-dom": "^6.22.3", "react-use-konami": "^1.1.0", "remark-gfm": "^4.0.0", - "rx-player": "^4.0.0", "shaka-player": "^4.7.11", "tauri-plugin-log-api": "github:tauri-apps/tauri-plugin-log#v1", "tauri-plugin-store-api": "github:tauri-apps/tauri-plugin-store", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4719f44..b67cf92 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -104,9 +104,6 @@ dependencies: remark-gfm: specifier: ^4.0.0 version: 4.0.0 - rx-player: - specifier: ^4.0.0 - version: 4.0.0 shaka-player: specifier: ^4.7.11 version: 4.7.11 @@ -4176,10 +4173,6 @@ packages: resolution: {integrity: sha512-seBl7J1J3/k0LuzW2T9fG6JIOpni5AbU+/87LA+zTYKgTVhsfShmS8K/yOo1eeEjGJHnAdkVAUUM+PEjN9Mpkw==} dev: false - /rx-player@4.0.0: - resolution: {integrity: sha512-Ye36kPOvsGY67DIhkuciYLXI1VCc2i+YOLB5KpnQGt+3+E1igxIqQ3zx6UJjy2yNuhXzXjqKWMFxnxdvqf4+Ng==} - dev: false - /safe-array-concat@1.1.2: resolution: {integrity: sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==} engines: {node: '>=0.4'} diff --git a/src/components/buttons/playButton.tsx b/src/components/buttons/playButton.tsx index 028019f..ae23169 100644 --- a/src/components/buttons/playButton.tsx +++ b/src/components/buttons/playButton.tsx @@ -14,6 +14,7 @@ import { type BaseItemDtoQueryResult, BaseItemKind, ItemFields, + type PlaybackInfoResponse, SortOrder, type UserItemDataDto, } from "@jellyfin/sdk/lib/generated-client"; @@ -36,8 +37,12 @@ import { usePlaybackStore, } from "../../utils/store/playback"; +import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api"; import type { SxProps } from "@mui/material"; +import type { AxiosResponse } from "axios"; +import type PlayResult from "src/utils/types/playResult"; import { getRuntimeCompact } from "../../utils/date/time"; +import playbackProfile from "../../utils/playback-profiles"; type PlayButtonProps = { item: BaseItemDto; @@ -135,9 +140,8 @@ const PlayButton = ({ mutationKey: ["playButton", itemId, userId], mutationFn: async () => { setPlaybackDataLoading(true); - let result: any; - const deviceProfile = await getDlnaApi(api).getDefaultProfile(); - console.log(deviceProfile); + let result: undefined | AxiosResponse; + let mediaSource: undefined | AxiosResponse; if (playlistItem) { result = await getPlaylistsApi(api).getPlaylistItems({ userId: userId, @@ -165,7 +169,7 @@ const PlayButton = ({ parentId: itemId, userId: userId, fields: [ItemFields.MediaSources, ItemFields.MediaStreams], - sortOrder: SortOrder.Ascending, + sortOrder: [SortOrder.Ascending], sortBy: ["IndexNumber"], }); break; @@ -176,7 +180,7 @@ const PlayButton = ({ includeItemTypes: [BaseItemKind.Audio], userId: userId, fields: [ItemFields.MediaSources, ItemFields.MediaStreams], - sortOrder: SortOrder.Ascending, + sortOrder: [SortOrder.Ascending], sortBy: ["PremiereDate", "ProductionYear", "SortName"], }); break; @@ -185,8 +189,8 @@ const PlayButton = ({ parentId: itemId, userId, fields: [ItemFields.MediaSources, ItemFields.MediaStreams], - sortOrder: SortOrder.Ascending, - sortBy: "IndexNumber", + sortOrder: [SortOrder.Ascending], + sortBy: ["IndexNumber"], }); break; default: @@ -194,15 +198,27 @@ const PlayButton = ({ ids: [itemId], userId: userId, fields: [ItemFields.MediaSources, ItemFields.MediaStreams], - sortOrder: SortOrder.Ascending, - sortBy: "IndexNumber", + sortOrder: [SortOrder.Ascending], + sortBy: ["IndexNumber"], + }); + mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({ + audioStreamIndex: currentAudioTrack, + subtitleStreamIndex: + currentSubTrack === "nosub" ? -1 : currentSubTrack, + itemId: itemId, + startTimeTicks: item.UserData.PlaybackPositionTicks, + userId: userId, + mediaSourceId: item.MediaSources[0].Id, + playbackInfoDto: { + DeviceProfile: playbackProfile, + }, }); break; } } - return result.data; + return { item: result?.data, mediaSource: mediaSource?.data }; }, - onSuccess: (result: BaseItemDtoQueryResult | null) => { + onSuccess: (result: PlayResult | null) => { if (trackIndex) { setPlaylistItemId(playlistItemId); // setCurrentTrack(trackIndex); @@ -223,22 +239,25 @@ const PlayButton = ({ setAudioDisplay(true); setQueue(result.Items, 0); } else { - // Movie / Series Playback - const queue = result.Items; + // Creates a queue containing all Episodes for a particular season(series) or collection of movies + const queue = result?.item.Items; - let itemName = result.Items[0].Name; + let itemName = item.Name; let episodeTitle = ""; - if (result.Items[0].SeriesId) { - itemName = result.Items[0].SeriesName; - episodeTitle = `S${result?.Items[0].ParentIndexNumber ?? 0}:E${ - result?.Items[0].IndexNumber ?? 0 - } ${result?.Items[0].Name}`; + if (result?.item.Items[0].SeriesId) { + itemName = result?.item.Items[0].SeriesName; + episodeTitle = `S${result?.item.Items[0].ParentIndexNumber ?? 0}:E${ + result?.item.Items[0].IndexNumber ?? 0 + } ${result?.item.Items[0].Name}`; } - let selectedSubtitleTrack: number | undefined = currentSubTrack; - const subtitles = result?.Items[0].MediaSources[0].MediaStreams?.filter( - (value) => value.Type === "Subtitle", - ); + // Select correct subtitle track, this is useful if item is played with playbutton from card since that does not provide coorect default subtitle track index. + let selectedSubtitleTrack: number | "nosub" | undefined = + currentSubTrack; + const subtitles = + result?.mediaSource.MediaSources[0].MediaStreams?.filter( + (value) => value.Type === "Subtitle", + ); let enableSubtitles = true; if (currentSubTrack === "nosub") { enableSubtitles = false; @@ -249,25 +268,45 @@ const PlayButton = ({ enableSubtitles = false; } - // playItem( - // itemName, - // episodeTitle, - // currentVideoTrack, - // currentAudioTrack, - // selectedSubtitleTrack, - // result.Items[0].Container, - // enableSubtitles, - // `${api.basePath}/Videos/${result.Items[0].Id}/stream.${result.Items[0].Container}?Static=true&mediaSourceId=${result.Items[0].Id}&deviceId=${api.deviceInfo.id}&api_key=${api.accessToken}&Tag=${result.Items[0].MediaSources[0].ETag}&videoStreamIndex=${currentVideoTrack}&audioStreamIndex=${currentAudioTrack}`, - // userId, - // result?.Items[0].UserData?.PlaybackPositionTicks, - // result.Items[0].RunTimeTicks, - // result.Items[0], - // queue, - // 0, - // subtitles, - // result?.Items[0].MediaSources[0].Id, - // ); - // navigate("/player"); + const urlOptions = { + Static: true, + tag: result?.mediaSource.MediaSources[0].Etag, + mediaSourceId: result?.mediaSource.MediaSources[0].Id, + deviceId: api?.deviceInfo.id, + api_key: api?.accessToken, + }; + + const urlParams = new URLSearchParams(urlOptions).toString(); + let playbackUrl = `${api?.basePath}/Videos/${result?.mediaSource.MediaSources[0].Id}/stream.${result?.mediaSource.MediaSources[0].Container}?${urlParams}`; + + if ( + result?.mediaSource.MediaSources[0].SupportsTranscoding && + result?.mediaSource.MediaSources[0].TranscodingUrl + ) { + playbackUrl = `${api.basePath}${result.mediaSource.MediaSources[0].TranscodingUrl}`; + } else if (result?.mediaSource.MediaSources[0].hlsStream) { + playbackUrl = result.mediaSource.MediaSources[0].hlsStream; + } + + playItem( + itemName, + episodeTitle, + currentVideoTrack, + currentAudioTrack, + selectedSubtitleTrack, + result?.mediaSource?.MediaSources[0].Container ?? "mkv", + enableSubtitles, + playbackUrl, + userId, + item.UserData?.PlaybackPositionTicks, + item.RunTimeTicks, + item, + queue, + 0, + subtitles, + result?.mediaSource.MediaSources[0].Id, + ); + navigate("/player"); } }, onSettled: () => { diff --git a/src/components/card/card.tsx b/src/components/card/card.tsx index a4c3dc8..f8117e0 100644 --- a/src/components/card/card.tsx +++ b/src/components/card/card.tsx @@ -150,6 +150,7 @@ export const Card = ({ <> 1; +} + +/** + * Guesses if the platform is a Smart TV (Tizen or WebOS). + * + * @returns Determines if platform is a Smart TV + */ +export function isTv(): boolean { + return isTizen() || isWebOS(); +} + +/** + * Guesses if the platform is a PS4 + * + * @returns Determines if the device is a PS4 + */ +export function isPs4(): boolean { + return userAgentContains('playstation 4'); +} + +/** + * Guesses if the platform is a Xbox + * + * @returns Determines if the device is a Xbox + */ +export function isXbox(): boolean { + return userAgentContains('xbox'); +} diff --git a/src/utils/playback-profiles/README.md b/src/utils/playback-profiles/README.md new file mode 100644 index 0000000..78a661e --- /dev/null +++ b/src/utils/playback-profiles/README.md @@ -0,0 +1 @@ +source (jellyfin/jellyfin-vue)[https://github.com/jellyfin/jellyfin-vue/tree/master/frontend/src/utils/playback-profiles] \ No newline at end of file diff --git a/src/utils/playback-profiles/directplay-profile.ts b/src/utils/playback-profiles/directplay-profile.ts new file mode 100644 index 0000000..04a9d59 --- /dev/null +++ b/src/utils/playback-profiles/directplay-profile.ts @@ -0,0 +1,108 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + type DirectPlayProfile, + DlnaProfileType +} from '@jellyfin/sdk/lib/generated-client'; +import { getSupportedMP4VideoCodecs } from './helpers/mp4-video-formats'; +import { getSupportedMP4AudioCodecs } from './helpers/mp4-audio-formats'; +import { hasMkvSupport } from './helpers/transcoding-formats'; +import { getSupportedWebMAudioCodecs } from './helpers/webm-audio-formats'; +import { getSupportedWebMVideoCodecs } from './helpers/webm-video-formats'; +import { getSupportedAudioCodecs } from './helpers/audio-formats'; + +/** + * Returns a valid DirectPlayProfile for the current platform. + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns An array of direct play profiles for the current platform. + */ +export function getDirectPlayProfiles( + videoTestElement: HTMLVideoElement +): DirectPlayProfile[] { + const DirectPlayProfiles: DirectPlayProfile[] = []; + + const webmVideoCodecs = getSupportedWebMVideoCodecs(videoTestElement); + const webmAudioCodecs = getSupportedWebMAudioCodecs(videoTestElement); + + const mp4VideoCodecs = getSupportedMP4VideoCodecs(videoTestElement); + const mp4AudioCodecs = getSupportedMP4AudioCodecs(videoTestElement); + + if (webmVideoCodecs.length > 0) { + DirectPlayProfiles.push({ + Container: 'webm', + Type: DlnaProfileType.Video, + VideoCodec: webmVideoCodecs.join(','), + AudioCodec: webmAudioCodecs.join(',') + }); + } + + if (mp4VideoCodecs.length > 0) { + DirectPlayProfiles.push({ + Container: 'mp4,m4v', + Type: DlnaProfileType.Video, + VideoCodec: mp4VideoCodecs.join(','), + AudioCodec: mp4AudioCodecs.join(',') + }); + } + + if (hasMkvSupport(videoTestElement) && mp4VideoCodecs.length > 0) { + DirectPlayProfiles.push({ + Container: 'mkv', + Type: DlnaProfileType.Video, + VideoCodec: mp4VideoCodecs.join(','), + AudioCodec: mp4AudioCodecs.join(',') + }); + } + + const supportedAudio = [ + 'opus', + 'mp3', + 'mp2', + 'aac', + 'flac', + 'alac', + 'webma', + 'wma', + 'wav', + 'ogg', + 'oga' + ]; + + for (const audioFormat of supportedAudio.filter(format => + getSupportedAudioCodecs(format) + )) { + DirectPlayProfiles.push({ + Container: audioFormat, + Type: DlnaProfileType.Audio + }); + + if (audioFormat === 'opus' || audioFormat === 'webma') { + DirectPlayProfiles.push({ + Container: 'webm', + Type: DlnaProfileType.Audio, + AudioCodec: audioFormat + }); + } + + // Aac also appears in the m4a and m4b container + if (audioFormat === 'aac' || audioFormat === 'alac') { + DirectPlayProfiles.push( + { + Container: 'm4a', + AudioCodec: audioFormat, + Type: DlnaProfileType.Audio + }, + { + Container: 'm4b', + AudioCodec: audioFormat, + Type: DlnaProfileType.Audio + } + ); + } + } + + return DirectPlayProfiles; +} diff --git a/src/utils/playback-profiles/helpers/audio-formats.ts b/src/utils/playback-profiles/helpers/audio-formats.ts new file mode 100644 index 0000000..720f2d7 --- /dev/null +++ b/src/utils/playback-profiles/helpers/audio-formats.ts @@ -0,0 +1,44 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { isApple, isTizen, isTv, isWebOS } from "src/utils/browser-detection"; + +/** + * Determines if audio codec is supported + */ +export function getSupportedAudioCodecs(format: string): boolean { + let typeString; + + if (format === "flac" && isTv()) { + return true; + } else if (format === "wma" && isTizen()) { + return true; + } else if (format === "asf" && isTv()) { + return true; + } else if (format === "opus") { + if (!isWebOS()) { + typeString = 'audio/ogg; codecs="opus"'; + + return !!document + .createElement("audio") + .canPlayType(typeString) + .replace(/no/, ""); + } + + return false; + } else if (format === "alac" && isApple()) { + return true; + } else if (format === "webma") { + typeString = "audio/webm"; + } else if (format === "mp2") { + typeString = "audio/mpeg"; + } else { + typeString = "audio/" + format; + } + + return !!document + .createElement("audio") + .canPlayType(typeString) + .replace(/no/, ""); +} diff --git a/src/utils/playback-profiles/helpers/codec-profiles.ts b/src/utils/playback-profiles/helpers/codec-profiles.ts new file mode 100644 index 0000000..4ce62e3 --- /dev/null +++ b/src/utils/playback-profiles/helpers/codec-profiles.ts @@ -0,0 +1,363 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + type CodecProfile, + CodecType, + type ProfileCondition, + ProfileConditionType, + ProfileConditionValue, +} from "@jellyfin/sdk/lib/generated-client"; +import { + isApple, + isChromiumBased, + isEdge, + isMobile, + isPs4, + isTizen, + isTv, + isWebOS, + isXbox, + safariVersion, +} from "src/utils/browser-detection"; + +/** + * Gets the max video bitrate + * + * @returns Returns the MaxVideoBitrate + */ +function getGlobalMaxVideoBitrate(): number | undefined { + let isTizenFhd = false; + + if ( + isTizen() && + "webapis" in window && + typeof window.webapis === "object" && + window.webapis && + "productinfo" in window.webapis && + typeof window.webapis.productinfo === "object" && + window.webapis.productinfo && + "isUdPanelSupported" in window.webapis.productinfo && + typeof window.webapis.productinfo.isUdPanelSupported === "function" + ) { + isTizenFhd = !window.webapis.productinfo.isUdPanelSupported(); + } + + /* + * TODO: These values are taken directly from Jellyfin-web. + * The source of them needs to be investigated. + */ + if (isPs4()) { + return 8_000_000; + } + + if (isXbox()) { + return 12_000_000; + } + + if (isTizen() && isTizenFhd) { + return 20_000_000; + } +} + +/** + * Creates a profile condition object for use in device playback profiles. + * + * @param Property - Value for the property + * @param Condition - Condition that the property must comply with + * @param Value - Value to check in the condition + * @param IsRequired - Whether this property is required + * @returns - Constructed ProfileCondition object + */ +function createProfileCondition( + Property: ProfileConditionValue, + Condition: ProfileConditionType, + Value: string, + IsRequired = false, +): ProfileCondition { + return { + Condition, + Property, + Value, + IsRequired, + }; +} + +/** + * Gets the AAC audio codec profile conditions + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns - Array of ACC Profile conditions + */ +export function getAacCodecProfileConditions( + videoTestElement: HTMLVideoElement, +): ProfileCondition[] { + const supportsSecondaryAudio = isTizen(); + + const conditions: ProfileCondition[] = []; + + // Handle he-aac not supported + if ( + !videoTestElement + .canPlayType('video/mp4; codecs="avc1.640029, mp4a.40.5"') + .replace(/no/, "") + ) { + // TODO: This needs to become part of the stream url in order to prevent stream copy + conditions.push( + createProfileCondition( + ProfileConditionValue.AudioProfile, + ProfileConditionType.NotEquals, + "HE-AAC", + ), + ); + } + + if (!supportsSecondaryAudio) { + conditions.push( + createProfileCondition( + ProfileConditionValue.IsSecondaryAudio, + ProfileConditionType.Equals, + "false", + ), + ); + } + + return conditions; +} + +/** + * Gets an array with all the codec profiles that this client supports + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns - Array containing the different profiles for the client + */ +export function getCodecProfiles( + videoTestElement: HTMLVideoElement, +): CodecProfile[] { + const CodecProfiles: CodecProfile[] = []; + + const aacProfileConditions = getAacCodecProfileConditions(videoTestElement); + + const supportsSecondaryAudio = isTizen(); + + if (aacProfileConditions.length > 0) { + CodecProfiles.push({ + Type: CodecType.VideoAudio, + Codec: "aac", + Conditions: aacProfileConditions, + }); + } + + if (!supportsSecondaryAudio) { + CodecProfiles.push({ + Type: CodecType.VideoAudio, + Conditions: [ + createProfileCondition( + ProfileConditionValue.IsSecondaryAudio, + ProfileConditionType.Equals, + "false", + ), + ], + }); + } + + let maxH264Level = 42; + let h264Profiles = "high|main|baseline|constrained baseline"; + + if ( + isTv() || + videoTestElement + .canPlayType('video/mp4; codecs="avc1.640833"') + .replace(/no/, "") + ) { + maxH264Level = 51; + } + + if ( + videoTestElement + .canPlayType('video/mp4; codecs="avc1.640834"') + .replace(/no/, "") + ) { + maxH264Level = 52; + } + + if ( + (isTizen() || + videoTestElement + .canPlayType('video/mp4; codecs="avc1.6e0033"') + .replace(/no/, "")) && // TODO: These tests are passing in Safari, but playback is failing + (!isApple() || !isWebOS() || !(isEdge() && !isChromiumBased())) + ) { + h264Profiles += "|high 10"; + } + + let maxHevcLevel = 120; + let hevcProfiles = "main"; + const hevcProfilesMain10 = "main|main 10"; + + // HEVC Main profile, Level 4.1 + if ( + videoTestElement + .canPlayType('video/mp4; codecs="hvc1.1.4.L123"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.1.4.L123"') + .replace(/no/, "") + ) { + maxHevcLevel = 123; + } + + // HEVC Main10 profile, Level 4.1 + if ( + videoTestElement + .canPlayType('video/mp4; codecs="hvc1.2.4.L123"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.2.4.L123"') + .replace(/no/, "") + ) { + maxHevcLevel = 123; + hevcProfiles = hevcProfilesMain10; + } + + // HEVC Main10 profile, Level 5.1 + if ( + videoTestElement + .canPlayType('video/mp4; codecs="hvc1.2.4.L153"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.2.4.L153"') + .replace(/no/, "") + ) { + maxHevcLevel = 153; + hevcProfiles = hevcProfilesMain10; + } + + // HEVC Main10 profile, Level 6.1 + if ( + videoTestElement + .canPlayType('video/mp4; codecs="hvc1.2.4.L183"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.2.4.L183"') + .replace(/no/, "") + ) { + maxHevcLevel = 183; + hevcProfiles = hevcProfilesMain10; + } + + const hevcCodecProfileConditions: ProfileCondition[] = [ + createProfileCondition( + ProfileConditionValue.IsAnamorphic, + ProfileConditionType.NotEquals, + "true", + ), + createProfileCondition( + ProfileConditionValue.VideoProfile, + ProfileConditionType.EqualsAny, + hevcProfiles, + ), + createProfileCondition( + ProfileConditionValue.VideoLevel, + ProfileConditionType.LessThanEqual, + maxHevcLevel.toString(), + ), + ]; + + const h264CodecProfileConditions: ProfileCondition[] = [ + createProfileCondition( + ProfileConditionValue.IsAnamorphic, + ProfileConditionType.NotEquals, + "true", + ), + createProfileCondition( + ProfileConditionValue.VideoProfile, + ProfileConditionType.EqualsAny, + h264Profiles, + ), + createProfileCondition( + ProfileConditionValue.VideoLevel, + ProfileConditionType.LessThanEqual, + maxH264Level.toString(), + ), + ]; + + if (!isTv()) { + h264CodecProfileConditions.push( + createProfileCondition( + ProfileConditionValue.IsInterlaced, + ProfileConditionType.NotEquals, + "true", + ), + ); + hevcCodecProfileConditions.push( + createProfileCondition( + ProfileConditionValue.IsInterlaced, + ProfileConditionType.NotEquals, + "true", + ), + ); + } + + const globalMaxVideoBitrate = (getGlobalMaxVideoBitrate() ?? "").toString(); + + if (globalMaxVideoBitrate) { + h264CodecProfileConditions.push( + createProfileCondition( + ProfileConditionValue.VideoBitrate, + ProfileConditionType.LessThanEqual, + globalMaxVideoBitrate, + true, + ), + ); + } + + if (globalMaxVideoBitrate) { + hevcCodecProfileConditions.push( + createProfileCondition( + ProfileConditionValue.VideoBitrate, + ProfileConditionType.LessThanEqual, + globalMaxVideoBitrate, + true, + ), + ); + } + + // On iOS 12.x, for TS container max h264 level is 4.2 + if (isApple() && isMobile() && Number(safariVersion()) < 13) { + const codecProfile = { + Type: CodecType.Video, + Codec: "h264", + Container: "ts", + Conditions: h264CodecProfileConditions.filter((condition) => { + return condition.Property !== "VideoLevel"; + }), + }; + + codecProfile.Conditions.push( + createProfileCondition( + ProfileConditionValue.VideoLevel, + ProfileConditionType.LessThanEqual, + "42", + ), + ); + + CodecProfiles.push(codecProfile); + } + + CodecProfiles.push( + { + Type: CodecType.Video, + Codec: "h264", + Conditions: h264CodecProfileConditions, + }, + { + Type: CodecType.Video, + Codec: "hevc", + Conditions: hevcCodecProfileConditions, + }, + ); + + return CodecProfiles; +} diff --git a/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts b/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts new file mode 100644 index 0000000..9bdcb2c --- /dev/null +++ b/src/utils/playback-profiles/helpers/fmp4-audio-formats.ts @@ -0,0 +1,51 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { isEdge } from "src/utils/browser-detection"; +import { getSupportedAudioCodecs } from "./audio-formats"; +import { + hasAacSupport, + hasAc3InHlsSupport, + hasAc3Support, + hasEac3Support, + hasMp3AudioSupport, +} from "./mp4-audio-formats"; + +/** + * Gets an array with the supported fmp4 codecs + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns List of supported FMP4 audio codecs + */ +export function getSupportedFmp4AudioCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const codecs = []; + + if (hasAacSupport(videoTestElement)) { + codecs.push("aac"); + } + + if (hasMp3AudioSupport(videoTestElement)) { + codecs.push("mp3"); + } + + if (hasAc3Support(videoTestElement) && hasAc3InHlsSupport(videoTestElement)) { + codecs.push("ac3"); + + if (hasEac3Support(videoTestElement)) { + codecs.push("eac3"); + } + } + + if (getSupportedAudioCodecs("flac") && !isEdge()) { + codecs.push("flac"); + } + + if (getSupportedAudioCodecs("alac")) { + codecs.push("alac"); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/fmp4-video-formats.ts b/src/utils/playback-profiles/helpers/fmp4-video-formats.ts new file mode 100644 index 0000000..f5d3a88 --- /dev/null +++ b/src/utils/playback-profiles/helpers/fmp4-video-formats.ts @@ -0,0 +1,46 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + isApple, + isChrome, + isEdge, + isFirefox, + isTizen, + isWebOS, +} from "src/utils/browser-detection"; +import { hasH264Support, hasHevcSupport } from "./mp4-video-formats"; + +/** + * Gets an array of supported fmp4 video codecs + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns List of supported fmp4 video codecs + */ +export function getSupportedFmp4VideoCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const codecs = []; + + if ( + (isApple() || isEdge() || isTizen() || isWebOS()) && + hasHevcSupport(videoTestElement) + ) { + codecs.push("hevc"); + } + + if ( + hasH264Support(videoTestElement) && + (isChrome() || + isFirefox() || + isApple() || + isEdge() || + isTizen() || + isWebOS()) + ) { + codecs.push("h264"); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/hls-formats.ts b/src/utils/playback-profiles/helpers/hls-formats.ts new file mode 100644 index 0000000..896ee68 --- /dev/null +++ b/src/utils/playback-profiles/helpers/hls-formats.ts @@ -0,0 +1,89 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { isTv } from "src/utils/browser-detection"; +import { getSupportedAudioCodecs } from "./audio-formats"; +import { hasAacSupport, hasEac3Support } from "./mp4-audio-formats"; +import { hasH264Support, hasH265Support } from "./mp4-video-formats"; + +/** + * Check if client supports AC3 in HLS stream + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if the browser has AC3 in HLS support + */ +function supportsAc3InHls( + videoTestElement: HTMLVideoElement, +): boolean | string { + if (isTv()) { + return true; + } + + if (videoTestElement.canPlayType) { + return ( + videoTestElement + .canPlayType('application/x-mpegurl; codecs="avc1.42E01E, ac-3"') + .replace(/no/, "") || + videoTestElement + .canPlayType( + 'application/vnd.apple.mpegURL; codecs="avc1.42E01E, ac-3"', + ) + .replace(/no/, "") + ); + } + + return false; +} + +/** + * Gets the supported HLS video codecs + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Array of video codecs supported in HLS + */ +export function getHlsVideoCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const hlsVideoCodecs = []; + + if (hasH264Support(videoTestElement)) { + hlsVideoCodecs.push("h264"); + } + + if (hasH265Support(videoTestElement) || isTv()) { + hlsVideoCodecs.push("h265", "hevc"); + } + + return hlsVideoCodecs; +} + +/** + * Gets the supported HLS audio codecs + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Array of audio codecs supported in HLS + */ +export function getHlsAudioCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const hlsVideoAudioCodecs = []; + + if (supportsAc3InHls(videoTestElement)) { + hlsVideoAudioCodecs.push("ac3"); + + if (hasEac3Support(videoTestElement)) { + hlsVideoAudioCodecs.push("eac3"); + } + } + + if (hasAacSupport(videoTestElement)) { + hlsVideoAudioCodecs.push("aac"); + } + + if (getSupportedAudioCodecs("opus")) { + hlsVideoAudioCodecs.push("opus"); + } + + return hlsVideoAudioCodecs; +} diff --git a/src/utils/playback-profiles/helpers/mp4-audio-formats.ts b/src/utils/playback-profiles/helpers/mp4-audio-formats.ts new file mode 100644 index 0000000..e1ef931 --- /dev/null +++ b/src/utils/playback-profiles/helpers/mp4-audio-formats.ts @@ -0,0 +1,202 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + isTizen, + isTizen4, + isTizen5, + isTizen55, + isTv, + isWebOS, +} from "src/utils/browser-detection"; +import { getSupportedAudioCodecs } from "./audio-formats"; +import { hasVp8Support } from "./mp4-video-formats"; + +/** + * Checks if the client can play the AC3 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if the browser has AC3 support + */ +export function hasAc3Support(videoTestElement: HTMLVideoElement): boolean { + if (isTv()) { + return true; + } + + return !!videoTestElement + .canPlayType('audio/mp4; codecs="ac-3"') + .replace(/no/, ""); +} + +/** + * Checks if the client can play AC3 in a HLS stream + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if the browser has AC3 support + */ +export function hasAc3InHlsSupport( + videoTestElement: HTMLVideoElement, +): boolean { + if (isTizen() || isWebOS()) { + return true; + } + + if (videoTestElement.canPlayType) { + return !!( + videoTestElement + .canPlayType('application/x-mpegurl; codecs="avc1.42E01E, ac-3"') + .replace(/no/, "") || + videoTestElement + .canPlayType( + 'application/vnd.apple.mpegURL; codecs="avc1.42E01E, ac-3"', + ) + .replace(/no/, "") + ); + } + + return false; +} + +/** + * Checks if the cliemt has E-AC3 codec support + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has EAC3 support + */ +export function hasEac3Support(videoTestElement: HTMLVideoElement): boolean { + if (isTv()) { + return true; + } + + return !!videoTestElement + .canPlayType('audio/mp4; codecs="ec-3"') + .replace(/no/, ""); +} + +/** + * Checks if the client has AAC codec support + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has AAC support + */ +export function hasAacSupport(videoTestElement: HTMLVideoElement): boolean { + return !!videoTestElement + .canPlayType('video/mp4; codecs="avc1.640029, mp4a.40.2"') + .replace(/no/, ""); +} + +/** + * Checks if the client has MP2 codec support + * + * @returns Determines if browser has MP2 support + */ +export function hasMp2AudioSupport(): boolean { + return isTv(); +} + +/** + * Checks if the client has MP3 audio codec support + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has Mp3 support + */ +export function hasMp3AudioSupport( + videoTestElement: HTMLVideoElement, +): boolean { + return !!( + videoTestElement + .canPlayType('video/mp4; codecs="avc1.640029, mp4a.69"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="avc1.640029, mp4a.6B"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="avc1.640029, mp3"') + .replace(/no/, "") + ); +} + +/** + * Determines DTS audio support + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browserr has DTS audio support + */ +export function hasDtsSupport( + videoTestElement: HTMLVideoElement, +): boolean | string { + // DTS audio not supported in 2018 models (Tizen 4.0) + if (isTizen4() || isTizen5() || isTizen55()) { + return false; + } + + return ( + isTv() || + videoTestElement + .canPlayType('video/mp4; codecs="dts-"') + .replace(/no/, "") || + videoTestElement.canPlayType('video/mp4; codecs="dts+"').replace(/no/, "") + ); +} + +/** + * Gets an array of supported MP4 codecs + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Array of supported MP4 audio codecs + */ +export function getSupportedMP4AudioCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const codecs = []; + + if (hasAacSupport(videoTestElement)) { + codecs.push("aac"); + } + + if (hasMp3AudioSupport(videoTestElement)) { + codecs.push("mp3"); + } + + if (hasAc3Support(videoTestElement)) { + codecs.push("ac3"); + + if (hasEac3Support(videoTestElement)) { + codecs.push("eac3"); + } + } + + if (hasMp2AudioSupport()) { + codecs.push("mp2"); + } + + if (hasDtsSupport(videoTestElement)) { + codecs.push("dca", "dts"); + } + + if (isTizen() || isWebOS()) { + codecs.push("pcm_s16le", "pcm_s24le"); + } + + if (isTizen()) { + codecs.push("aac_latm"); + } + + if (getSupportedAudioCodecs("opus")) { + codecs.push("opus"); + } + + if (getSupportedAudioCodecs("flac")) { + codecs.push("flac"); + } + + if (getSupportedAudioCodecs("alac")) { + codecs.push("alac"); + } + + if (hasVp8Support(videoTestElement) || isTizen()) { + codecs.push("vorbis"); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/mp4-video-formats.ts b/src/utils/playback-profiles/helpers/mp4-video-formats.ts new file mode 100644 index 0000000..6baf710 --- /dev/null +++ b/src/utils/playback-profiles/helpers/mp4-video-formats.ts @@ -0,0 +1,184 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + isApple, + isTizen, + isTizen55, + isTv, + isWebOS5, +} from "src/utils/browser-detection"; + +/** + * Checks if the client has support for the H264 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has H264 support + */ +export function hasH264Support(videoTestElement: HTMLVideoElement): boolean { + return !!videoTestElement + .canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"') + .replace(/no/, ""); +} + +/** + * Checks if the client has support for the H265 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has H265 support + */ +export function hasH265Support(videoTestElement: HTMLVideoElement): boolean { + if (isTv()) { + return true; + } + + return !!( + videoTestElement.canPlayType && + (videoTestElement + .canPlayType('video/mp4; codecs="hvc1.1.L120"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.1.L120"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hvc1.1.0.L120"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.1.0.L120"') + .replace(/no/, "")) + ); +} + +/** + * Checks if the client has support for the HEVC codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has HEVC Support + */ +export function hasHevcSupport(videoTestElement: HTMLVideoElement): boolean { + if (isTv()) { + return true; + } + + return !!( + !!videoTestElement.canPlayType && + (videoTestElement + .canPlayType('video/mp4; codecs="hvc1.1.L120"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.1.L120"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hvc1.1.0.L120"') + .replace(/no/, "") || + videoTestElement + .canPlayType('video/mp4; codecs="hev1.1.0.L120"') + .replace(/no/, "")) + ); +} + +/** + * Checks if the client has support for the AV1 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has AV1 support + */ +export function hasAv1Support(videoTestElement: HTMLVideoElement): boolean { + if ( + (isTizen() && isTizen55()) || + (isWebOS5() && window.outerHeight >= 2160) + ) { + return true; + } + + return !!videoTestElement + .canPlayType('video/webm; codecs="av01.0.15M.10"') + .replace(/no/, ""); +} + +/** + * Check if the client has support for the VC1 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has VC1 support + */ +function hasVc1Support(videoTestElement: HTMLVideoElement): boolean { + return !!( + isTv() || + videoTestElement.canPlayType('video/mp4; codecs="vc-1"').replace(/no/, "") + ); +} + +/** + * Checks if the client has support for the VP8 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has VP8 support + */ +export function hasVp8Support(videoTestElement: HTMLVideoElement): boolean { + return !!videoTestElement + .canPlayType('video/webm; codecs="vp8"') + .replace(/no/, ""); +} + +/** + * Checks if the client has support for the VP9 codec + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if browser has VP9 support + */ +export function hasVp9Support(videoTestElement: HTMLVideoElement): boolean { + return !!videoTestElement + .canPlayType('video/webm; codecs="vp9"') + .replace(/no/, ""); +} + +/** + * Queries the platform for the codecs suppers in an MP4 container. + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Array of codec identifiers. + */ +export function getSupportedMP4VideoCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const codecs = []; + + if (hasH264Support(videoTestElement)) { + codecs.push("h264"); + } + + if ( + hasHevcSupport(videoTestElement) && // Safari is lying on HDR and 60fps videos, use fMP4 instead + !isApple() + ) { + codecs.push("hevc"); + } + + if (isTv()) { + codecs.push("mpeg2video"); + } + + if (hasVc1Support(videoTestElement)) { + codecs.push("vc1"); + } + + if (isTizen()) { + codecs.push("msmpeg4v2"); + } + + if (hasVp8Support(videoTestElement)) { + codecs.push("vp8"); + } + + if (hasVp9Support(videoTestElement)) { + codecs.push("vp9"); + } + + if (hasAv1Support(videoTestElement)) { + codecs.push("av1"); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/transcoding-formats.ts b/src/utils/playback-profiles/helpers/transcoding-formats.ts new file mode 100644 index 0000000..93b6cf7 --- /dev/null +++ b/src/utils/playback-profiles/helpers/transcoding-formats.ts @@ -0,0 +1,54 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + isEdge, + isTizen, + isTv, + supportsMediaSource, +} from "src/utils/browser-detection"; + +/** + * Checks if the client can play native HLS + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns Determines if the browser can play native Hls + */ +export function canPlayNativeHls(videoTestElement: HTMLVideoElement): boolean { + if (isTizen()) { + return true; + } + + return !!( + videoTestElement.canPlayType("application/x-mpegURL").replace(/no/, "") || + videoTestElement + .canPlayType("application/vnd.apple.mpegURL") + .replace(/no/, "") + ); +} + +/** + * Determines if the browser can play Hls with Media Source Extensions + */ +export function canPlayHlsWithMSE(): boolean { + return supportsMediaSource(); +} + +/** + * Determines if the browser can play Mkvs + */ +export function hasMkvSupport(videoTestElement: HTMLVideoElement): boolean { + if (isTv()) { + return true; + } + + if ( + videoTestElement.canPlayType("video/x-matroska").replace(/no/, "") || + videoTestElement.canPlayType("video/mkv").replace(/no/, "") + ) { + return true; + } + + return !!isEdge(); +} diff --git a/src/utils/playback-profiles/helpers/ts-audio-formats.ts b/src/utils/playback-profiles/helpers/ts-audio-formats.ts new file mode 100644 index 0000000..db4d001 --- /dev/null +++ b/src/utils/playback-profiles/helpers/ts-audio-formats.ts @@ -0,0 +1,38 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + hasAacSupport, + hasAc3InHlsSupport, + hasAc3Support, + hasEac3Support, + hasMp3AudioSupport +} from './mp4-audio-formats'; + +/** + * List of supported Ts audio codecs + */ +export function getSupportedTsAudioCodecs( + videoTestElement: HTMLVideoElement +): string[] { + const codecs = []; + + if (hasAacSupport(videoTestElement)) { + codecs.push('aac'); + } + + if (hasMp3AudioSupport(videoTestElement)) { + codecs.push('mp3'); + } + + if (hasAc3Support(videoTestElement) && hasAc3InHlsSupport(videoTestElement)) { + codecs.push('ac3'); + + if (hasEac3Support(videoTestElement)) { + codecs.push('eac3'); + } + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/ts-video-formats.ts b/src/utils/playback-profiles/helpers/ts-video-formats.ts new file mode 100644 index 0000000..08d69be --- /dev/null +++ b/src/utils/playback-profiles/helpers/ts-video-formats.ts @@ -0,0 +1,20 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { hasH264Support } from './mp4-video-formats'; + +/** + * List of supported ts video codecs + */ +export function getSupportedTsVideoCodecs( + videoTestElement: HTMLVideoElement +): string[] { + const codecs = []; + + if (hasH264Support(videoTestElement)) { + codecs.push('h264'); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/webm-audio-formats.ts b/src/utils/playback-profiles/helpers/webm-audio-formats.ts new file mode 100644 index 0000000..57f5f91 --- /dev/null +++ b/src/utils/playback-profiles/helpers/webm-audio-formats.ts @@ -0,0 +1,25 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { isWebOS } from "src/utils/browser-detection"; + +/** + * Get an array of supported codecs + */ +export function getSupportedWebMAudioCodecs( + videoTestElement: HTMLVideoElement, +): string[] { + const codecs = []; + + codecs.push("vorbis"); + + if ( + !isWebOS() && + videoTestElement.canPlayType('audio/ogg; codecs="opus"').replace(/no/, "") + ) { + codecs.push("opus"); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/helpers/webm-video-formats.ts b/src/utils/playback-profiles/helpers/webm-video-formats.ts new file mode 100644 index 0000000..a791c25 --- /dev/null +++ b/src/utils/playback-profiles/helpers/webm-video-formats.ts @@ -0,0 +1,32 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + hasAv1Support, + hasVp8Support, + hasVp9Support +} from './mp4-video-formats'; + +/** + * Get an array of supported codecs WebM video codecs + */ +export function getSupportedWebMVideoCodecs( + videoTestElement: HTMLVideoElement +): string[] { + const codecs = []; + + if (hasVp8Support(videoTestElement)) { + codecs.push('vp8'); + } + + if (hasVp9Support(videoTestElement)) { + codecs.push('vp9'); + } + + if (hasAv1Support(videoTestElement)) { + codecs.push('av1'); + } + + return codecs; +} diff --git a/src/utils/playback-profiles/index.ts b/src/utils/playback-profiles/index.ts new file mode 100644 index 0000000..e881472 --- /dev/null +++ b/src/utils/playback-profiles/index.ts @@ -0,0 +1,58 @@ +/** + * @deprecated + * Since we're targeting modern environments/devices only, it makes sense to switch + * to the native MediaCapabilities API, widely supported on modern devices, but not in older. + * + * Given a media file, we should test with MC the compatibility of video, audio and subtitle streams + * independently: + * If success: Don't request transcoding and direct play that specific stream. + * If failure: Request transcoding of the failing streams to a previously hardcoded + * bitrate/codec combination + * + * For the hardcoded bitrate/codecs combination we can use what we know that are universally + * compatible, even without testing for explicit compatibility (we can do simple checks, + * but the more we do, the complex/less portable our solution can get). + * Examples: H264, AAC and VTT/SASS (thanks to JASSUB). + * + * Other codec combinations can be hardcoded, even if they're not direct-playable in + * 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, + * 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'; + +/** + * Creates a device profile containing supported codecs for the active Cast device. + * + * @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(), + ResponseProfiles: getResponseProfiles() + }; +} + +const videoTestElement = document.createElement('video'); +const playbackProfile = getDeviceProfile(videoTestElement); + +export default playbackProfile; diff --git a/src/utils/playback-profiles/response-profile.ts b/src/utils/playback-profiles/response-profile.ts new file mode 100644 index 0000000..c99347b --- /dev/null +++ b/src/utils/playback-profiles/response-profile.ts @@ -0,0 +1,25 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + DlnaProfileType, + type ResponseProfile +} from '@jellyfin/sdk/lib/generated-client'; + +/** + * Returns a valid ResponseProfile for the current platform. + * + * @returns An array of subtitle profiles for the current platform. + */ +export function getResponseProfiles(): ResponseProfile[] { + const ResponseProfiles = []; + + ResponseProfiles.push({ + Type: DlnaProfileType.Video, + Container: 'm4v', + MimeType: 'video/mp4' + }); + + return ResponseProfiles; +} diff --git a/src/utils/playback-profiles/subtitle-profile.ts b/src/utils/playback-profiles/subtitle-profile.ts new file mode 100644 index 0000000..6875e92 --- /dev/null +++ b/src/utils/playback-profiles/subtitle-profile.ts @@ -0,0 +1,34 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + SubtitleDeliveryMethod, + type SubtitleProfile +} from '@jellyfin/sdk/lib/generated-client'; + +/** + * Returns a valid SubtitleProfile for the current platform. + * + * @returns An array of subtitle profiles for the current platform. + */ +export function getSubtitleProfiles(): SubtitleProfile[] { + const SubtitleProfiles: SubtitleProfile[] = []; + + SubtitleProfiles.push( + { + Format: 'vtt', + Method: SubtitleDeliveryMethod.External + }, + { + Format: 'ass', + Method: SubtitleDeliveryMethod.External + }, + { + Format: 'ssa', + Method: SubtitleDeliveryMethod.External + } + ); + + return SubtitleProfiles; +} diff --git a/src/utils/playback-profiles/transcoding-profile.ts b/src/utils/playback-profiles/transcoding-profile.ts new file mode 100644 index 0000000..1dcbe14 --- /dev/null +++ b/src/utils/playback-profiles/transcoding-profile.ts @@ -0,0 +1,136 @@ +/** + * @deprecated - Check @/utils/playback-profiles/index + */ + +import { + DlnaProfileType, + EncodingContext, + type TranscodingProfile, +} from "@jellyfin/sdk/lib/generated-client"; +import { + isAndroid, + isApple, + isChromiumBased, + isEdge, + isTizen, + isTv, +} from "src/utils/browser-detection"; +import { getSupportedAudioCodecs } from "./helpers/audio-formats"; +import { getSupportedMP4AudioCodecs } from "./helpers/mp4-audio-formats"; +import { + getSupportedMP4VideoCodecs, + hasVp8Support, +} from "./helpers/mp4-video-formats"; +import { + canPlayHlsWithMSE, + canPlayNativeHls, + hasMkvSupport, +} from "./helpers/transcoding-formats"; +import { getSupportedTsAudioCodecs } from "./helpers/ts-audio-formats"; +import { getSupportedTsVideoCodecs } from "./helpers/ts-video-formats"; + +/** + * Returns a valid TranscodingProfile for the current platform. + * + * @param videoTestElement - A HTML video element for testing codecs + * @returns An array of transcoding profiles for the current platform. + */ +export function getTranscodingProfiles( + videoTestElement: HTMLVideoElement, +): TranscodingProfile[] { + const TranscodingProfiles: TranscodingProfile[] = []; + const physicalAudioChannels = isTv() ? 6 : 2; + + const hlsBreakOnNonKeyFrames = !!( + isApple() || + (isEdge() && !isChromiumBased()) || + !canPlayNativeHls(videoTestElement) + ); + + const mp4AudioCodecs = getSupportedMP4AudioCodecs(videoTestElement); + const mp4VideoCodecs = getSupportedMP4VideoCodecs(videoTestElement); + const canPlayHls = canPlayNativeHls(videoTestElement) || canPlayHlsWithMSE(); + + if (canPlayHls) { + TranscodingProfiles.push({ + // Hlsjs, edge, and android all seem to require ts container + Container: + !canPlayNativeHls(videoTestElement) || + (isEdge() && !isChromiumBased()) || + isAndroid() + ? "ts" + : "aac", + Type: DlnaProfileType.Audio, + AudioCodec: "aac", + Context: EncodingContext.Streaming, + Protocol: "hls", + MaxAudioChannels: physicalAudioChannels.toString(), + MinSegments: isApple() ? 2 : 1, + BreakOnNonKeyFrames: hlsBreakOnNonKeyFrames, + }); + } + + for (const audioFormat of ["aac", "mp3", "opus", "wav"].filter((format) => + getSupportedAudioCodecs(format), + )) { + TranscodingProfiles.push({ + Container: audioFormat, + Type: DlnaProfileType.Audio, + AudioCodec: audioFormat, + Context: EncodingContext.Streaming, + Protocol: "http", + MaxAudioChannels: physicalAudioChannels.toString(), + }); + } + + const hlsInTsVideoCodecs = getSupportedTsVideoCodecs(videoTestElement); + const hlsInTsAudioCodecs = getSupportedTsAudioCodecs(videoTestElement); + + if ( + canPlayHls && + hlsInTsVideoCodecs.length > 0 && + hlsInTsAudioCodecs.length > 0 + ) { + TranscodingProfiles.push({ + Container: "ts", + Type: DlnaProfileType.Video, + AudioCodec: hlsInTsAudioCodecs.join(","), + VideoCodec: hlsInTsVideoCodecs.join(","), + Context: EncodingContext.Streaming, + Protocol: "hls", + MaxAudioChannels: physicalAudioChannels.toString(), + MinSegments: isApple() ? 2 : 1, + BreakOnNonKeyFrames: hlsBreakOnNonKeyFrames, + }); + } + + if (hasMkvSupport(videoTestElement) && !isTizen()) { + TranscodingProfiles.push({ + Container: "mkv", + Type: DlnaProfileType.Video, + AudioCodec: mp4AudioCodecs.join(","), + VideoCodec: mp4VideoCodecs.join(","), + Context: EncodingContext.Streaming, + MaxAudioChannels: physicalAudioChannels.toString(), + CopyTimestamps: true, + }); + } + + if (hasVp8Support(videoTestElement)) { + TranscodingProfiles.push({ + Container: "webm", + Type: DlnaProfileType.Video, + AudioCodec: "vorbis", + VideoCodec: "vpx", + Context: EncodingContext.Streaming, + Protocol: "http", + /* + * If audio transcoding is needed, limit channels to number of physical audio channels + * Trying to transcode to 5 channels when there are only 2 speakers generally does not sound good + */ + MaxAudioChannels: physicalAudioChannels.toString(), + }); + } + + return TranscodingProfiles; +} diff --git a/src/utils/types/playResult.ts b/src/utils/types/playResult.ts new file mode 100644 index 0000000..eb0423c --- /dev/null +++ b/src/utils/types/playResult.ts @@ -0,0 +1,11 @@ +import type { + BaseItemDtoQueryResult, + PlaybackInfoResponse, +} from "@jellyfin/sdk/lib/generated-client"; + +interface PlayResult { + item: BaseItemDtoQueryResult; + mediaSource: PlaybackInfoResponse; +} + +export default PlayResult; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index c95b04b..cb54163 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,6 +6,7 @@ "dom.iterable", "esnext" ], + "baseUrl": ".", "checkJs": true, "allowJs": true, // Allow JavaScript files to be compiled "skipLibCheck": true, // Skip type checking of all declaration files diff --git a/vite.config.js b/vite.config.js index 6d71449..ff5c934 100644 --- a/vite.config.js +++ b/vite.config.js @@ -16,6 +16,11 @@ export default defineConfig({ }, }, }, + resolve: { + alias: { + src: "/src", + }, + }, // prevent vite from obscuring rust errors clearScreen: false, // Tauri expects a fixed port, fail if that port is not available