Open the web build of a React Native video player on an iPhone and tap fullscreen. Your controls vanish and Safari's take over, because an iPhone will only put the <video> element itself fullscreen. You can't stop that, but the player can find out before the tap and hide its own fullscreen button.
A DASH stream that plays fine on Android shows nothing on iOS, where Expo Video doesn't play DASH at all. A feed that autoplays in a browser gets its play() refused, and a player that flipped its icon on the tap now shows pause over a video that never started.
So my player waits for the engine to report before it changes a button, on all three platforms, with one set of controls.
Expo Video on the phone, the video element on the web
Every platform shares the source model, the commands (play, pause, seek, mute, fullscreen and Picture in Picture), the names for what the player is doing and the control layout.
Under them, iOS and Android run Expo Video, which wraps AVPlayer on iOS and Media3's ExoPlayer on Android. In the browser it's the HTML <video> element, with hls.js attached when a stream needs it.
- ControlsControlBar and ProgressSliderShared
- State and contractplayerReducer.ts and types.tsShared
- SurfaceVideoSurface.tsxSwapped
- EngineExpo Video: AVPlayer on iOS, Media3 ExoPlayer on AndroidSwapped
- Streams
- Files and HLS on both. DASH plays on Android only, so iOS needs an HLS rendition.
- Fullscreen
- enterFullscreen() on the VideoView.
- Picture in Picture
- startPictureInPicture(), once supportsPictureInPicture is in the config plugin. Starting on its own as the app leaves works on iOS, and on Android 12 or later.
The types the controls see
The public types only cover what the controls need. Never hand the controls a whole native player or a DOM element: the first time one of them reads video.paused directly, the abstraction is gone.
export type VideoSource = {
kind: "file" | "hls" | "dash";
title: string;
uri: string;
};
export type Capabilities = {
fullscreen: boolean;
pictureInPicture: boolean;
};
export type PlaybackSnapshot = {
capabilities: Capabilities;
duration: number;
error?: string;
phase: "loading" | "buffering" | "playing" | "paused" | "ended" | "error";
position: number;
};
export type PlaybackAction =
| { type: "LOAD" }
| { capabilities: Capabilities; duration: number; type: "READY" }
| { position: number; type: "PLAY" }
| { type: "WAIT" }
| { position: number; type: "PAUSE" }
| { position: number; type: "TIME" }
| { type: "END" }
| { message: string; type: "FAIL" };
export type VideoSurfaceHandle = {
pause: () => void;
play: () => Promise<void>;
requestFullscreen: () => Promise<void>;
requestPictureInPicture: () => Promise<void>;
seekTo: (seconds: number) => void;
setMuted: (muted: boolean) => void;
};The controls call the handle; the surface reports back with PlaybackActions, which a reducer turns into the snapshot. Capabilities come back with READY, since some of them aren't known until the metadata has loaded.
These types assume a video with an end. A live stream reports a duration of Infinity in the browser and sets isLive in Expo Video, and both the slider and END need a finite number, so live would need a flag of its own on READY.
Captions aren't in this contract either. The browser reads a WebVTT file as a <track>, while Expo Video chooses among the subtitle tracks the stream already carries (availableSubtitleTracks and subtitleTrack).
Let Metro choose the engine
With platform-specific files, the web bundle never imports expo-video and the native bundle never imports hls.js. In an Expo app, Metro picks a .web.tsx file for the browser build and the plain .tsx file everywhere else:
video-player/
UniversalVideoPlayer.tsx
VideoSurface.tsx
VideoSurface.web.tsx
attachSource.web.ts
fullscreen.web.ts
mediaCoordinator.ts
playerReducer.ts
types.ts
controls/
ControlBar.tsx
ProgressSlider.tsxUniversalVideoPlayer imports VideoSurface and never learns which one it got. It owns the reducer and hands its dispatch to the surface as onEvent:
export function UniversalVideoPlayer({ source }: { source: VideoSource }) {
const surface = useRef<VideoSurfaceHandle>(null);
const [snapshot, dispatch] = useReducer(playerReducer, initialSnapshot);
const [attempt, setAttempt] = useState(0);
const play = () => {
// A refused play() leaves the phase paused, and the play button that
// still shows is the tap the browser is waiting for.
surface.current?.play().catch(() => {});
};
const retry = () => {
dispatch({ type: "LOAD" });
setAttempt((count) => count + 1);
};
return (
<View style={{ aspectRatio: 16 / 9 }}>
<VideoSurface
key={attempt}
onEvent={dispatch}
ref={surface}
source={source}
/>
<ControlBar
onPlay={play}
onRetry={retry}
snapshot={snapshot}
surface={surface}
/>
</View>
);
}dispatch never changes identity, so a surface can list it as an effect's dependency without that effect running again on every render.
"Try again" has no command of its own. A new key remounts the surface, which throws away the failed engine (and the hls.js instance with it) and builds a fresh one, and LOAD is the one action that clears an error.
On iOS and Android, Expo Video
timeUpdate never fires until you set timeUpdateEventInterval, because it defaults to 0. And contentType: "dash" only works on Android: Expo Video's docs mark DASH and Smooth Streaming as Android-only, so the iOS build needs an HLS rendition of the same video.
import { useEventListener } from "expo";
import {
isPictureInPictureSupported,
useVideoPlayer,
VideoView,
} from "expo-video";
import { useImperativeHandle, useRef, type Ref } from "react";
import type { PlaybackAction, VideoSource, VideoSurfaceHandle } from "./types";
type NativeVideoSurfaceProps = {
onEvent: (action: PlaybackAction) => void;
ref?: Ref<VideoSurfaceHandle>;
source: VideoSource;
};
export function VideoSurface({ onEvent, ref, source }: NativeVideoSurfaceProps) {
const viewRef = useRef<VideoView>(null);
const player = useVideoPlayer(
{
contentType: source.kind === "file" ? "progressive" : source.kind,
metadata: { title: source.title },
uri: source.uri,
},
(player) => {
player.timeUpdateEventInterval = 0.25;
}
);
useEventListener(player, "sourceChange", () => {
onEvent({ type: "LOAD" });
});
useEventListener(player, "sourceLoad", ({ duration }) => {
onEvent({
capabilities: {
fullscreen: true,
pictureInPicture: isPictureInPictureSupported(),
},
duration,
type: "READY",
});
});
useEventListener(player, "playingChange", ({ isPlaying }) => {
const position = player.currentTime;
if (isPlaying) {
onEvent({ position, type: "PLAY" });
} else if (player.status !== "loading") {
// A stall turns playing off too, after the status has gone to
// loading, and statusChange has already reported it as WAIT.
onEvent({ position, type: "PAUSE" });
}
});
useEventListener(player, "timeUpdate", ({ currentTime }) => {
onEvent({ position: currentTime, type: "TIME" });
});
useEventListener(player, "playToEnd", () => {
onEvent({ type: "END" });
});
useEventListener(player, "statusChange", ({ error, status }) => {
if (status === "loading") {
onEvent({ type: "WAIT" });
} else if (status === "readyToPlay" && player.playing) {
onEvent({ position: player.currentTime, type: "PLAY" });
} else if (status === "error") {
onEvent({ message: error?.message ?? "Playback failed", type: "FAIL" });
}
});
useImperativeHandle(
ref,
() => ({
pause: () => {
player.pause();
// During a stall playing is already false, so this pause fires no
// playingChange; the surface reports it itself.
if (player.status === "loading") {
onEvent({ position: player.currentTime, type: "PAUSE" });
}
},
play: async () => player.play(),
requestFullscreen: async () => {
await viewRef.current?.enterFullscreen();
},
requestPictureInPicture: async () => {
await viewRef.current?.startPictureInPicture();
},
seekTo: (seconds) => {
player.currentTime = seconds;
},
setMuted: (muted) => {
player.muted = muted;
},
}),
[player, onEvent]
);
return (
<VideoView
allowsPictureInPicture
contentFit="contain"
nativeControls={false}
player={player}
ref={viewRef}
style={{ height: "100%", width: "100%" }}
/>
);
}Report PAUSE every time playingChange says false and each stall shows a play button. Expo Video takes playing from AVPlayer's timeControlStatus on iOS and from ExoPlayer's onIsPlayingChanged on Android, and neither counts waiting for data as playing. Both change the status first: Expo Video's iOS observer sets it before playing, and Media3 sends onPlaybackStateChanged before onIsPlayingChanged. So by the time playingChange says false in a stall, player.status already reads loading, and the surface can tell a stall from a pause.
startPictureInPicture() does nothing useful until the app is built for it: set supportsPictureInPicture in Expo Video's config plugin, and supportsBackgroundPlayback too if audio should carry on when the app leaves the screen, which also needs staysActiveInBackground on the player.
In the browser, the video element itself
Expo Video has a web build too, and I don't use it for this. Its web player sets the source straight on a <video> element, so HLS only plays where the browser plays it natively. Its enterFullscreen() also takes the video element fullscreen and leaves the box around it, custom controls and all, behind. So I render the element myself:
import { useEffect, useImperativeHandle, useRef, type Ref } from "react";
import { attachSource } from "./attachSource.web";
import { canFullscreen, enterFullscreen } from "./fullscreen.web";
import type { PlaybackAction, VideoSource, VideoSurfaceHandle } from "./types";
type WebVideoSurfaceProps = {
onEvent: (action: PlaybackAction) => void;
ref?: Ref<VideoSurfaceHandle>;
source: VideoSource;
};
export function VideoSurface({ onEvent, ref, source }: WebVideoSurfaceProps) {
const boxRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const { kind, uri } = source;
// Keyed on the source's fields, so a caller that builds the source
// inline doesn't reattach the stream on every render.
useEffect(() => {
const video = videoRef.current;
if (!video) return;
return attachSource(video, { kind, uri }, (message) => {
onEvent({ message, type: "FAIL" });
});
}, [kind, uri, onEvent]);
useImperativeHandle(
ref,
() => ({
pause: () => videoRef.current?.pause(),
play: async () => {
await videoRef.current?.play();
},
requestFullscreen: () => enterFullscreen(boxRef.current, videoRef.current),
requestPictureInPicture: async () => {
await videoRef.current?.requestPictureInPicture();
},
seekTo: (seconds) => {
if (videoRef.current) videoRef.current.currentTime = seconds;
},
setMuted: (muted) => {
if (videoRef.current) videoRef.current.muted = muted;
},
}),
[]
);
return (
<div ref={boxRef} style={{ height: "100%", width: "100%" }}>
<video
aria-label={source.title}
onEnded={() => onEvent({ type: "END" })}
onError={(event) =>
onEvent({
message: event.currentTarget.error?.message || "Playback failed",
type: "FAIL",
})
}
onLoadStart={() => onEvent({ type: "LOAD" })}
onLoadedMetadata={(event) => {
const video = event.currentTarget;
onEvent({
capabilities: {
fullscreen: canFullscreen(video),
pictureInPicture:
document.pictureInPictureEnabled === true &&
!video.disablePictureInPicture,
},
duration: video.duration,
type: "READY",
});
}}
onPause={(event) =>
onEvent({ position: event.currentTarget.currentTime, type: "PAUSE" })
}
onPlaying={(event) =>
onEvent({ position: event.currentTarget.currentTime, type: "PLAY" })
}
onTimeUpdate={(event) =>
onEvent({ position: event.currentTarget.currentTime, type: "TIME" })
}
onWaiting={() => onEvent({ type: "WAIT" })}
playsInline
preload="metadata"
ref={videoRef}
style={{ height: "100%", objectFit: "contain", width: "100%" }}
/>
</div>
);
}Dispatch PLAY from onPlaying. The play event fires as soon as the element is told to play; playing waits until playback has actually started, or resumed after waiting for data. loadstart fires every time the element begins loading a new resource, whether that's a plain URL or the media source hls.js attaches, so it's the web's LOAD.
For streams, a small adapter decides who loads the source. I follow the order the hls.js README recommends: hls.js first wherever Hls.isSupported() is true, and the browser's own HLS only as a fallback. The README warns that canPlayType() answers "maybe" in Safari, Chrome and possibly other browsers, so a yes from it doesn't promise the stream will play. On iOS 17.1 and later, hls.js runs on Safari's Managed Media Source, so the fallback mostly matters on older iPhones.
The price is AirPlay. MDN's page on ManagedMediaSource says Safari only opens one for an element that either sets disableRemotePlayback or offers an AirPlay alternative, such as an HLS <source>. hls.js takes the first way: its buffer controller sets disableRemotePlayback and removes any <source> children when it attaches. So this player gives up AirPlay wherever hls.js runs in Safari. Keeping it would mean handing Safari the plain HLS URL and skipping hls.js there, which brings back the canPlayType() guess.
import Hls from "hls.js";
import type { VideoSource } from "./types";
export function attachSource(
video: HTMLVideoElement,
source: Pick<VideoSource, "kind" | "uri">,
fail: (message: string) => void
) {
if (source.kind === "dash") {
// No browser plays a DASH manifest by itself, and this player doesn't
// load dash.js until a source needs it.
fail("This player can't play DASH in a browser yet.");
return;
}
if (source.kind === "hls" && Hls.isSupported()) {
const hls = new Hls();
// hls.js reports its failures here, not as the element's error event.
hls.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal) fail(data.details);
});
hls.loadSource(source.uri);
hls.attachMedia(video);
return () => hls.destroy();
}
if (
source.kind === "hls" &&
!video.canPlayType("application/vnd.apple.mpegurl")
) {
fail("This browser can't play HLS.");
return;
}
video.src = source.uri;
return () => {
// Removing the attribute alone doesn't stop the download; load() does.
video.removeAttribute("src");
video.load();
};
}When a manifest 404s or the network drops under hls.js, the <video> element usually stays quiet. Without the ERROR listener the player would sit on loading forever.
preload="metadata" only holds on the plain-file path, too. hls.js starts loading the playlist and the first segments as soon as it has parsed the manifest, unless it's created with autoStartLoad: false and told to startLoad() later.
Let the engine decide when playback started
When a video reaches its end in a browser, the element fires pause and then ended. Expo Video reports playingChange and playToEnd as separate events, and nothing promises that a failure on a phone won't be followed by a playingChange to false. A reducer gives the interface one place to decide what each of those means. With booleans instead of one phase, a replay could leave isPlaying and hasEnded both true unless every handler remembered to clear the other:
import type { PlaybackAction, PlaybackSnapshot } from "./types";
export const initialSnapshot: PlaybackSnapshot = {
capabilities: { fullscreen: false, pictureInPicture: false },
duration: 0,
phase: "loading",
position: 0,
};
export function playerReducer(
state: PlaybackSnapshot,
action: PlaybackAction
): PlaybackSnapshot {
// Only a new load leaves an error, so a pause that follows the failure
// can't hide it.
if (state.phase === "error" && action.type !== "LOAD") return state;
switch (action.type) {
case "LOAD":
return initialSnapshot;
case "READY":
return {
...state,
capabilities: action.capabilities,
duration: action.duration,
phase: "paused",
};
case "PLAY":
return { ...state, phase: "playing", position: action.position };
case "WAIT":
return state.phase === "playing" ? { ...state, phase: "buffering" } : state;
case "PAUSE":
// Whichever of the pause and the end arrives last, the end wins.
if (state.phase === "ended") return state;
return { ...state, phase: "paused", position: action.position };
case "TIME":
return { ...state, position: action.position };
case "END":
return { ...state, phase: "ended", position: state.duration };
case "FAIL":
return { ...state, error: action.message, phase: "error" };
}
}Tapping play calls surface.play(), and the phase moves to playing when the engine reports it, not on the tap.
In a browser, play() returns a promise, and it rejects with a NotAllowedError when the autoplay policy blocks it. A tap counts as permission, so this happens to a feed that autoplays, or to a play() that runs after an await has outlasted the tap's user activation. On a phone, a call can pause the video at any time without anyone touching the screen.
Harbour at dawn
Episode 3, 4 minutes
Phasepaused
- uiload the source
- enginemetadata loaded
- uisurface.play(), to autoplay
When the controls hide
Moving the mouse shows the controls. On a phone it takes a tap on the surface, and from the keyboard it takes focus, with a visible ring and a tab order that follows the bar.
They hide only while the video is playing and the viewer has been idle for a moment, and they stay up while focus is inside the bar, during a scrub, or whenever the video isn't playing. I reset the idle timer in the pointer and key handlers, so a re-render on its own never brings the controls back.
Scrubbing needs two clocks
Bind the thumb to the engine's position and every drag becomes a stream of seeks, while every progress report pulls the thumb back to where the engine still is. The thumb needs a clock of its own that follows the finger while it's held, and the player seeks once, on release.
- Seeks sent
- 0
- Thumb follows
- engine
If the preview disappears on release, the thumb snaps back until the seek lands. So mine keeps the target until the engine reports a position near it. In the browser, that report is the seeked event. Expo Video has no seek event, so on a phone it's the first timeUpdate close to the target. Either way, compare with a tolerance: the engine lands on a keyframe or a segment boundary, and rarely on the exact second the finger let go. In React Native, @react-native-community/slider gives you onValueChange for the preview and onSlidingComplete for the seek.
Show only the buttons the platform supports
The control bar reads snapshot.capabilities and leaves out a button the surface said it can't honour.
On the web, fullscreen belongs to the box around the video, so the controls go with it. MDN's compatibility data marks requestFullscreen() as iPad only on iOS; on an iPhone, Safari will only take the <video> element fullscreen, through its own webkitEnterFullscreen(), with its own controls. Apple's webkitSupportsFullscreen only means something once the metadata has loaded, which is why capabilities arrive with READY:
type AppleVideo = HTMLVideoElement & {
webkitEnterFullscreen?: () => void;
webkitSupportsFullscreen?: boolean;
};
export function canFullscreen(video: AppleVideo) {
return document.fullscreenEnabled || video.webkitSupportsFullscreen === true;
}
export async function enterFullscreen(
box: HTMLElement | null,
video: AppleVideo | null
) {
if (box && document.fullscreenEnabled) {
await box.requestFullscreen();
} else if (video?.webkitSupportsFullscreen && video.webkitEnterFullscreen) {
video.webkitEnterFullscreen();
} else {
throw new Error("Fullscreen isn't available here.");
}
}document.fullscreenEnabled is false inside an iframe that wasn't given allow="fullscreen", and then desktop Chrome has neither path. The button doesn't show, and if something calls it anyway, the promise rejects with an error.
Picture in Picture belongs to the video element. requestPictureInPicture() has to be called from a click or a tap; without one, it rejects with NotAllowedError. On native, Expo Video's isPictureInPictureSupported() answers whether to show the button on iOS and Android, and startsPictureInPictureAutomatically lets the video float when the viewer leaves the app, on iOS and on Android 12 and later.
On native, fullscreen can be enterFullscreen() on the VideoView, a dedicated screen, or a layer above the navigation that reuses the same player. Whichever it is, keep the player instance: a remount on the way into fullscreen can reset the position and throw away the buffer.
More than one player on a screen
A feed can leave several players mounted at once, and two autoplaying cards play their audio over each other. A module that remembers which handle is playing fixes it:
import type { VideoSurfaceHandle } from "./types";
let current: VideoSurfaceHandle | null = null;
export function claim(handle: VideoSurfaceHandle) {
if (current !== handle) current?.pause();
current = handle;
}
export function release(handle: VideoSurfaceHandle) {
if (current === handle) current = null;
}
export function pauseCurrent() {
current?.pause();
}UniversalVideoPlayer holds the claim while its phase is playing or buffering, so a stall doesn't give it up, and releases it when the video pauses, ends or fails, or the player unmounts:
const active = snapshot.phase === "playing" || snapshot.phase === "buffering";
useEffect(() => {
const handle = surface.current;
if (!active || !handle) return;
claim(handle);
return () => release(handle);
}, [active]);Keying the effect on the phase itself would release the claim the moment the first player stalled. A second player could then start, and once the first one's data arrived, both would play.
A screen that holds players returns pauseCurrent from React Navigation's useFocusEffect, so the video stops when the viewer navigates away. Going to the background needs nothing: Expo Video pauses the player itself unless staysActiveInBackground is set.
Testing it by hand
Each of these has a right answer the code above should give:
- Tap play and pause fast. The icon should end where the engine did, not where the last tap was.
- Rotate while fullscreen. The position should survive, because the player instance does.
- Switch sources while one is playing. The phase goes back to
loading, and the old source's claim on the coordinator goes with it. - Pull the network mid-stream in a browser. Under hls.js, only the
ERRORlistener turns that into the error state. - Start a second player while the first is buffering. The first should stay paused when its data comes back.



