Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MediaVideoPlayer.tsx

230 lines9.6 KB

1import { useIsFocused } from "@react-navigation/native";
2import { useEvent } from "expo";
3import { useVideoPlayer, VideoView } from "expo-video";
4import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
5import { AppState, Pressable, View } from "react-native";
6​
7import { AppActivityIndicator } from "./ui/AppActivityIndicator";
8import { AppText } from "./ui/AppText";
9import { SymbolView } from "./ui/AppSymbol";
10import { VideoThumbnailImage } from "./VideoThumbnailImage";
11import { useMediaActions } from "../state/mediaActions";
12import { type MediaActionsSource } from "../lib/mediaActionsSource";
13import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession";
14import { MediaActionsMenu } from "./MediaActionsMenu";
15import { createAudioPlaybackSession } from "../lib/audioSession";
16​
17function LoadedMediaVideo(props: {
18 readonly uri: string;
19 readonly resolvePlaybackUri?: () => Promise<string | null>;
20 readonly playRequested: boolean;
21 readonly paused: boolean;
22 readonly onPlaybackStart?: () => void;
23}) {
24 const focused = useIsFocused();
25 const fullscreenVideoOpen = useFullscreenVideoOpen();
26 const paused = props.paused || fullscreenVideoOpen;
27 const active = useRef(focused && AppState.currentState === "active");
28 const fullscreen = useRef(false);
29 const [attempt, setAttempt] = useState(0);
30 // Expo's Android player also reports completed playback as idle.
31 const [loadState, setLoadState] = useState<"pending" | "complete" | "error">("pending");
32 const player = useVideoPlayer(null, (player) => {
33 player.staysActiveInBackground = false;
34 player.bufferOptions = { preferredForwardBufferDuration: 5 };
35 });
36 const playback = useMemo(() => createAudioPlaybackSession(player, true), [player]);
37 const previousPlaybackRequested = useRef(false);
38 const onPlaybackStart = useEffectEvent(() => props.onPlaybackStart?.());
39 useEffect(() => {
40 const subscription = player.addListener("playingChange", ({ isPlaying }) => {
41 if (isPlaying && !active.current && !fullscreen.current) playback.pause();
42 else playback.playingChanged(isPlaying);
43 });
44 const requested = player.addListener("playbackRequestedChange", ({ isPlaybackRequested }) => {
45 const wasPlaybackRequested = previousPlaybackRequested.current;
46 previousPlaybackRequested.current = isPlaybackRequested;
47 if (!isPlaybackRequested) {
48 if (playback.requested) playback.pause();
49 } else if (!active.current && !fullscreen.current) playback.pause();
50 else {
51 if (!wasPlaybackRequested) onPlaybackStart();
52 playback.playingChanged(true);
53 }
54 });
55 const ended = player.addListener("playToEnd", () => playback.pause());
56 const failed = player.addListener("statusChange", ({ status }) => {
57 if (status === "error") playback.pause();
58 });
59 return () => {
60 subscription.remove();
61 requested.remove();
62 ended.remove();
63 failed.remove();
64 playback.pause();
65 previousPlaybackRequested.current = false;
66 };
67 }, [player, playback]);
68 const { status } = useEvent(player, "statusChange", { status: player.status });
69 const { isPlaying } = useEvent(player, "playingChange", { isPlaying: player.playing });
70 useMediaAudioSessionHold(isPlaying);
71 const loadSource = useEffectEvent(async (signal: AbortSignal) => {
72 const uri = props.resolvePlaybackUri ? await props.resolvePlaybackUri() : props.uri;
73 if (signal.aborted) return;
74 if (uri === null) throw new Error("Video unavailable");
75 playback.pause();
76 previousPlaybackRequested.current = false;
77 await player.replaceAsync({ uri, contentType: "progressive" });
78 if (!signal.aborted && props.playRequested && active.current) await playback.play();
79 });
80​
81 useEffect(() => {
82 active.current = focused && !paused && AppState.currentState === "active";
83 if (!focused || paused || (!active.current && !fullscreen.current)) playback.pause();
84 // RN reports both leaving the app and Android fullscreen as background; native handling distinguishes them.
85 const subscription = AppState.addEventListener("change", (state) => {
86 active.current = focused && !paused && state === "active";
87 if (state === "inactive" || (state === "background" && !fullscreen.current)) playback.pause();
88 });
89 return () => subscription.remove();
90 }, [focused, playback, paused]);
91​
92 useEffect(() => {
93 const controller = new AbortController();
94 setLoadState("pending");
95 // A renewed signature is used on Retry, not as a reason to reset the native player.
96 void loadSource(controller.signal).then(
97 () => {
98 if (!controller.signal.aborted) setLoadState("complete");
99 },
100 () => {
101 if (!controller.signal.aborted) setLoadState("error");
102 },
103 );
104 return () => controller.abort();
105 }, [player, props.playRequested, attempt]);
106​
107 return (
108 <View collapsable={false} style={{ flex: 1 }}>
109 <VideoView
110 player={player}
111 style={{ width: "100%", height: "100%" }}
112 surfaceType="textureView"
113 nativeControls
114 contentFit="contain"
115 fullscreenOptions={{ enable: true }}
116 onFullscreenEnter={() => {
117 fullscreen.current = true;
118 }}
119 onFullscreenExit={() => {
120 fullscreen.current = false;
121 }}
122 allowsPictureInPicture={false}
123 />
124 {loadState === "error" || (loadState === "complete" && status === "error") ? (
125 <View className="absolute inset-0 items-center justify-center gap-2 bg-black px-4">
126 <AppText className="text-center text-sm text-white/80">Video unavailable</AppText>
127 <Pressable
128 accessibilityRole="button"
129 accessibilityLabel="Retry video"
130 onPress={() => setAttempt((value) => value + 1)}
131 className="min-h-11 justify-center px-4"
132 >
133 <AppText className="text-sm text-white">Retry</AppText>
134 </Pressable>
135 </View>
136 ) : loadState === "pending" || status === "loading" ? (
137 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
138 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
139 </View>
140 ) : null}
141 </View>
142 );
144​
145interface MediaVideoPlayerProps {
146 readonly uri: string | null;
147 readonly resolvePlaybackUri?: () => Promise<string | null>;
148 readonly name: string;
149 readonly thumbnailKey: string;
150 readonly thumbnailVisible?: boolean;
151 readonly unavailable?: boolean;
152 readonly expanded?: boolean;
153 readonly autoPlay?: boolean;
154 readonly paused?: boolean;
155 readonly onPlaybackStart?: () => void;
156 readonly actionsSource?: MediaActionsSource;
158​
159function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
160 const mediaActions = useMediaActions(props.actionsSource);
161 const [playbackUri, setPlaybackUri] = useState<string | null>(props.expanded ? props.uri : null);
162 // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL.
163 if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri);
164​
165 return (
166 <View
167 collapsable={false}
168 className="overflow-hidden rounded-[10px] bg-black"
169 style={props.expanded ? { flex: 1 } : { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }}
170 >
171 {playbackUri ? (
172 <LoadedMediaVideo
173 uri={props.uri ?? playbackUri}
174 resolvePlaybackUri={props.resolvePlaybackUri}
175 playRequested={!props.expanded || props.autoPlay === true}
176 paused={(props.paused ?? false) || mediaActions.sharing}
177 onPlaybackStart={props.onPlaybackStart}
178 />
179 ) : (
180 <MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
181 <Pressable
182 accessibilityRole="button"
183 accessibilityLabel={`Play ${props.name}`}
184 accessibilityHint={
185 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
186 }
187 accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
188 // Stays pressable so the long-press menu still opens on a failed or unsigned tile.
189 onPress={() => {
190 if (props.uri !== null && !props.unavailable) {
191 props.onPlaybackStart?.();
192 setPlaybackUri(props.uri);
193 }
194 }}
195 className="flex-1 items-center justify-center px-4"
196 >
197 {!props.unavailable ? (
198 <VideoThumbnailImage
199 cacheKey={props.thumbnailKey}
200 source={props.thumbnailVisible === false ? null : props.uri}
201 contentFit="contain"
202 />
203 ) : null}
204 {props.unavailable ? (
205 <AppText className="text-sm text-white/80">Video unavailable</AppText>
206 ) : props.uri === null ? (
207 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
208 ) : (
209 <View className="size-12 items-center justify-center rounded-full bg-black/60">
210 <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
211 </View>
212 )}
213 {props.uri !== null && !props.unavailable ? (
214 <AppText
215 className="absolute right-2 bottom-2 max-w-[75%] rounded bg-black/60 px-2 py-1 text-right text-xs text-white"
216 numberOfLines={1}
217 >
218 {props.name}
219 </AppText>
220 ) : null}
221 </Pressable>
222 </MediaActionsMenu>
223 )}
224 </View>
225 );
227​
228export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
229 return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;