Files
streamyfin/app/(auth)/casting-player.tsx
Uruk 6894decdba feat: optimize and complete casting system implementation
Performance Optimizations:
- Add progress tracking to skip redundant Jellyfin API calls (< 5s changes)
- Debounce volume changes (300ms) to reduce API load
- Memoize expensive calculations (protocol colors, icons, progress percent)
- Remove dead useChromecastPlayer hook (redundant with useCasting)

Feature Integrations:
- Add ChromecastEpisodeList modal with Episodes button for TV shows
- Add ChromecastDeviceSheet modal accessible via device indicator
- Add ChromecastSettingsMenu modal with settings icon
- Integrate segment detection with Skip Intro/Credits/Recap buttons
- Add next episode countdown UI (30s before end)

AirPlay Support:
- Add comprehensive documentation for AirPlay detection approaches
- Document integration requirements with AVRoutePickerView
- Prepare infrastructure for native module or AVPlayer integration

UI Improvements:
- Make device indicator tappable to open device sheet
- Add settings icon in header
- Show segment skip buttons dynamically based on current playback
- Display next episode countdown with cancel option
- Optimize hook ordering to prevent conditional hook violations

TODOs for future work:
- Fetch actual episode list from Jellyfin API
- Wire media source/audio/subtitle track selectors to player
- Implement episode auto-play logic
- Create native module for AirPlay state detection
- Add RemoteMediaClient to segment skip functions
2026-05-21 00:47:31 +02:00

595 lines
18 KiB
TypeScript

/**
* Unified Casting Player Modal
* Full-screen player for both Chromecast and AirPlay
*/
import { Ionicons } from "@expo/vector-icons";
import { Image } from "expo-image";
import { router } from "expo-router";
import { useAtomValue } from "jotai";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import Animated, {
runOnJS,
useAnimatedStyle,
useSharedValue,
withSpring,
} from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ChromecastDeviceSheet } from "@/components/chromecast/ChromecastDeviceSheet";
import { ChromecastEpisodeList } from "@/components/chromecast/ChromecastEpisodeList";
import { ChromecastSettingsMenu } from "@/components/chromecast/ChromecastSettingsMenu";
import { useChromecastSegments } from "@/components/chromecast/hooks/useChromecastSegments";
import { Text } from "@/components/common/Text";
import { useCasting } from "@/hooks/useCasting";
import { apiAtom } from "@/providers/JellyfinProvider";
import {
calculateEndingTime,
formatTime,
getPosterUrl,
getProtocolIcon,
getProtocolName,
shouldShowNextEpisodeCountdown,
truncateTitle,
} from "@/utils/casting/helpers";
import { PROTOCOL_COLORS } from "@/utils/casting/types";
export default function CastingPlayerScreen() {
const insets = useSafeAreaInsets();
const api = useAtomValue(apiAtom);
const {
isConnected,
protocol,
currentItem,
currentDevice,
progress,
duration,
isPlaying,
isBuffering,
togglePlayPause,
skipForward,
skipBackward,
stop,
setVolume,
volume,
} = useCasting(null);
// Modal states
const [showEpisodeList, setShowEpisodeList] = useState(false);
const [showDeviceSheet, setShowDeviceSheet] = useState(false);
const [showSettings, setShowSettings] = useState(false);
// Segment detection (skip intro/credits)
const { currentSegment, skipIntro, skipCredits, skipSegment } =
useChromecastSegments(currentItem, progress, false);
// Swipe down to dismiss gesture
const translateY = useSharedValue(0);
const context = useSharedValue({ y: 0 });
const dismissModal = useCallback(() => {
if (router.canGoBack()) {
router.back();
}
}, []);
const panGesture = Gesture.Pan()
.onStart(() => {
context.value = { y: translateY.value };
})
.onUpdate((event) => {
if (event.translationY > 0) {
translateY.value = event.translationY;
}
})
.onEnd((event) => {
if (event.translationY > 100) {
translateY.value = withSpring(500, {}, () => {
runOnJS(dismissModal)();
});
} else {
translateY.value = withSpring(0);
}
});
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateY: translateY.value }],
}));
// Memoize expensive calculations (before early return)
const posterUrl = useMemo(
() =>
getPosterUrl(
api?.basePath,
currentItem?.Id,
currentItem?.ImageTags?.Primary,
300,
450,
),
[api?.basePath, currentItem?.Id, currentItem?.ImageTags?.Primary],
);
const progressPercent = useMemo(
() => (duration > 0 ? (progress / duration) * 100 : 0),
[progress, duration],
);
const protocolColor = useMemo(
() => (protocol ? PROTOCOL_COLORS[protocol] : "#666"),
[protocol],
);
const protocolIcon = useMemo(
() => (protocol ? getProtocolIcon(protocol) : ("tv" as const)),
[protocol],
);
const protocolName = useMemo(
() => (protocol ? getProtocolName(protocol) : "Unknown"),
[protocol],
);
const showNextEpisode = useMemo(() => {
if (currentItem?.Type !== "Episode") return false;
const remaining = duration - progress;
const hasNextEpisode = false; // TODO: Detect if next episode exists
return shouldShowNextEpisodeCountdown(remaining, hasNextEpisode, 30);
}, [currentItem?.Type, duration, progress]);
// Redirect if not connected
if (!isConnected || !currentItem || !protocol) {
if (router.canGoBack()) {
router.back();
}
return null;
}
return (
<GestureDetector gesture={panGesture}>
<Animated.View
style={[
{
flex: 1,
backgroundColor: "#000",
paddingTop: insets.top,
paddingBottom: insets.bottom,
},
animatedStyle,
]}
>
<ScrollView
contentContainerStyle={{
flexGrow: 1,
paddingHorizontal: 20,
}}
showsVerticalScrollIndicator={false}
>
{/* Header */}
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 32,
}}
>
<Pressable
onPress={dismissModal}
style={{ padding: 8, marginLeft: -8 }}
>
<Ionicons name='chevron-down' size={32} color='white' />
</Pressable>
{/* Connection indicator */}
<Pressable
onPress={() => setShowDeviceSheet(true)}
style={{
flexDirection: "row",
alignItems: "center",
gap: 6,
paddingHorizontal: 12,
paddingVertical: 6,
backgroundColor: "#1a1a1a",
borderRadius: 16,
}}
>
<View
style={{
width: 8,
height: 8,
borderRadius: 4,
backgroundColor: protocolColor,
}}
/>
<Text
style={{
color: protocolColor,
fontSize: 12,
fontWeight: "500",
}}
>
{protocolName}
</Text>
</Pressable>
<Pressable
onPress={() => setShowSettings(true)}
style={{ padding: 8, marginRight: -8 }}
>
<Ionicons name='settings-outline' size={24} color='white' />
</Pressable>
</View>
{/* Title and episode info */}
<View style={{ marginBottom: 24 }}>
<Text
style={{
color: "white",
fontSize: 28,
fontWeight: "700",
textAlign: "center",
}}
>
{truncateTitle(currentItem.Name || "Unknown", 50)}
</Text>
{currentItem.SeriesName && (
<Text
style={{
color: "#999",
fontSize: 16,
textAlign: "center",
marginTop: 8,
}}
>
{currentItem.SeriesName}
{currentItem.ParentIndexNumber &&
currentItem.IndexNumber &&
` • S${currentItem.ParentIndexNumber}:E${currentItem.IndexNumber}`}
</Text>
)}
</View>
{/* Poster with buffering overlay */}
<View
style={{
alignItems: "center",
marginBottom: 32,
}}
>
<View
style={{
width: 300,
height: 450,
borderRadius: 12,
overflow: "hidden",
position: "relative",
}}
>
{posterUrl ? (
<Image
source={{ uri: posterUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
/>
) : (
<View
style={{
width: "100%",
height: "100%",
backgroundColor: "#1a1a1a",
justifyContent: "center",
alignItems: "center",
}}
>
<Ionicons name='film-outline' size={64} color='#333' />
</View>
)}
{/* Buffering overlay */}
{isBuffering && (
<View
style={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,0.7)",
justifyContent: "center",
alignItems: "center",
backdropFilter: "blur(10px)",
}}
>
<ActivityIndicator size='large' color={protocolColor} />
<Text
style={{
color: "white",
fontSize: 16,
marginTop: 16,
}}
>
Buffering...
</Text>
</View>
)}
</View>
</View>
{/* Device info */}
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 8,
marginBottom: 32,
}}
>
<Ionicons name={protocolIcon} size={20} color={protocolColor} />
<Text style={{ color: protocolColor, fontSize: 15 }}>
{currentDevice?.name || protocolName}
</Text>
</View>
{/* Progress slider */}
<View style={{ marginBottom: 12 }}>
<View
style={{
height: 4,
backgroundColor: "#333",
borderRadius: 2,
overflow: "hidden",
}}
>
<View
style={{
height: "100%",
width: `${progressPercent}%`,
backgroundColor: protocolColor,
}}
/>
</View>
</View>
{/* Time display */}
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
marginBottom: 32,
}}
>
<Text style={{ color: "#999", fontSize: 13 }}>
{formatTime(progress)}
</Text>
<Text style={{ color: "#999", fontSize: 13 }}>
Ending at {calculateEndingTime(progress, duration)}
</Text>
<Text style={{ color: "#999", fontSize: 13 }}>
{formatTime(duration)}
</Text>
</View>
{/* Segment skip button (intro/credits) */}
{currentSegment && (
<View style={{ marginBottom: 24, alignItems: "center" }}>
<Pressable
onPress={() => {
if (currentSegment.type === "intro") {
skipIntro(null as any); // TODO: Get RemoteMediaClient from useCasting
} else if (currentSegment.type === "credits") {
skipCredits(null as any);
} else {
skipSegment(null as any);
}
}}
style={{
backgroundColor: protocolColor,
paddingHorizontal: 24,
paddingVertical: 12,
borderRadius: 8,
flexDirection: "row",
alignItems: "center",
gap: 8,
}}
>
<Ionicons name='play-skip-forward' size={20} color='white' />
<Text
style={{ color: "white", fontSize: 16, fontWeight: "600" }}
>
Skip{" "}
{currentSegment.type.charAt(0).toUpperCase() +
currentSegment.type.slice(1)}
</Text>
</Pressable>
</View>
)}
{/* Next episode countdown */}
{showNextEpisode && (
<View style={{ marginBottom: 24, alignItems: "center" }}>
<View
style={{
backgroundColor: "#1a1a1a",
paddingHorizontal: 20,
paddingVertical: 12,
borderRadius: 8,
flexDirection: "row",
alignItems: "center",
gap: 12,
}}
>
<ActivityIndicator size='small' color={protocolColor} />
<View>
<Text
style={{ color: "white", fontSize: 14, fontWeight: "600" }}
>
Next Episode Starting Soon
</Text>
<Text style={{ color: "#999", fontSize: 12, marginTop: 2 }}>
{Math.ceil((duration - progress) / 1000)}s remaining
</Text>
</View>
<Pressable
onPress={() => {
// TODO: Cancel auto-play
}}
style={{ marginLeft: 8 }}
>
<Ionicons name='close-circle' size={24} color='#999' />
</Pressable>
</View>
</View>
)}
{/* Playback controls */}
<View
style={{
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
gap: 32,
marginBottom: 48,
}}
>
{/* Rewind 10s */}
<Pressable onPress={() => skipBackward(10)} style={{ padding: 16 }}>
<Ionicons name='play-back' size={32} color='white' />
</Pressable>
{/* Play/Pause */}
<Pressable
onPress={togglePlayPause}
style={{
width: 72,
height: 72,
borderRadius: 36,
backgroundColor: protocolColor,
justifyContent: "center",
alignItems: "center",
}}
>
<Ionicons
name={isPlaying ? "pause" : "play"}
size={36}
color='white'
style={{ marginLeft: isPlaying ? 0 : 4 }}
/>
</Pressable>
{/* Forward 10s */}
<Pressable onPress={() => skipForward(10)} style={{ padding: 16 }}>
<Ionicons name='play-forward' size={32} color='white' />
</Pressable>
</View>
{/* Stop casting button */}
<Pressable
onPress={stop}
style={{
backgroundColor: "#1a1a1a",
padding: 16,
borderRadius: 12,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
gap: 8,
marginBottom: 16,
}}
>
<Ionicons name='stop-circle-outline' size={20} color='#FF3B30' />
<Text style={{ color: "#FF3B30", fontSize: 16, fontWeight: "600" }}>
Stop Casting
</Text>
</Pressable>
{/* Episode list button (for TV shows) */}
{currentItem.Type === "Episode" && (
<Pressable
onPress={() => setShowEpisodeList(true)}
style={{
backgroundColor: "#1a1a1a",
padding: 16,
borderRadius: 12,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
gap: 8,
marginBottom: 24,
}}
>
<Ionicons name='list' size={20} color='white' />
<Text style={{ color: "white", fontSize: 16, fontWeight: "600" }}>
Episodes
</Text>
</Pressable>
)}
</ScrollView>
{/* Modals */}
<ChromecastDeviceSheet
visible={showDeviceSheet && protocol === "chromecast"}
onClose={() => setShowDeviceSheet(false)}
device={
currentDevice && protocol === "chromecast"
? ({
deviceId: currentDevice.id,
friendlyName: currentDevice.name,
} as any)
: null
}
onDisconnect={stop}
volume={volume}
onVolumeChange={async (vol) => setVolume(vol)}
/>
<ChromecastEpisodeList
visible={showEpisodeList}
onClose={() => setShowEpisodeList(false)}
currentItem={currentItem}
episodes={[]} // TODO: Fetch episodes from series
onSelectEpisode={(episode) => {
// TODO: Load new episode
console.log("Selected episode:", episode.Name);
}}
/>
<ChromecastSettingsMenu
visible={showSettings}
onClose={() => setShowSettings(false)}
item={currentItem}
mediaSources={[]} // TODO: Get from media source selector
selectedMediaSource={null}
onMediaSourceChange={(source) => {
// TODO: Change quality
console.log("Changed media source:", source);
}}
audioTracks={[]} // TODO: Get from player
selectedAudioTrack={null}
onAudioTrackChange={(track) => {
// TODO: Change audio track
console.log("Changed audio track:", track);
}}
subtitleTracks={[]} // TODO: Get from player
selectedSubtitleTrack={null}
onSubtitleTrackChange={(track) => {
// TODO: Change subtitle track
console.log("Changed subtitle track:", track);
}}
playbackSpeed={1.0}
onPlaybackSpeedChange={(speed) => {
// TODO: Change playback speed
console.log("Changed playback speed:", speed);
}}
showTechnicalInfo={false}
onToggleTechnicalInfo={() => {
// TODO: Toggle technical info
}}
/>
</Animated.View>
</GestureDetector>
);
}