Compare commits

..

2 Commits

Author SHA1 Message Date
Lance Chant
d6980cfc8e fix: subtitle ordering
Fixed an issue where external and subrip subtitles were not ordered
correctly

Signed-off-by: Lance Chant <13349722+lancechant@users.noreply.github.com>
2026-06-23 12:00:11 +02:00
Niyazaki
b256e99fc8 fix(search): set typed text color on Android search bar (#1756)
Some checks failed
🏗️ Build Apps / 🤖 Build Android APK (Phone) (push) Has been cancelled
🏗️ Build Apps / 🍎 Build iOS IPA (Phone) (push) Has been cancelled
🏗️ Build Apps / 🤖 Build Android APK (TV) (push) Has been cancelled
🏗️ Build Apps / 🍎 Build iOS IPA (Phone - Unsigned) (push) Has been cancelled
🏗️ Build Apps / 🍎 Build tvOS IPA (push) Has been cancelled
🏗️ Build Apps / 🍎 Build tvOS IPA (Unsigned) (push) Has been cancelled
🔒 Lockfile Consistency Check / 🔍 Check bun.lock and package.json consistency (push) Has been cancelled
🏷️🔀Merge Conflict Labeler / 🏷️ Labeling Merge Conflicts (push) Has been cancelled
🚦 Security & Quality Gate / 📝 Validate PR Title (push) Has been cancelled
🛡️ CodeQL Analysis / 🔎 Analyze with CodeQL (actions) (push) Has been cancelled
🛡️ CodeQL Analysis / 🔎 Analyze with CodeQL (javascript-typescript) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Vulnerable Dependencies (push) Has been cancelled
🚦 Security & Quality Gate / 🚑 Expo Doctor Check (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (check) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (format) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (i18n:check) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (lint) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (typecheck) (push) Has been cancelled
🛡️ Trivy Security Scan / 🔎 Filesystem scan (push) Has been cancelled
2026-06-23 09:11:38 +02:00
18 changed files with 442 additions and 791 deletions

View File

@@ -36,7 +36,6 @@ import {
InactivityTimeout, InactivityTimeout,
type MpvCacheMode, type MpvCacheMode,
type MpvVoDriver, type MpvVoDriver,
type SegmentSkipMode,
TVTypographyScale, TVTypographyScale,
useSettings, useSettings,
} from "@/utils/atoms/settings"; } from "@/utils/atoms/settings";
@@ -48,22 +47,6 @@ import {
} from "@/utils/secureCredentials"; } from "@/utils/secureCredentials";
import { clearTopShelfCacheSafely } from "@/utils/topshelf/cache"; import { clearTopShelfCacheSafely } from "@/utils/topshelf/cache";
const SEGMENT_SKIP_ROWS: {
key:
| "skipIntro"
| "skipOutro"
| "skipRecap"
| "skipCommercial"
| "skipPreview";
labelKey: string;
}[] = [
{ key: "skipIntro", labelKey: "skip_intro" },
{ key: "skipOutro", labelKey: "skip_outro" },
{ key: "skipRecap", labelKey: "skip_recap" },
{ key: "skipCommercial", labelKey: "skip_commercial" },
{ key: "skipPreview", labelKey: "skip_preview" },
];
export default function SettingsTV() { export default function SettingsTV() {
const { t } = useTranslation(); const { t } = useTranslation();
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
@@ -552,30 +535,6 @@ export default function SettingsTV() {
); );
}, [inactivityTimeoutOptions, t]); }, [inactivityTimeoutOptions, t]);
// Segment skip: same auto/ask/none choice for every segment type.
const segmentSkipModeLabel = (mode: SegmentSkipMode) =>
t(`home.settings.other.segment_skip_${mode}`);
const buildSegmentSkipOptions = (
current: SegmentSkipMode,
): TVOptionItem<SegmentSkipMode>[] => [
{
label: t("home.settings.other.segment_skip_auto"),
value: "auto",
selected: current === "auto",
},
{
label: t("home.settings.other.segment_skip_ask"),
value: "ask",
selected: current === "ask",
},
{
label: t("home.settings.other.segment_skip_none"),
value: "none",
selected: current === "none",
},
];
return ( return (
<View style={{ flex: 1, backgroundColor: "#000000" }}> <View style={{ flex: 1, backgroundColor: "#000000" }}>
<View style={{ flex: 1 }}> <View style={{ flex: 1 }}>
@@ -860,30 +819,6 @@ export default function SettingsTV() {
formatValue={(v) => `${v} MB`} formatValue={(v) => `${v} MB`}
/> />
{/* Segment Skip Section */}
<TVSectionHeader
title={t("home.settings.other.segment_skip_settings")}
/>
{SEGMENT_SKIP_ROWS.map((row, index) => {
const current = (settings[row.key] ?? "ask") as SegmentSkipMode;
const rowLabel = t(`home.settings.other.${row.labelKey}`);
return (
<TVSettingsOptionButton
key={row.key}
label={rowLabel}
value={segmentSkipModeLabel(current)}
isFirst={index === 0}
onPress={() =>
showOptions({
title: rowLabel,
options: buildSegmentSkipOptions(current),
onSelect: (value) => updateSettings({ [row.key]: value }),
})
}
/>
);
})}
{/* Appearance Section */} {/* Appearance Section */}
<TVSectionHeader title={t("home.settings.appearance.title")} /> <TVSectionHeader title={t("home.settings.appearance.title")} />
<TVSettingsOptionButton <TVSettingsOptionButton

View File

@@ -1,101 +0,0 @@
import { Ionicons } from "@expo/vector-icons";
import { useNavigation } from "expo-router";
import { TFunction } from "i18next";
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { Text } from "@/components/common/Text";
import { ListGroup } from "@/components/list/ListGroup";
import { ListItem } from "@/components/list/ListItem";
import { PlatformDropdown } from "@/components/PlatformDropdown";
import { SegmentSkipMode, useSettings } from "@/utils/atoms/settings";
type SkipSettingKey =
| "skipIntro"
| "skipOutro"
| "skipRecap"
| "skipCommercial"
| "skipPreview";
const SEGMENTS: ReadonlyArray<{ key: SkipSettingKey; labelKey: string }> = [
{ key: "skipIntro", labelKey: "skip_intro" },
{ key: "skipOutro", labelKey: "skip_outro" },
{ key: "skipRecap", labelKey: "skip_recap" },
{ key: "skipCommercial", labelKey: "skip_commercial" },
{ key: "skipPreview", labelKey: "skip_preview" },
];
const SEGMENT_SKIP_OPTIONS = (
t: TFunction<"translation", undefined>,
): Array<{ label: string; value: SegmentSkipMode }> => [
{ label: t("home.settings.other.segment_skip_auto"), value: "auto" },
{ label: t("home.settings.other.segment_skip_ask"), value: "ask" },
{ label: t("home.settings.other.segment_skip_none"), value: "none" },
];
export default function SegmentSkipPage() {
const { settings, updateSettings, pluginSettings } = useSettings();
const { t } = useTranslation();
const navigation = useNavigation();
useEffect(() => {
navigation.setOptions({
title: t("home.settings.other.segment_skip_settings"),
});
}, [navigation, t]);
const options = useMemo(() => SEGMENT_SKIP_OPTIONS(t), [t]);
if (!settings) return null;
return (
<View className='px-4'>
<ListGroup>
{SEGMENTS.map(({ key, labelKey }) => {
const current = settings[key];
const locked = pluginSettings?.[key]?.locked ?? false;
const groups = [
{
options: options.map((o) => ({
type: "radio" as const,
label: o.label,
value: o.value,
selected: o.value === current,
disabled: locked,
onPress: () => {
if (locked) return;
updateSettings({ [key]: o.value });
},
})),
},
];
return (
<ListItem
key={key}
title={t(`home.settings.other.${labelKey}`)}
subtitle={t(`home.settings.other.${labelKey}_description`)}
disabled={locked}
>
<PlatformDropdown
groups={groups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{t(`home.settings.other.segment_skip_${current}`)}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t(`home.settings.other.${labelKey}`)}
/>
</ListItem>
);
})}
</ListGroup>
</View>
);
}

View File

@@ -305,6 +305,8 @@ export default function SearchPage() {
}, },
hideWhenScrolling: false, hideWhenScrolling: false,
autoFocus: false, autoFocus: false,
// Android: color of the user-typed text (was dark and unreadable on the dark header)
textColor: "#fff",
// Android: placeholder and icon color // Android: placeholder and icon color
hintTextColor: "#fff", hintTextColor: "#fff",
headerIconColor: "#fff", headerIconColor: "#fff",

View File

@@ -8,7 +8,6 @@ import { BITRATES } from "@/components/BitrateSelector";
import { PlatformDropdown } from "@/components/PlatformDropdown"; import { PlatformDropdown } from "@/components/PlatformDropdown";
import { PLAYBACK_SPEEDS } from "@/components/PlaybackSpeedSelector"; import { PLAYBACK_SPEEDS } from "@/components/PlaybackSpeedSelector";
import DisabledSetting from "@/components/settings/DisabledSetting"; import DisabledSetting from "@/components/settings/DisabledSetting";
import useRouter from "@/hooks/useAppRouter";
import * as ScreenOrientation from "@/packages/expo-screen-orientation"; import * as ScreenOrientation from "@/packages/expo-screen-orientation";
import { ScreenOrientationEnum, useSettings } from "@/utils/atoms/settings"; import { ScreenOrientationEnum, useSettings } from "@/utils/atoms/settings";
import { Text } from "../common/Text"; import { Text } from "../common/Text";
@@ -16,7 +15,6 @@ import { ListGroup } from "../list/ListGroup";
import { ListItem } from "../list/ListItem"; import { ListItem } from "../list/ListItem";
export const PlaybackControlsSettings: React.FC = () => { export const PlaybackControlsSettings: React.FC = () => {
const router = useRouter();
const { settings, updateSettings, pluginSettings } = useSettings(); const { settings, updateSettings, pluginSettings } = useSettings();
const { t } = useTranslation(); const { t } = useTranslation();
@@ -253,15 +251,6 @@ export const PlaybackControlsSettings: React.FC = () => {
title={t("home.settings.other.max_auto_play_episode_count")} title={t("home.settings.other.max_auto_play_episode_count")}
/> />
</ListItem> </ListItem>
{/* Media Segment Skip Settings */}
<ListItem
title={t("home.settings.other.segment_skip_settings")}
subtitle={t("home.settings.other.segment_skip_settings_description")}
onPress={() => router.push("/settings/segment-skip/page")}
>
<Ionicons name='chevron-forward' size={20} color='#8E8D91' />
</ListItem>
</ListGroup> </ListGroup>
</DisabledSetting> </DisabledSetting>
); );

View File

@@ -61,39 +61,17 @@ export const TVOptionCard = React.forwardRef<View, TVOptionCardProps>(
}, },
]} ]}
> >
{/* Selected + unfocused: label and checkmark form a centered group. <Text
The left padding offsets the checkmark's width so the label stays
optically centered. Without a checkmark, no offset → label centered. */}
<View
style={{ style={{
flexDirection: "row", fontSize: typography.callout,
alignItems: "center", color: focused ? "#000" : "#fff",
justifyContent: "center", fontWeight: focused || selected ? "600" : "400",
// Offset checkmark width only when it's shown, else label sits right. textAlign: "center",
paddingLeft: selected && !focused ? scaleSize(10) : 0,
}} }}
numberOfLines={4}
> >
<Text {label}
style={{ </Text>
fontSize: typography.callout,
color: focused ? "#000" : "#fff",
fontWeight: focused || selected ? "600" : "400",
textAlign: "center",
flexShrink: 1,
}}
numberOfLines={4}
>
{label}
</Text>
{selected && !focused && (
<Ionicons
name='checkmark'
size={scaleSize(26)}
color='rgba(255,255,255,0.8)'
style={{ marginLeft: scaleSize(8), flexShrink: 0 }}
/>
)}
</View>
{sublabel && ( {sublabel && (
<Text <Text
style={{ style={{
@@ -107,6 +85,21 @@ export const TVOptionCard = React.forwardRef<View, TVOptionCardProps>(
{sublabel} {sublabel}
</Text> </Text>
)} )}
{selected && !focused && (
<View
style={{
position: "absolute",
top: 8,
right: 8,
}}
>
<Ionicons
name='checkmark'
size={16}
color='rgba(255,255,255,0.8)'
/>
</View>
)}
</Animated.View> </Animated.View>
</Pressable> </Pressable>
); );

View File

@@ -19,27 +19,10 @@ import { Text } from "@/components/common/Text";
import { scaleSize } from "@/utils/scaleSize"; import { scaleSize } from "@/utils/scaleSize";
import { useTVFocusAnimation } from "./hooks/useTVFocusAnimation"; import { useTVFocusAnimation } from "./hooks/useTVFocusAnimation";
export type TVSkipSegmentType =
| "intro"
| "credits"
| "outro"
| "recap"
| "commercial"
| "preview";
const SEGMENT_LABEL_KEY: Record<TVSkipSegmentType, string> = {
intro: "player.skip_intro",
credits: "player.skip_credits",
outro: "player.skip_outro",
recap: "player.skip_recap",
commercial: "player.skip_commercial",
preview: "player.skip_preview",
};
export interface TVSkipSegmentCardProps { export interface TVSkipSegmentCardProps {
show: boolean; show: boolean;
onPress: () => void; onPress: () => void;
type: TVSkipSegmentType; type: "intro" | "credits";
/** Whether controls are visible - affects card position */ /** Whether controls are visible - affects card position */
controlsVisible?: boolean; controlsVisible?: boolean;
/** Callback ref setter for focus guide destination pattern */ /** Callback ref setter for focus guide destination pattern */
@@ -89,7 +72,8 @@ export const TVSkipSegmentCard: FC<TVSkipSegmentCardProps> = ({
bottom: bottomPosition.value, bottom: bottomPosition.value,
})); }));
const labelText = t(SEGMENT_LABEL_KEY[type]); const labelText =
type === "intro" ? t("player.skip_intro") : t("player.skip_credits");
if (!show) return null; if (!show) return null;

View File

@@ -34,13 +34,11 @@ interface BottomControlsProps {
showRemoteBubble: boolean; showRemoteBubble: boolean;
currentTime: number; currentTime: number;
remainingTime: number; remainingTime: number;
showSkipSegmentButton: boolean; showSkipButton: boolean;
skipSegmentButtonText: string; showSkipCreditButton: boolean;
showSkipOutroButton: boolean;
skipOutroButtonText: string;
hasContentAfterCredits: boolean; hasContentAfterCredits: boolean;
onSkipSegment: () => void; skipIntro: () => void;
onSkipOutro: () => void; skipCredit: () => void;
nextItem?: BaseItemDto | null; nextItem?: BaseItemDto | null;
handleNextEpisodeAutoPlay: () => void; handleNextEpisodeAutoPlay: () => void;
handleNextEpisodeManual: () => void; handleNextEpisodeManual: () => void;
@@ -88,13 +86,11 @@ export const BottomControls: FC<BottomControlsProps> = ({
showRemoteBubble, showRemoteBubble,
currentTime, currentTime,
remainingTime, remainingTime,
showSkipSegmentButton, showSkipButton,
skipSegmentButtonText, showSkipCreditButton,
showSkipOutroButton,
skipOutroButtonText,
hasContentAfterCredits, hasContentAfterCredits,
onSkipSegment, skipIntro,
onSkipOutro, skipCredit,
nextItem, nextItem,
handleNextEpisodeAutoPlay, handleNextEpisodeAutoPlay,
handleNextEpisodeManual, handleNextEpisodeManual,
@@ -185,18 +181,19 @@ export const BottomControls: FC<BottomControlsProps> = ({
</View> </View>
<View className='flex flex-row items-center space-x-2 shrink-0'> <View className='flex flex-row items-center space-x-2 shrink-0'>
<SkipButton <SkipButton
showButton={showSkipSegmentButton} showButton={showSkipButton}
onPress={onSkipSegment} onPress={skipIntro}
buttonText={skipSegmentButtonText} buttonText='Skip Intro'
/> />
{/* Outro button defers to "Next Episode" when credits run to the {/* Smart Skip Credits behavior:
video end and a next episode exists. */} - Show "Skip Credits" if there's content after credits OR no next episode
- Show "Next Episode" if credits extend to video end AND next episode exists */}
<SkipButton <SkipButton
showButton={ showButton={
showSkipOutroButton && (hasContentAfterCredits || !nextItem) showSkipCreditButton && (hasContentAfterCredits || !nextItem)
} }
onPress={onSkipOutro} onPress={skipCredit}
buttonText={skipOutroButtonText} buttonText='Skip Credits'
/> />
{settings.autoPlayNextEpisode !== false && {settings.autoPlayNextEpisode !== false &&
(settings.maxAutoPlayEpisodeCount.value === -1 || (settings.maxAutoPlayEpisodeCount.value === -1 ||
@@ -207,7 +204,7 @@ export const BottomControls: FC<BottomControlsProps> = ({
!nextItem !nextItem
? false ? false
: // Show during credits if no content after, OR near end of video : // Show during credits if no content after, OR near end of video
(showSkipOutroButton && !hasContentAfterCredits) || (showSkipCreditButton && !hasContentAfterCredits) ||
remainingTime < 10000 remainingTime < 10000
} }
onFinish={handleNextEpisodeAutoPlay} onFinish={handleNextEpisodeAutoPlay}

View File

@@ -5,7 +5,6 @@ import type {
} from "@jellyfin/sdk/lib/generated-client"; } from "@jellyfin/sdk/lib/generated-client";
import { useLocalSearchParams } from "expo-router"; import { useLocalSearchParams } from "expo-router";
import { type FC, useCallback, useEffect, useState } from "react"; import { type FC, useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, useWindowDimensions, View } from "react-native"; import { StyleSheet, useWindowDimensions, View } from "react-native";
import Animated, { import Animated, {
Easing, Easing,
@@ -17,8 +16,9 @@ import Animated, {
} from "react-native-reanimated"; } from "react-native-reanimated";
import ContinueWatchingOverlay from "@/components/video-player/controls/ContinueWatchingOverlay"; import ContinueWatchingOverlay from "@/components/video-player/controls/ContinueWatchingOverlay";
import useRouter from "@/hooks/useAppRouter"; import useRouter from "@/hooks/useAppRouter";
import { useCreditSkipper } from "@/hooks/useCreditSkipper";
import { useHaptic } from "@/hooks/useHaptic"; import { useHaptic } from "@/hooks/useHaptic";
import { useMediaSegments } from "@/hooks/useMediaSegments"; import { useIntroSkipper } from "@/hooks/useIntroSkipper";
import { usePlaybackManager } from "@/hooks/usePlaybackManager"; import { usePlaybackManager } from "@/hooks/usePlaybackManager";
import { useTrickplay } from "@/hooks/useTrickplay"; import { useTrickplay } from "@/hooks/useTrickplay";
import type { TechnicalInfo } from "@/modules/mpv-player"; import type { TechnicalInfo } from "@/modules/mpv-player";
@@ -26,7 +26,6 @@ import { DownloadedItem } from "@/providers/Downloads/types";
import { useOfflineMode } from "@/providers/OfflineModeProvider"; import { useOfflineMode } from "@/providers/OfflineModeProvider";
import { useSettings } from "@/utils/atoms/settings"; import { useSettings } from "@/utils/atoms/settings";
import { getDefaultPlaySettings } from "@/utils/jellyfin/getDefaultPlaySettings"; import { getDefaultPlaySettings } from "@/utils/jellyfin/getDefaultPlaySettings";
import { useSegments } from "@/utils/segments";
import { ticksToMs } from "@/utils/time"; import { ticksToMs } from "@/utils/time";
import { BottomControls } from "./BottomControls"; import { BottomControls } from "./BottomControls";
import { CenterControls } from "./CenterControls"; import { CenterControls } from "./CenterControls";
@@ -317,38 +316,27 @@ export const Controls: FC<Props> = ({
subtitleIndex: string; subtitleIndex: string;
}>(); }>();
// Fetch all segments for the current item const { showSkipButton, skipIntro } = useIntroSkipper(
const { data: segments } = useSegments( item.Id!,
item.Id ?? "",
offline,
downloadedFiles,
api,
);
// Unified segment orchestration (identical mechanism on mobile and TV):
// overlap priority + a single auto-skip driver live in the shared hook.
const {
activeSegment,
skipActiveSegment: onSkipSegment,
showSkipButton: showSkipSegmentButton,
isOutroActive: showSkipOutroButton,
skipOutro: onSkipOutro,
hasContentAfterCredits,
} = useMediaSegments({
segments,
currentTime, currentTime,
maxMs,
seek, seek,
play, play,
isPlaying, offline,
isBuffering, api,
}); downloadedFiles,
);
const { t } = useTranslation(); const { showSkipCreditButton, skipCredit, hasContentAfterCredits } =
const skipSegmentButtonText = activeSegment useCreditSkipper(
? t(`player.skip_${activeSegment.type.toLowerCase()}`) item.Id!,
: t("player.skip_intro"); currentTime,
const skipOutroButtonText = t("player.skip_outro"); seek,
play,
offline,
api,
downloadedFiles,
maxMs,
);
const goToItemCommon = useCallback( const goToItemCommon = useCallback(
(item: BaseItemDto) => { (item: BaseItemDto) => {
@@ -582,13 +570,11 @@ export const Controls: FC<Props> = ({
showRemoteBubble={showRemoteBubble} showRemoteBubble={showRemoteBubble}
currentTime={currentTime} currentTime={currentTime}
remainingTime={remainingTime} remainingTime={remainingTime}
showSkipSegmentButton={showSkipSegmentButton} showSkipButton={showSkipButton}
skipSegmentButtonText={skipSegmentButtonText} showSkipCreditButton={showSkipCreditButton}
showSkipOutroButton={showSkipOutroButton}
skipOutroButtonText={skipOutroButtonText}
hasContentAfterCredits={hasContentAfterCredits} hasContentAfterCredits={hasContentAfterCredits}
onSkipSegment={onSkipSegment} skipIntro={skipIntro}
onSkipOutro={onSkipOutro} skipCredit={skipCredit}
nextItem={nextItem} nextItem={nextItem}
handleNextEpisodeAutoPlay={handleNextEpisodeAutoPlay} handleNextEpisodeAutoPlay={handleNextEpisodeAutoPlay}
handleNextEpisodeManual={handleNextEpisodeManual} handleNextEpisodeManual={handleNextEpisodeManual}

View File

@@ -38,9 +38,9 @@ import {
import { TVFocusableProgressBar } from "@/components/tv/TVFocusableProgressBar"; import { TVFocusableProgressBar } from "@/components/tv/TVFocusableProgressBar";
import { useScaledTVTypography } from "@/constants/TVTypography"; import { useScaledTVTypography } from "@/constants/TVTypography";
import useRouter from "@/hooks/useAppRouter"; import useRouter from "@/hooks/useAppRouter";
import { useMediaSegments } from "@/hooks/useMediaSegments"; import { useCreditSkipper } from "@/hooks/useCreditSkipper";
import { useIntroSkipper } from "@/hooks/useIntroSkipper";
import { usePlaybackManager } from "@/hooks/usePlaybackManager"; import { usePlaybackManager } from "@/hooks/usePlaybackManager";
import type { SegmentType } from "@/hooks/useSegmentSkipper";
import { useTrickplay } from "@/hooks/useTrickplay"; import { useTrickplay } from "@/hooks/useTrickplay";
import { useTVOptionModal } from "@/hooks/useTVOptionModal"; import { useTVOptionModal } from "@/hooks/useTVOptionModal";
import { useTVSubtitleModal } from "@/hooks/useTVSubtitleModal"; import { useTVSubtitleModal } from "@/hooks/useTVSubtitleModal";
@@ -51,7 +51,6 @@ import { useOfflineMode } from "@/providers/OfflineModeProvider";
import { useSettings } from "@/utils/atoms/settings"; import { useSettings } from "@/utils/atoms/settings";
import type { TVOptionItem } from "@/utils/atoms/tvOptionModal"; import type { TVOptionItem } from "@/utils/atoms/tvOptionModal";
import { getDefaultPlaySettings } from "@/utils/jellyfin/getDefaultPlaySettings"; import { getDefaultPlaySettings } from "@/utils/jellyfin/getDefaultPlaySettings";
import { useSegments } from "@/utils/segments";
import { formatTimeString, msToTicks, ticksToMs } from "@/utils/time"; import { formatTimeString, msToTicks, ticksToMs } from "@/utils/time";
import { CONTROLS_CONSTANTS } from "./constants"; import { CONTROLS_CONSTANTS } from "./constants";
import { useVideoContext } from "./contexts/VideoContext"; import { useVideoContext } from "./contexts/VideoContext";
@@ -200,7 +199,6 @@ export const Controls: FC<Props> = ({
isSeeking, isSeeking,
progress, progress,
cacheProgress, cacheProgress,
isBuffering,
showControls, showControls,
setShowControls, setShowControls,
mediaSource, mediaSource,
@@ -429,42 +427,30 @@ export const Controls: FC<Props> = ({
seek, seek,
}); });
// Segment skipping (intro + outro/credits) via the unified hook. // Skip intro/credits hooks
// Note: hooks expect seek callback that takes ms, and seek prop already expects ms
const offline = useOfflineMode(); const offline = useOfflineMode();
const { showSkipButton, skipIntro } = useIntroSkipper(
const { data: segments } = useSegments( item.Id!,
item.Id ?? "", currentTime,
seek,
_play,
offline, offline,
downloadedFiles,
api, api,
downloadedFiles,
); );
// Unified segment orchestration (identical mechanism on mobile and TV): const { showSkipCreditButton, skipCredit, hasContentAfterCredits } =
// overlap priority + a single auto-skip driver live in the shared hook. useCreditSkipper(
const { item.Id!,
activeSegment, currentTime,
skipActiveSegment, seek,
showSkipButton, _play,
isOutroActive, offline,
skipOutro: skipCredit, api,
hasContentAfterCredits, downloadedFiles,
} = useMediaSegments({ max.value,
segments, );
currentTime,
maxMs,
seek,
play: _play,
isPlaying,
isBuffering,
});
// The outro keeps its dedicated card (it composes with the Next Episode
// countdown); the other four share the generic skip card.
const showSkipCreditButton = isOutroActive;
const activeSegmentType =
isOutroActive || !activeSegment
? "intro"
: (activeSegment.type.toLowerCase() as Lowercase<SegmentType>);
// Countdown logic // Countdown logic
const isCountdownActive = useMemo(() => { const isCountdownActive = useMemo(() => {
@@ -1140,11 +1126,11 @@ export const Controls: FC<Props> = ({
/> />
)} )}
{/* Generic skip card (intro / recap / commercial / preview) */} {/* Skip intro card */}
<TVSkipSegmentCard <TVSkipSegmentCard
show={showSkipButton && !isCountdownActive} show={showSkipButton && !isCountdownActive}
onPress={skipActiveSegment} onPress={skipIntro}
type={activeSegmentType} type='intro'
controlsVisible={showControls} controlsVisible={showControls}
refSetter={setSkipSegmentRef} refSetter={setSkipSegmentRef}
hasTVPreferredFocus={!showControls} hasTVPreferredFocus={!showControls}

109
hooks/useCreditSkipper.ts Normal file
View File

@@ -0,0 +1,109 @@
import { Api } from "@jellyfin/sdk";
import { useCallback, useEffect, useState } from "react";
import { DownloadedItem } from "@/providers/Downloads/types";
import { useSegments } from "@/utils/segments";
import { msToSeconds, secondsToMs } from "@/utils/time";
import { useHaptic } from "./useHaptic";
/**
* Custom hook to handle skipping credits in a media player.
* The player reports time values in milliseconds.
*/
export const useCreditSkipper = (
itemId: string,
currentTime: number,
seek: (ms: number) => void,
play: () => void,
isOffline = false,
api: Api | null = null,
downloadedFiles: DownloadedItem[] | undefined = undefined,
totalDuration?: number,
) => {
const [showSkipCreditButton, setShowSkipCreditButton] = useState(false);
const lightHapticFeedback = useHaptic("light");
// Convert ms to seconds for comparison with timestamps
const currentTimeSeconds = msToSeconds(currentTime);
const totalDurationInSeconds =
totalDuration != null ? msToSeconds(totalDuration) : undefined;
// Regular function (not useCallback) to match useIntroSkipper pattern
const wrappedSeek = (seconds: number) => {
seek(secondsToMs(seconds));
};
const { data: segments } = useSegments(
itemId,
isOffline,
downloadedFiles,
api,
);
const creditTimestamps = segments?.creditSegments?.[0];
// Determine if there's content after credits (credits don't extend to video end)
// Use a 5-second buffer to account for timing discrepancies
const hasContentAfterCredits = (() => {
if (
!creditTimestamps ||
totalDurationInSeconds == null ||
!Number.isFinite(totalDurationInSeconds)
) {
return false;
}
const creditsEndToVideoEnd =
totalDurationInSeconds - creditTimestamps.endTime;
// If credits end more than 5 seconds before video ends, there's content after
return creditsEndToVideoEnd > 5;
})();
useEffect(() => {
if (creditTimestamps) {
const shouldShow =
currentTimeSeconds > creditTimestamps.startTime &&
currentTimeSeconds < creditTimestamps.endTime;
setShowSkipCreditButton(shouldShow);
} else {
// Reset button state when no credit timestamps exist
if (showSkipCreditButton) {
setShowSkipCreditButton(false);
}
}
}, [creditTimestamps, currentTimeSeconds, showSkipCreditButton]);
const skipCredit = useCallback(() => {
if (!creditTimestamps) return;
try {
lightHapticFeedback();
// Calculate the target seek position
let seekTarget = creditTimestamps.endTime;
// If we have total duration, ensure we don't seek past the end of the video.
// Some media sources report credit end times that exceed the actual video duration,
// which causes the player to pause/stop when seeking past the end.
// Leave a small buffer (2 seconds) to trigger the natural end-of-video flow
// (next episode countdown, etc.) instead of an abrupt pause.
if (totalDurationInSeconds && seekTarget >= totalDurationInSeconds) {
seekTarget = Math.max(0, totalDurationInSeconds - 2);
}
wrappedSeek(seekTarget);
setTimeout(() => {
play();
}, 200);
} catch (error) {
console.error("[CREDIT_SKIPPER] Error skipping credit", error);
}
}, [
creditTimestamps,
lightHapticFeedback,
wrappedSeek,
play,
totalDurationInSeconds,
]);
return { showSkipCreditButton, skipCredit, hasContentAfterCredits };
};

68
hooks/useIntroSkipper.ts Normal file
View File

@@ -0,0 +1,68 @@
import { Api } from "@jellyfin/sdk";
import { useCallback, useEffect, useState } from "react";
import { DownloadedItem } from "@/providers/Downloads/types";
import { useSegments } from "@/utils/segments";
import { msToSeconds, secondsToMs } from "@/utils/time";
import { useHaptic } from "./useHaptic";
/**
* Custom hook to handle skipping intros in a media player.
* MPV player uses milliseconds for time.
*
* @param {number} currentTime - The current playback time in milliseconds.
*/
export const useIntroSkipper = (
itemId: string,
currentTime: number,
seek: (ms: number) => void,
play: () => void,
isOffline = false,
api: Api | null = null,
downloadedFiles: DownloadedItem[] | undefined = undefined,
) => {
const [showSkipButton, setShowSkipButton] = useState(false);
// Convert ms to seconds for comparison with timestamps
const currentTimeSeconds = msToSeconds(currentTime);
const lightHapticFeedback = useHaptic("light");
const wrappedSeek = (seconds: number) => {
seek(secondsToMs(seconds));
};
const { data: segments } = useSegments(
itemId,
isOffline,
downloadedFiles,
api,
);
const introTimestamps = segments?.introSegments?.[0];
useEffect(() => {
if (introTimestamps) {
const shouldShow =
currentTimeSeconds > introTimestamps.startTime &&
currentTimeSeconds < introTimestamps.endTime;
setShowSkipButton(shouldShow);
} else {
if (showSkipButton) {
setShowSkipButton(false);
}
}
}, [introTimestamps, currentTimeSeconds, showSkipButton]);
const skipIntro = useCallback(() => {
if (!introTimestamps) return;
try {
lightHapticFeedback();
wrappedSeek(introTimestamps.endTime);
setTimeout(() => {
play();
}, 200);
} catch (error) {
console.error("[INTRO_SKIPPER] Error skipping intro", error);
}
}, [introTimestamps, lightHapticFeedback, wrappedSeek, play]);
return { showSkipButton, skipIntro };
};

View File

@@ -1,220 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { MediaTimeSegment } from "@/providers/Downloads/types";
import type { SegmentSkipMode } from "@/utils/atoms/settings";
import type { SegmentBuckets } from "@/utils/segments";
import { type SegmentType, useSegmentSkipper } from "./useSegmentSkipper";
const noop = () => {};
// Delay the FIRST auto-skip until playback has been stable this long. Seeking a
// transcoded stream the instant the first frame appears (e.g. a 0:00 intro)
// asks the transcode for a segment it hasn't produced yet and stalls at 0:00;
// direct-play is always seekable so the delay is invisible there.
const AUTO_SKIP_ARM_DELAY_MS = 1500;
export interface ActiveSegment {
type: SegmentType;
currentSegment: MediaTimeSegment;
skipSegment: (useHaptics?: boolean) => void;
skipMode: SegmentSkipMode;
}
interface UseMediaSegmentsProps {
segments: SegmentBuckets | undefined;
/** Current playback position, in ms. */
currentTime: number;
/** Total media duration, in ms. */
maxMs?: number;
/** Player seek, expects ms. */
seek: (ms: number) => void;
/** Player resume. */
play: () => void;
isPlaying: boolean;
/** True while the player is (re)buffering; auto-skip waits for this to clear. */
isBuffering?: boolean;
}
export interface UseMediaSegmentsReturn {
/** Highest-priority segment under the playhead (excludes 'none' types), or null. */
activeSegment: ActiveSegment | null;
/** Skip the active segment (no-op when there is none). */
skipActiveSegment: (useHaptics?: boolean) => void;
/** Show the generic skip button: an active segment that is not the outro. */
showSkipButton: boolean;
/** The active segment is the outro/credits (it gets its own button/card). */
isOutroActive: boolean;
/** Skip the outro, independent of which button the priority shows. */
skipOutro: (useHaptics?: boolean) => void;
/** The outro ends before the media end, i.e. there is content after credits. */
hasContentAfterCredits: boolean;
}
/**
* Unified media-segment orchestration shared by the mobile and TV player controls.
* Owns the per-type skippers, the seek-with-delayed-play workaround, the overlap
* priority (Commercial > Recap > Intro > Preview > Outro) and a SINGLE auto-skip
* driver, so overlapping auto-enabled segments can't fire competing seeks and both
* platforms behave identically.
*/
export const useMediaSegments = ({
segments,
currentTime,
maxMs,
seek,
play,
isPlaying,
isBuffering = false,
}: UseMediaSegmentsProps): UseMediaSegmentsReturn => {
// Keep sub-second precision: segment boundaries are fractional seconds, so
// flooring currentTime would detect segments up to ~1s late / end them early.
const currentTimeSeconds = currentTime / 1000;
const maxSeconds = maxMs ? maxMs / 1000 : undefined;
// Seek-with-delayed-play workaround: some seeks otherwise resume from the
// pre-seek position. playingRef avoids a stale closure on isPlaying.
const playTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const playingRef = useRef(isPlaying);
useEffect(() => {
playingRef.current = isPlaying;
}, [isPlaying]);
useEffect(() => {
return () => {
if (playTimeoutRef.current) clearTimeout(playTimeoutRef.current);
};
}, []);
const seekSeconds = useCallback(
(timeInSeconds: number) => {
if (playTimeoutRef.current) clearTimeout(playTimeoutRef.current);
seek(timeInSeconds * 1000);
playTimeoutRef.current = setTimeout(() => {
if (playingRef.current) play();
playTimeoutRef.current = null;
}, 200);
},
[seek, play],
);
const introSkipper = useSegmentSkipper({
segments: segments?.introSegments ?? [],
segmentType: "Intro",
currentTime: currentTimeSeconds,
seek: seekSeconds,
});
const outroSkipper = useSegmentSkipper({
segments: segments?.creditSegments ?? [],
segmentType: "Outro",
currentTime: currentTimeSeconds,
totalDuration: maxSeconds,
seek: seekSeconds,
});
const recapSkipper = useSegmentSkipper({
segments: segments?.recapSegments ?? [],
segmentType: "Recap",
currentTime: currentTimeSeconds,
seek: seekSeconds,
});
const commercialSkipper = useSegmentSkipper({
segments: segments?.commercialSegments ?? [],
segmentType: "Commercial",
currentTime: currentTimeSeconds,
seek: seekSeconds,
});
const previewSkipper = useSegmentSkipper({
segments: segments?.previewSegments ?? [],
segmentType: "Preview",
currentTime: currentTimeSeconds,
seek: seekSeconds,
});
// Priority when multiple segments overlap: Commercial > Recap > Intro > Preview > Outro.
const activeSegment = useMemo<ActiveSegment | null>(() => {
const byPriority: Array<[SegmentType, typeof introSkipper]> = [
["Commercial", commercialSkipper],
["Recap", recapSkipper],
["Intro", introSkipper],
["Preview", previewSkipper],
["Outro", outroSkipper],
];
for (const [type, skipper] of byPriority) {
if (skipper.currentSegment) {
return {
type,
currentSegment: skipper.currentSegment,
skipSegment: skipper.skipSegment,
skipMode: skipper.skipMode,
};
}
}
return null;
}, [
commercialSkipper.currentSegment,
commercialSkipper.skipSegment,
commercialSkipper.skipMode,
recapSkipper.currentSegment,
recapSkipper.skipSegment,
recapSkipper.skipMode,
introSkipper.currentSegment,
introSkipper.skipSegment,
introSkipper.skipMode,
previewSkipper.currentSegment,
previewSkipper.skipSegment,
previewSkipper.skipMode,
outroSkipper.currentSegment,
outroSkipper.skipSegment,
outroSkipper.skipMode,
]);
// Single auto-skip driver: only the priority-resolved active segment skips,
// so overlapping auto-enabled segments can't trigger competing seeks.
const autoSkipTriggeredRef = useRef<string | null>(null);
const [autoSkipArmed, setAutoSkipArmed] = useState(false);
// Reset per item (its segments change): re-allow skipping and re-arm so the
// next episode's transcode has time to become seekable. We do NOT reset the
// guard when the active segment momentarily disappears — seeking a transcoded
// stream makes the reported position bounce back into a 0:00 intro, and
// clearing the guard there caused an infinite seek loop that crashed mpv.
useEffect(() => {
autoSkipTriggeredRef.current = null;
setAutoSkipArmed(false);
}, [segments]);
// Arm auto-skip once playback has been genuinely stable (not buffering) for a
// short moment, so the first seek lands on an established (seekable) timeline.
useEffect(() => {
if (autoSkipArmed || isBuffering || !isPlaying) return;
const id = setTimeout(() => setAutoSkipArmed(true), AUTO_SKIP_ARM_DELAY_MS);
return () => clearTimeout(id);
}, [autoSkipArmed, isBuffering, isPlaying]);
useEffect(() => {
if (
!autoSkipArmed ||
!activeSegment ||
!isPlaying ||
isBuffering ||
activeSegment.skipMode !== "auto"
)
return;
const { startTime, endTime } = activeSegment.currentSegment;
const segmentId = `${activeSegment.type}:${startTime}-${endTime}`;
if (autoSkipTriggeredRef.current === segmentId) return;
autoSkipTriggeredRef.current = segmentId;
activeSegment.skipSegment(false);
}, [activeSegment, isPlaying, isBuffering, autoSkipArmed]);
const isOutroActive = activeSegment?.type === "Outro";
return {
activeSegment,
skipActiveSegment: activeSegment?.skipSegment ?? noop,
showSkipButton: !!activeSegment && !isOutroActive,
isOutroActive,
skipOutro: outroSkipper.skipSegment,
hasContentAfterCredits:
outroSkipper.currentSegment && maxSeconds
? outroSkipper.currentSegment.endTime < maxSeconds
: false,
};
};

View File

@@ -1,104 +0,0 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { MediaTimeSegment } from "@/providers/Downloads/types";
import { SegmentSkipMode, useSettings } from "@/utils/atoms/settings";
import { useHaptic } from "./useHaptic";
export type SegmentType =
| "Intro"
| "Outro"
| "Recap"
| "Commercial"
| "Preview";
const SEGMENT_TO_SETTING: Record<
SegmentType,
"skipIntro" | "skipOutro" | "skipRecap" | "skipCommercial" | "skipPreview"
> = {
Intro: "skipIntro",
Outro: "skipOutro",
Recap: "skipRecap",
Commercial: "skipCommercial",
Preview: "skipPreview",
};
interface UseSegmentSkipperProps {
segments: MediaTimeSegment[];
segmentType: SegmentType;
currentTime: number;
totalDuration?: number;
seek: (time: number) => void;
}
interface UseSegmentSkipperReturn {
currentSegment: MediaTimeSegment | null;
skipSegment: (useHaptics?: boolean) => void;
skipMode: SegmentSkipMode;
}
/**
* Generic hook for a single media segment type (intro, outro, recap, commercial, preview).
* Reports the segment currently under the playhead, its skip mode, and a skip action.
* Auto-skip is NOT performed here: the consumer drives it from the priority-resolved
* active segment so overlapping segments can't trigger competing seeks.
*/
export const useSegmentSkipper = ({
segments,
segmentType,
currentTime,
totalDuration,
seek,
}: UseSegmentSkipperProps): UseSegmentSkipperReturn => {
const { settings } = useSettings();
const haptic = useHaptic();
const skipMode: SegmentSkipMode =
settings?.[SEGMENT_TO_SETTING[segmentType]] ?? "none";
const currentSegment = useMemo(
() =>
segments.find(
(s) => currentTime >= s.startTime && currentTime < s.endTime,
) ?? null,
[segments, currentTime],
);
// Refs keep skipSegment's identity stable across seek/haptic changes
// (haptic is unstable when disabled), so the consumer's auto-skip effect
// doesn't re-fire spuriously.
const seekRef = useRef(seek);
const hapticRef = useRef(haptic);
useEffect(() => {
seekRef.current = seek;
hapticRef.current = haptic;
});
const skipSegment = useCallback(
(useHaptics = true) => {
if (!currentSegment || skipMode === "none") return;
// Outro endTime sometimes exceeds the actual file duration. Keep a 2s
// buffer so the player's natural end-of-video flow (next-episode
// countdown, etc.) still fires instead of stalling at the exact end.
let target = currentSegment.endTime;
if (
segmentType === "Outro" &&
totalDuration != null &&
Number.isFinite(totalDuration) &&
target >= totalDuration
) {
target = Math.max(0, totalDuration - 2);
}
seekRef.current(target);
if (useHaptics) hapticRef.current();
},
[currentSegment, segmentType, totalDuration, skipMode],
);
return {
currentSegment: skipMode === "none" ? null : currentSegment,
skipSegment,
skipMode,
};
};

View File

@@ -32,6 +32,12 @@ export interface MediaTimeSegment {
text: string; text: string;
} }
export interface Segment {
startTime: number;
endTime: number;
text: string;
}
/** Represents a single downloaded media item with all necessary metadata for offline playback. */ /** Represents a single downloaded media item with all necessary metadata for offline playback. */
export interface DownloadedItem { export interface DownloadedItem {
/** The Jellyfin item DTO. */ /** The Jellyfin item DTO. */
@@ -50,12 +56,6 @@ export interface DownloadedItem {
introSegments?: MediaTimeSegment[]; introSegments?: MediaTimeSegment[];
/** The credit segments for the item. */ /** The credit segments for the item. */
creditSegments?: MediaTimeSegment[]; creditSegments?: MediaTimeSegment[];
/** The recap segments for the item. */
recapSegments?: MediaTimeSegment[];
/** The commercial segments for the item. */
commercialSegments?: MediaTimeSegment[];
/** The preview segments for the item. */
previewSegments?: MediaTimeSegment[];
/** The user data for the item. */ /** The user data for the item. */
userData: UserData; userData: UserData;
} }
@@ -144,12 +144,6 @@ export type JobStatus = {
introSegments?: MediaTimeSegment[]; introSegments?: MediaTimeSegment[];
/** Pre-downloaded credit segments (optional) - downloaded before video starts */ /** Pre-downloaded credit segments (optional) - downloaded before video starts */
creditSegments?: MediaTimeSegment[]; creditSegments?: MediaTimeSegment[];
/** Pre-downloaded recap segments (optional) - downloaded before video starts */
recapSegments?: MediaTimeSegment[];
/** Pre-downloaded commercial segments (optional) - downloaded before video starts */
commercialSegments?: MediaTimeSegment[];
/** Pre-downloaded preview segments (optional) - downloaded before video starts */
previewSegments?: MediaTimeSegment[];
/** The audio stream index selected for this download */ /** The audio stream index selected for this download */
audioStreamIndex?: number; audioStreamIndex?: number;
/** The subtitle stream index selected for this download */ /** The subtitle stream index selected for this download */

View File

@@ -304,21 +304,6 @@
"default_playback_speed": "Default playback speed", "default_playback_speed": "Default playback speed",
"auto_play_next_episode": "Auto-play next episode", "auto_play_next_episode": "Auto-play next episode",
"max_auto_play_episode_count": "Max auto-play episode count", "max_auto_play_episode_count": "Max auto-play episode count",
"segment_skip_settings": "Segment skip settings",
"segment_skip_settings_description": "Configure skip behavior for intros, credits, and other segments",
"skip_intro": "Skip intro",
"skip_intro_description": "Action when intro segment is detected",
"skip_outro": "Skip outro/credits",
"skip_outro_description": "Action when outro/credits segment is detected",
"skip_recap": "Skip recap",
"skip_recap_description": "Action when recap segment is detected",
"skip_commercial": "Skip commercial",
"skip_commercial_description": "Action when commercial segment is detected",
"skip_preview": "Skip preview",
"skip_preview_description": "Action when preview segment is detected",
"segment_skip_none": "None",
"segment_skip_ask": "Show skip button",
"segment_skip_auto": "Auto skip",
"disabled": "Disabled" "disabled": "Disabled"
}, },
"music": { "music": {
@@ -644,10 +629,6 @@
"settings": "Settings", "settings": "Settings",
"skip_intro": "Skip intro", "skip_intro": "Skip intro",
"skip_credits": "Skip credits", "skip_credits": "Skip credits",
"skip_outro": "Skip outro",
"skip_recap": "Skip recap",
"skip_commercial": "Skip commercial",
"skip_preview": "Skip preview",
"stopPlayback": "Stop playback", "stopPlayback": "Stop playback",
"stopPlayingTitle": "Stop playing \"{{title}}\"?", "stopPlayingTitle": "Stop playing \"{{title}}\"?",
"stopPlayingConfirm": "Are you sure you want to stop playback?", "stopPlayingConfirm": "Are you sure you want to stop playback?",

View File

@@ -183,9 +183,6 @@ export enum TVTypographyScale {
ExtraLarge = "extraLarge", ExtraLarge = "extraLarge",
} }
// Segment skip behavior options
export type SegmentSkipMode = "none" | "ask" | "auto";
// Audio transcoding mode - controls how surround audio is handled // Audio transcoding mode - controls how surround audio is handled
// This controls server-side transcoding behavior for audio streams. // This controls server-side transcoding behavior for audio streams.
// MPV decodes via FFmpeg and supports most formats, but mobile devices // MPV decodes via FFmpeg and supports most formats, but mobile devices
@@ -249,12 +246,6 @@ export type Settings = {
maxAutoPlayEpisodeCount: MaxAutoPlayEpisodeCount; maxAutoPlayEpisodeCount: MaxAutoPlayEpisodeCount;
autoPlayEpisodeCount: number; autoPlayEpisodeCount: number;
autoPlayNextEpisode: boolean; autoPlayNextEpisode: boolean;
// Media segment skip preferences
skipIntro: SegmentSkipMode;
skipOutro: SegmentSkipMode;
skipRecap: SegmentSkipMode;
skipCommercial: SegmentSkipMode;
skipPreview: SegmentSkipMode;
// Playback speed settings // Playback speed settings
defaultPlaybackSpeed: number; defaultPlaybackSpeed: number;
playbackSpeedPerMedia: Record<string, number>; playbackSpeedPerMedia: Record<string, number>;
@@ -358,12 +349,6 @@ export const defaultValues: Settings = {
maxAutoPlayEpisodeCount: { key: "3", value: 3 }, maxAutoPlayEpisodeCount: { key: "3", value: 3 },
autoPlayEpisodeCount: 0, autoPlayEpisodeCount: 0,
autoPlayNextEpisode: true, autoPlayNextEpisode: true,
// Media segment skip defaults
skipIntro: "ask",
skipOutro: "ask",
skipRecap: "ask",
skipCommercial: "ask",
skipPreview: "ask",
// Playback speed defaults // Playback speed defaults
defaultPlaybackSpeed: 1.0, defaultPlaybackSpeed: 1.0,
playbackSpeedPerMedia: {}, playbackSpeedPerMedia: {},

View File

@@ -44,9 +44,22 @@ export const isSubtitleInMpv = (
/** /**
* Calculate the MPV track ID for a given Jellyfin subtitle index. * Calculate the MPV track ID for a given Jellyfin subtitle index.
* *
* MPV track IDs are 1-based and only count subtitles that are actually in MPV. * MPV track IDs are 1-based, but MPV's track list is NOT in MediaStreams order:
* We iterate through all subtitles, counting only those in MPV, until we find * 1. Embedded/HLS subs are enumerated from the container (or HLS playlist)
* the one matching the Jellyfin index. * first, in MediaStreams order.
* 2. External subs are appended via `sub-add` AFTER the file loads, in the
* order they are passed to MPV (here, also MediaStreams order — see
* direct-player.tsx where the externalSubtitles array is built by
* filtering MediaStreams).
*
* Iterating in pure MediaStreams order produces the wrong MPV ID whenever an
* External sub is listed before an Embed sub in MediaStreams (common when
* Jellyfin prepends a converted SRT/VTT ahead of an original PGS/ASS track),
* causing e.g. English to select Spanish. We therefore count in two phases
* that mirror MPV's actual ordering.
*
* Image-based subs (PGS/VOBSUB) during transcoding are burned into the video
* and absent from MPV's track list; they are skipped in both phases.
* *
* @param mediaSource - The media source containing subtitle streams * @param mediaSource - The media source containing subtitle streams
* @param jellyfinSubtitleIndex - The Jellyfin server-side subtitle index (-1 = disabled) * @param jellyfinSubtitleIndex - The Jellyfin server-side subtitle index (-1 = disabled)
@@ -74,14 +87,30 @@ export const getMpvSubtitleId = (
return undefined; return undefined;
} }
// Count MPV track position (1-based) const isExternal = (sub: MediaStream) =>
sub.DeliveryMethod === SubtitleDeliveryMethod.External;
let mpvIndex = 0; let mpvIndex = 0;
// Phase 1: embedded / HLS subs — these occupy MPV track IDs first because
// they come from the container or HLS playlist.
for (const sub of allSubs) { for (const sub of allSubs) {
if (isSubtitleInMpv(sub, isTranscoding)) { if (isExternal(sub)) continue;
mpvIndex++; if (!isSubtitleInMpv(sub, isTranscoding)) continue;
if (sub.Index === jellyfinSubtitleIndex) { mpvIndex++;
return mpvIndex; if (sub.Index === jellyfinSubtitleIndex) {
} return mpvIndex;
}
}
// Phase 2: external subs — appended via `sub-add` after the file loads,
// so they come last in MPV's track list.
for (const sub of allSubs) {
if (!isExternal(sub)) continue;
if (!isSubtitleInMpv(sub, isTranscoding)) continue;
mpvIndex++;
if (sub.Index === jellyfinSubtitleIndex) {
return mpvIndex;
} }
} }

View File

@@ -1,40 +1,46 @@
import { Api } from "@jellyfin/sdk"; import { Api } from "@jellyfin/sdk";
import { MediaSegmentType } from "@jellyfin/sdk/lib/generated-client/models/media-segment-type";
import { getMediaSegmentsApi } from "@jellyfin/sdk/lib/utils/api/media-segments-api";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import React from "react"; import React from "react";
import { DownloadedItem, MediaTimeSegment } from "@/providers/Downloads/types"; import { DownloadedItem, MediaTimeSegment } from "@/providers/Downloads/types";
import { getAuthHeaders } from "./jellyfin/jellyfin"; import { getAuthHeaders } from "./jellyfin/jellyfin";
export interface SegmentBuckets { // New Jellyfin 10.11+ Media Segments API types
introSegments: MediaTimeSegment[]; interface MediaSegmentDto {
creditSegments: MediaTimeSegment[]; Id: string;
recapSegments: MediaTimeSegment[]; ItemId: string;
commercialSegments: MediaTimeSegment[]; Type: "Intro" | "Outro" | "Recap" | "Commercial" | "Preview";
previewSegments: MediaTimeSegment[]; StartTicks: number;
EndTicks: number;
} }
// Legacy endpoints (intro-skipper / chapter-credits plugins on pre-10.11 servers) interface MediaSegmentsResponse {
Items: MediaSegmentDto[];
}
// Legacy API types (for fallback)
interface IntroTimestamps { interface IntroTimestamps {
IntroStart: number; EpisodeId: string;
HideSkipPromptAt: number;
IntroEnd: number; IntroEnd: number;
IntroStart: number;
ShowSkipPromptAt: number;
Valid: boolean; Valid: boolean;
} }
interface CreditTimestamps { interface CreditTimestamps {
Credits: { Start: number; End: number; Valid: boolean }; Introduction: {
Start: number;
End: number;
Valid: boolean;
};
Credits: {
Start: number;
End: number;
Valid: boolean;
};
} }
const TICKS_PER_SECOND = 10_000_000; const TICKS_PER_SECOND = 10000000;
const ticksToSeconds = (ticks: number): number => ticks / TICKS_PER_SECOND;
const emptyBuckets = (): SegmentBuckets => ({
introSegments: [],
creditSegments: [],
recapSegments: [],
commercialSegments: [],
previewSegments: [],
});
export const useSegments = ( export const useSegments = (
itemId: string, itemId: string,
@@ -42,6 +48,7 @@ export const useSegments = (
downloadedFiles: DownloadedItem[] | undefined, downloadedFiles: DownloadedItem[] | undefined,
api: Api | null, api: Api | null,
) => { ) => {
// Memoize the lookup so the array is only traversed when dependencies change
const downloadedItem = React.useMemo( const downloadedItem = React.useMemo(
() => downloadedFiles?.find((d) => d.item.Id === itemId), () => downloadedFiles?.find((d) => d.item.Id === itemId),
[downloadedFiles, itemId], [downloadedFiles, itemId],
@@ -58,110 +65,141 @@ export const useSegments = (
} }
return fetchAndParseSegments(itemId, api); return fetchAndParseSegments(itemId, api);
}, },
enabled: !!itemId && (isOffline ? !!downloadedItem : !!api), enabled: isOffline ? !!downloadedItem : !!api,
}); });
}; };
export const getSegmentsForItem = (item: DownloadedItem): SegmentBuckets => ({ export const getSegmentsForItem = (
introSegments: item.introSegments || [], item: DownloadedItem,
creditSegments: item.creditSegments || [], ): {
recapSegments: item.recapSegments || [], introSegments: MediaTimeSegment[];
commercialSegments: item.commercialSegments || [], creditSegments: MediaTimeSegment[];
previewSegments: item.previewSegments || [], } => {
}); return {
introSegments: item.introSegments || [],
creditSegments: item.creditSegments || [],
};
};
/** Jellyfin 10.11+ unified MediaSegments API. Returns null so the caller can fall back. */ /**
* Converts Jellyfin ticks to seconds
*/
const ticksToSeconds = (ticks: number): number => ticks / TICKS_PER_SECOND;
/**
* Fetches segments using the new Jellyfin 10.11+ MediaSegments API
*/
const fetchMediaSegments = async ( const fetchMediaSegments = async (
itemId: string, itemId: string,
api: Api, api: Api,
): Promise<SegmentBuckets | null> => { ): Promise<{
introSegments: MediaTimeSegment[];
creditSegments: MediaTimeSegment[];
} | null> => {
try { try {
const response = await getMediaSegmentsApi(api).getItemSegments({ const response = await api.axiosInstance.get<MediaSegmentsResponse>(
itemId, `${api.basePath}/MediaSegments/${itemId}`,
includeSegmentTypes: [ {
MediaSegmentType.Intro, headers: getAuthHeaders(api),
MediaSegmentType.Outro, params: {
MediaSegmentType.Recap, includeSegmentTypes: ["Intro", "Outro"],
MediaSegmentType.Commercial, },
MediaSegmentType.Preview, },
], );
});
const buckets = emptyBuckets(); const introSegments: MediaTimeSegment[] = [];
for (const segment of response.data.Items ?? []) { const creditSegments: MediaTimeSegment[] = [];
if (segment.StartTicks == null || segment.EndTicks == null) continue;
response.data.Items.forEach((segment) => {
const timeSegment: MediaTimeSegment = { const timeSegment: MediaTimeSegment = {
startTime: ticksToSeconds(segment.StartTicks), startTime: ticksToSeconds(segment.StartTicks),
endTime: ticksToSeconds(segment.EndTicks), endTime: ticksToSeconds(segment.EndTicks),
text: segment.Type ?? "", text: segment.Type,
}; };
switch (segment.Type) { switch (segment.Type) {
case MediaSegmentType.Intro: case "Intro":
buckets.introSegments.push(timeSegment); introSegments.push(timeSegment);
break; break;
case MediaSegmentType.Outro: case "Outro":
buckets.creditSegments.push(timeSegment); creditSegments.push(timeSegment);
break; break;
case MediaSegmentType.Recap: // Optionally handle other types like Recap, Commercial, Preview
buckets.recapSegments.push(timeSegment); default:
break;
case MediaSegmentType.Commercial:
buckets.commercialSegments.push(timeSegment);
break;
case MediaSegmentType.Preview:
buckets.previewSegments.push(timeSegment);
break; break;
} }
} });
return buckets; return { introSegments, creditSegments };
} catch { } catch (_error) {
// Return null to indicate we should try legacy endpoints
return null; return null;
} }
}; };
/** Pre-10.11 fallback: third-party intro-skipper / chapter-credits plugin endpoints. */ /**
* Fetches segments using legacy pre-10.11 endpoints
*/
const fetchLegacySegments = async ( const fetchLegacySegments = async (
itemId: string, itemId: string,
api: Api, api: Api,
): Promise<SegmentBuckets> => { ): Promise<{
const buckets = emptyBuckets(); introSegments: MediaTimeSegment[];
creditSegments: MediaTimeSegment[];
}> => {
const introSegments: MediaTimeSegment[] = [];
const creditSegments: MediaTimeSegment[] = [];
const [introRes, creditRes] = await Promise.allSettled([ try {
api.axiosInstance.get<IntroTimestamps>( const [introRes, creditRes] = await Promise.allSettled([
`${api.basePath}/Episode/${itemId}/IntroTimestamps`, api.axiosInstance.get<IntroTimestamps>(
{ headers: getAuthHeaders(api) }, `${api.basePath}/Episode/${itemId}/IntroTimestamps`,
), { headers: getAuthHeaders(api) },
api.axiosInstance.get<CreditTimestamps>( ),
`${api.basePath}/Episode/${itemId}/Timestamps`, api.axiosInstance.get<CreditTimestamps>(
{ headers: getAuthHeaders(api) }, `${api.basePath}/Episode/${itemId}/Timestamps`,
), { headers: getAuthHeaders(api) },
]); ),
]);
if (introRes.status === "fulfilled" && introRes.value.data.Valid) { if (introRes.status === "fulfilled" && introRes.value.data.Valid) {
buckets.introSegments.push({ introSegments.push({
startTime: introRes.value.data.IntroStart, startTime: introRes.value.data.IntroStart,
endTime: introRes.value.data.IntroEnd, endTime: introRes.value.data.IntroEnd,
text: "Intro", text: "Intro",
}); });
}
if (
creditRes.status === "fulfilled" &&
creditRes.value.data.Credits.Valid
) {
creditSegments.push({
startTime: creditRes.value.data.Credits.Start,
endTime: creditRes.value.data.Credits.End,
text: "Credits",
});
}
} catch (error) {
console.error("Failed to fetch legacy segments", error);
} }
if (creditRes.status === "fulfilled" && creditRes.value.data.Credits.Valid) { return { introSegments, creditSegments };
buckets.creditSegments.push({
startTime: creditRes.value.data.Credits.Start,
endTime: creditRes.value.data.Credits.End,
text: "Outro",
});
}
return buckets;
}; };
export const fetchAndParseSegments = async ( export const fetchAndParseSegments = async (
itemId: string, itemId: string,
api: Api, api: Api,
): Promise<SegmentBuckets> => { ): Promise<{
introSegments: MediaTimeSegment[];
creditSegments: MediaTimeSegment[];
}> => {
// Try new API first (Jellyfin 10.11+)
const newSegments = await fetchMediaSegments(itemId, api); const newSegments = await fetchMediaSegments(itemId, api);
return newSegments ?? fetchLegacySegments(itemId, api); if (newSegments) {
return newSegments;
}
// Fallback to legacy endpoints
return fetchLegacySegments(itemId, api);
}; };