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 expanded?: boolean;
142 /** Fill the parent and size the frame to the video's shape instead of a fixed 16:9 slot. */
143 readonly fitToVideo?: boolean;
144 readonly autoPlay?: boolean;
145 readonly paused?: boolean;
146 readonly onPlaybackStart?: () => void;
147 readonly actionsSource?: MediaActionsSource;
148 readonly borderRadius?: number;
149}
150
151function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
152 const mediaActions = useMediaActions(props.actionsSource);
153 const isFocused = useIsFocused();
154 const [playbackUri, setPlaybackUri] = useState<string | null>(props.expanded ? props.uri : null);
155 // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL.
156 if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri);
157 const [videoSize, setVideoSize] = useState<{ width: number; height: number } | null>(null);
158 const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null);
159 const sizeSource = props.fitToVideo && isFocused && videoSize === null ? props.uri : null;
160 // Queue before the poster so early Play cannot cancel the extraction that supplies frame dimensions.
161 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads native thumbnail dimensions independently of the poster's lifetime
162 useLayoutEffect(() => {
163 if (sizeSource === null) return;
164 // Thumbnails are oriented like the displayed frame, unlike VideoTrack.size.
165 const controller = new AbortController();
166 void loadVideoThumbnail(
167 props.thumbnailKey,
168 async () => ({ uri: sizeSource, dispose: () => undefined }),
169 controller.signal,
170 ).then((thumbnail) => {
171 if (thumbnail && !controller.signal.aborted) {
172 setVideoSize({ width: thumbnail.width, height: thumbnail.height });
173 }
174 });
175 return () => controller.abort();
176 }, [props.thumbnailKey, sizeSource]);
177 const fittedFrame =
178 props.fitToVideo && videoSize && bounds ? fitVideoFrame(videoSize, bounds, 480) : null;
179
180 const frame = (
181 <View
182 collapsable={false}
183 className="overflow-hidden rounded-[10px] bg-black"
184 style={[
185 props.expanded
186 ? { flex: 1 }
187 : (fittedFrame ?? { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }),
188 props.borderRadius === undefined ? null : { borderRadius: props.borderRadius },
189 ]}
190 >
191 {playbackUri ? (
192 <LoadedMediaVideo
193 uri={props.uri ?? playbackUri}
194 resolvePlaybackUri={props.resolvePlaybackUri}
195 playRequested={!props.expanded || props.autoPlay === true}
196 paused={(props.paused ?? false) || mediaActions.sharing}
197 visible={props.visible ?? true}
198 onPlaybackStart={props.onPlaybackStart}
199 />
200 ) : (
201 <MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
202 <Pressable
203 accessibilityRole="button"
204 accessibilityLabel={`Play ${props.name}`}
205 accessibilityHint={
206 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
207 }
208 accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
209 // Stays pressable so the long-press menu still opens on a failed or unsigned tile.
210 onPress={() => {
211 if (props.uri !== null && !props.unavailable) {
212 props.onPlaybackStart?.();
213 setPlaybackUri(props.uri);
214 }
215 }}
216 className="flex-1 items-center justify-center px-4"
217 >
218 {!props.unavailable ? (
219 <VideoThumbnailImage
220 cacheKey={props.thumbnailKey}
221 source={props.thumbnailVisible === false ? null : props.uri}
222 contentFit="contain"
223 />
224 ) : null}
225 {props.unavailable ? (
226 <AppText className="text-sm text-white/80">Video unavailable</AppText>
227 ) : props.uri === null ? (
228 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
229 ) : (
230 <View className="size-12 items-center justify-center rounded-full bg-black/60">
231 <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
232 </View>
233 )}
234 {props.uri !== null && !props.unavailable ? (
235 <AppText
236 className="absolute right-2 bottom-2 max-w-[75%] rounded bg-black/60 px-2 py-1 text-right text-xs text-white"
237 numberOfLines={1}
238 >
239 {props.name}
240 </AppText>
241 ) : null}
242 </Pressable>
243 </MediaActionsMenu>
244 )}
245 </View>
246 );
247 if (!props.fitToVideo) return frame;
248 return (
249 <View
250 className="flex-1 items-center justify-center self-stretch"
251 onLayout={(event) => {
252 const { width, height } = event.nativeEvent.layout;
253 setBounds({ width, height });
254 }}
255 >
256 {frame}
257 </View>
258 );
259}
260
261export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
262 return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;
263}