Open History to see the last commit
1import { useEvent } from "expo";
2import { useVideoPlayer, VideoView } from "expo-video";
3import { useIsFocused } from "@react-navigation/native";
4import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
5import { 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 { fitVideoFrame } from "../lib/videoFrameFit";
13import { loadVideoThumbnail } from "../lib/videoThumbnails";
14import { type MediaActionsSource } from "../lib/mediaActionsSource";
15import { useMediaVideoPlayback } from "../lib/useMediaVideoPlayback";
16import { MediaActionsMenu } from "./MediaActionsMenu";
17import { createAudioPlaybackSession } from "../lib/audioSession";
18
19function LoadedMediaVideo(props: {
20 readonly uri: string;
21 readonly resolvePlaybackUri?: () => Promise<string | null>;
22 readonly playRequested: boolean;
23 readonly paused: boolean;
24 readonly visible: boolean;
25 readonly onPlaybackStart?: () => void;
26}) {
27 const [attempt, setAttempt] = useState(0);
28 // Expo's Android player also reports completed playback as idle.
29 const [loadState, setLoadState] = useState<"pending" | "complete" | "error">("pending");
30 const player = useVideoPlayer(null, (player) => {
31 player.staysActiveInBackground = false;
32 player.bufferOptions = { preferredForwardBufferDuration: 5 };
33 });
34 const playback = createAudioPlaybackSession(player, true);
35 const { active, fullscreen, createPlayRequest, onFullscreenEnter, onFullscreenExit } =
36 useMediaVideoPlayback(player, props, playback);
37 const previousPlaybackRequested = useRef(false);
38 const onPlaybackStart = useEffectEvent(() => props.onPlaybackStart?.());
39 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to native video player events to keep the shared audio session in step
40 useEffect(() => {
41 const subscription = player.addListener("playingChange", ({ isPlaying }) => {
42 if (isPlaying && !active.current && !fullscreen.current) playback.pause();
43 else playback.playingChanged(isPlaying);
44 });
45 const requested = player.addListener("playbackRequestedChange", ({ isPlaybackRequested }) => {
46 const wasPlaybackRequested = previousPlaybackRequested.current;
47 previousPlaybackRequested.current = isPlaybackRequested;
48 if (!isPlaybackRequested) {
49 if (playback.requested) playback.pause();
50 } else if (!active.current && !fullscreen.current) playback.pause();
51 else {
52 if (!wasPlaybackRequested) onPlaybackStart();
53 playback.playingChanged(true);
54 }
55 });
56 const ended = player.addListener("playToEnd", () => playback.pause());
57 const failed = player.addListener("statusChange", ({ status }) => {
58 if (status === "error") playback.pause();
59 });
60 return () => {
61 subscription.remove();
62 requested.remove();
63 ended.remove();
64 failed.remove();
65 playback.pause();
66 previousPlaybackRequested.current = false;
67 };
68 }, [active, fullscreen, player, playback]);
69 const { status } = useEvent(player, "statusChange", { status: player.status });
70 const loadSource = useEffectEvent(async (signal: AbortSignal) => {
71 const playIfUninterrupted = createPlayRequest();
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) await playIfUninterrupted();
79 });
80
81 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the video source into the native player and aborts the load on cleanup
82 useEffect(() => {
83 const controller = new AbortController();
84 // oxlint-disable-next-line react/set-state-in-effect -- Starting a native media load publishes pending before its async result.
85 setLoadState("pending");
86 // A renewed signature is used on Retry, not as a reason to reset the native player.
87 void loadSource(controller.signal).then(
88 () => {
89 if (!controller.signal.aborted) setLoadState("complete");
90 },
91 () => {
92 if (!controller.signal.aborted) setLoadState("error");
93 },
94 );
95 return () => controller.abort();
96 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A play request or Retry (attempt) reloads the source into the same player.
97 }, [player, props.playRequested, attempt]);
98
99 return (
100 <View collapsable={false} style={{ flex: 1 }}>
101 <VideoView
102 player={player}
103 style={{ width: "100%", height: "100%" }}
104 surfaceType="textureView"
105 nativeControls
106 contentFit="contain"
107 fullscreenOptions={{ enable: true }}
108 onFullscreenEnter={onFullscreenEnter}
109 onFullscreenExit={onFullscreenExit}
110 allowsPictureInPicture={false}
111 />
112 {loadState === "error" || (loadState === "complete" && status === "error") ? (
113 <View className="absolute inset-0 items-center justify-center gap-2 bg-black px-4">
114 <AppText className="text-center text-sm text-white/80">Video unavailable</AppText>
115 <Pressable
116 accessibilityRole="button"
117 accessibilityLabel="Retry video"
118 onPress={() => setAttempt((value) => value + 1)}
119 className="min-h-11 justify-center px-4"
120 >
121 <AppText className="text-sm text-white">Retry</AppText>
122 </Pressable>
123 </View>
124 ) : loadState === "pending" || status === "loading" ? (
125 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
126 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
127 </View>
128 ) : null}
129 </View>
130 );
131}
132
133interface MediaVideoPlayerProps {
134 readonly uri: string | null;
135 readonly resolvePlaybackUri?: () => Promise<string | null>;
136 readonly name: string;
137 readonly thumbnailKey: string;
138 readonly thumbnailVisible?: boolean;
139 readonly visible?: boolean;
140 readonly unavailable?: boolean;
141 readonly unavailableDetail?: string | undefined;
142 readonly expanded?: boolean;
143 /** Fill the parent and size the frame to the video's shape instead of a fixed 16:9 slot. */
144 readonly fitToVideo?: boolean;
145 readonly autoPlay?: boolean;
146 readonly paused?: boolean;
147 readonly onPlaybackStart?: () => void;
148 readonly actionsSource?: MediaActionsSource;
149 readonly borderRadius?: number;
150}
151
152function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
153 const mediaActions = useMediaActions(props.actionsSource);
154 const isFocused = useIsFocused();
155 const [playbackUri, setPlaybackUri] = useState<string | null>(props.expanded ? props.uri : null);
156 // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL.
157 if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri);
158 const unavailableText = props.unavailableDetail
159 ? `Video unavailable. ${props.unavailableDetail}`
160 : "Video unavailable";
161 const [videoSize, setVideoSize] = useState<{ width: number; height: number } | null>(null);
162 const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null);
163 const sizeSource = props.fitToVideo && isFocused && videoSize === null ? props.uri : null;
164 // Queue before the poster so early Play cannot cancel the extraction that supplies frame dimensions.
165 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads native thumbnail dimensions independently of the poster's lifetime
166 useLayoutEffect(() => {
167 if (sizeSource === null) return;
168 // Thumbnails are oriented like the displayed frame, unlike VideoTrack.size.
169 const controller = new AbortController();
170 void loadVideoThumbnail(
171 props.thumbnailKey,
172 async () => ({ uri: sizeSource, dispose: () => undefined }),
173 controller.signal,
174 ).then((thumbnail) => {
175 if (thumbnail && !controller.signal.aborted) {
176 setVideoSize({ width: thumbnail.width, height: thumbnail.height });
177 }
178 });
179 return () => controller.abort();
180 }, [props.thumbnailKey, sizeSource]);
181 const fittedFrame =
182 props.fitToVideo && videoSize && bounds ? fitVideoFrame(videoSize, bounds, 480) : null;
183
184 const frame = (
185 <View
186 collapsable={false}
187 className="overflow-hidden rounded-[10px] bg-black"
188 style={[
189 props.expanded
190 ? { flex: 1 }
191 : (fittedFrame ?? { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }),
192 props.borderRadius === undefined ? null : { borderRadius: props.borderRadius },
193 ]}
194 >
195 {playbackUri ? (
196 <LoadedMediaVideo
197 uri={props.uri ?? playbackUri}
198 resolvePlaybackUri={props.resolvePlaybackUri}
199 playRequested={!props.expanded || props.autoPlay === true}
200 paused={(props.paused ?? false) || mediaActions.sharing}
201 visible={props.visible ?? true}
202 onPlaybackStart={props.onPlaybackStart}
203 />
204 ) : (
205 <MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
206 <Pressable
207 accessibilityRole="button"
208 accessibilityLabel={
209 props.unavailable ? `${props.name}. ${unavailableText}` : `Play ${props.name}`
210 }
211 accessibilityHint={
212 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
213 }
214 accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
215 // Stays pressable so the long-press menu still opens on a failed or unsigned tile.
216 onPress={() => {
217 if (props.uri !== null && !props.unavailable) {
218 props.onPlaybackStart?.();
219 setPlaybackUri(props.uri);
220 }
221 }}
222 className="flex-1 items-center justify-center px-4"
223 >
224 {!props.unavailable ? (
225 <VideoThumbnailImage
226 cacheKey={props.thumbnailKey}
227 source={props.thumbnailVisible === false ? null : props.uri}
228 contentFit="contain"
229 />
230 ) : null}
231 {props.unavailable ? (
232 <AppText className="text-center text-sm text-white/80">{unavailableText}</AppText>
233 ) : props.uri === null ? (
234 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
235 ) : (
236 <View className="size-12 items-center justify-center rounded-full bg-black/60">
237 <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
238 </View>
239 )}
240 {props.uri !== null && !props.unavailable ? (
241 <AppText
242 className="absolute right-2 bottom-2 max-w-[75%] rounded bg-black/60 px-2 py-1 text-right text-xs text-white"
243 numberOfLines={1}
244 >
245 {props.name}
246 </AppText>
247 ) : null}
248 </Pressable>
249 </MediaActionsMenu>
250 )}
251 </View>
252 );
253 if (!props.fitToVideo) return frame;
254 return (
255 <View
256 className="flex-1 items-center justify-center self-stretch"
257 onLayout={(event) => {
258 const { width, height } = event.nativeEvent.layout;
259 setBounds({ width, height });
260 }}
261 >
262 {frame}
263 </View>
264 );
265}
266
267export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
268 return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;
269}