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