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