WebRTC on Safari: repeated camera prompts, black remote video and calls dying in background
Our video call app passed every Chrome test and then failed three different ways on Safari: extra permission prompts, a black remote tile after an H.264 profile mismatch, and calls that froze when an iPhone was locked. One root cause per symptom, one fix each.
We had built a one-to-one video call feature for a coaching marketplace and tested it mostly on Chrome and Android. When we opened it to iPhone users, three bug reports arrived in the same week:
"It asks for my camera again every time I open a call, sometimes twice."
"I can hear my coach but their video is black." (Coach on Safari for Mac, client on an Android phone, both using our SFU.)
"The call freezes when my phone locks and never comes back."
They looked like one vague "Safari is broken" problem. They were three separate causes.
Reproducing it
Symptom 1: open the call page on iOS Safari, accept the camera prompt, switch from front to back camera in our UI. Safari prompted again.
Symptom 2: start a call between Safari on macOS and Chrome on Android through the SFU. Audio flowed.
getStats()on the Safari side showed aninbound-rtpvideo entry withbytesReceivedgrowing andframesDecodedstuck at 0.Symptom 3: on an iPhone, join a call and press the side button to lock the screen for 30 seconds. On unlock, local video was frozen and the remote side saw our tile stuck on the last frame.
What we ruled out
HTTPS or permissions policy. The page was served over HTTPS and our
Permissions-Policyheader allowedcameraandmicrophonefor self. Without those,getUserMedia()fails outright instead of prompting twice.Bandwidth for symptom 2. Bytes were arriving. The decoder was the problem, not the network.
Our reconnect logic for symptom 3. The WebSocket survived short locks. The media did not.
Root cause
Prompts: our camera switcher called
getUserMedia()again for each device change and for each component that needed a preview, and the user's Safari website setting for camera was the default "Ask". Each new capture request could trigger a prompt.Black video: the SFU was configured to forward a single H.264 profile. The Android sender negotiated H.264 with a
profile-level-idthe SFU relayed to Safari, but our SFU's codec table rewrote the SDP so Safari believed it would receive a different profile than the one actually sent. Safari accepted the packets but its decoder rejected the stream.Background: iOS interrupts camera capture when Safari leaves the foreground. Our local track fired
mute, and on return we never re-acquired the camera or replaced the track on the sender.
What is happening under the hood
Capture permission. Safari's camera and microphone permission is controlled per website in Safari settings with "Ask", "Deny" and "Allow". With "Ask", Safari decides when to prompt again, and repeated capture requests are a common trigger. The fix on our side is to capture once and reuse the tracks rather than call getUserMedia() from many places. iOS also allows only one active capture of a kind at a time, so a second camera request can mute the first track.
H.264 profiles. H.264 comes in profiles (Constrained Baseline, Main, High) and levels. In SDP, profile-level-id advertises them, and packetization-mode must match too. Safari offers several H.264 variants. If an SFU rewrites payload types or profiles inconsistently, a receiver can end up with a decoder configured for one profile while packets of another arrive. Audio and other media continue to work, which makes it look like a camera problem.
Autoplay of remote media. WebKit's autoplay policy treats media backed by a MediaStream specially: if the page is already capturing camera or microphone, remote media with audio may play without a separate gesture. If the page is not capturing, for example a viewer who joined with camera off, the remote <video> must be muted or started from a user gesture. That is why some of our viewers also saw a frozen first frame.
Background on iOS. When Safari moves to the background or the device locks, iOS suspends capture. The track is muted, not ended, in short interruptions; after longer ones the page itself may be suspended and network connections dropped.
Environment
Component | Version / value |
|---|---|
Safari | Safari 26 on macOS 26, iOS 26 |
Other clients | Chrome 141 on Android 15 and desktop |
SFU | Self-hosted, H.264 and VP8 enabled |
Page | HTTPS, |
Minimal reproduction
The camera switcher before the fix:
// before: new capture for every switch and every preview
async function useCamera(deviceId) {
const stream = await navigator.mediaDevices.getUserMedia({
video: { deviceId: { exact: deviceId } },
audio: true,
});
previewEl.srcObject = stream;
sender.replaceTrack(stream.getVideoTracks()[0]);
}
Who is affected
Symptom 1 affects any app that calls getUserMedia() repeatedly on Safari. Symptom 2 affects SFU setups that use H.264 and rewrite or filter codec parameters, particularly between Apple devices and Android hardware encoders. Symptom 3 affects every WebRTC app on iOS; the platform behaviour is by design, so the app must handle it.
The fix
1. Capture once, switch with constraints. We keep one stream per session. Switching cameras stops only the old video track and requests a new video track, never a new audio track, and every preview uses the same stream.
// after
let session = null;
export async function initMedia() {
session ??= await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
return session;
}
export async function switchCamera(deviceId, sender) {
const old = session.getVideoTracks()[0];
const fresh = await navigator.mediaDevices.getUserMedia({
video: { deviceId: { exact: deviceId } },
});
const track = fresh.getVideoTracks()[0];
await sender.replaceTrack(track);
session.removeTrack(old);
old.stop();
session.addTrack(track);
}
We also added a help page telling users how to set the site to "Allow" in Safari settings if they use the app daily.
2. Pin codec preferences on the client and fix the SFU table. We fixed the SFU config so it forwards H.264 with matching profile-level-id and packetization-mode=1, and on clients we put VP8 first for SFU calls, keeping H.264 as fallback. setCodecPreferences() is supported in Safari and Chrome:
function preferCodecs(transceiver, order = ['video/VP8', 'video/H264']) {
const { codecs } = RTCRtpReceiver.getCapabilities('video');
const ranked = [
...order.flatMap((m) => codecs.filter((c) => c.mimeType === m)),
...codecs.filter((c) => !order.includes(c.mimeType)),
];
transceiver.setCodecPreferences(ranked);
}
3. Treat remote video as muted by default. Remote <video> elements are created with autoplay, playsinline and muted; audio plays through a separate <audio> element that we start after the "Join" click.
<video id="remote" autoplay playsinline muted></video>
<audio id="remote-audio"></audio>
4. Recover after background. We listen for track mute/ended and page visibility, then re-acquire and replace the track, and restart ICE if the connection dropped.
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState !== 'visible') return;
const track = session.getVideoTracks()[0];
if (!track || track.readyState === 'ended' || track.muted) {
await switchCamera(currentDeviceId, videoSender);
}
if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
pc.restartIce();
}
});
We show a small banner, "Video paused while the app was in the background", so users understand the gap.
Alternatives and trade-offs
VP8 everywhere. Simplest interop, but costs battery on devices where H.264 is hardware encoded and VP8 is not.
H.264 everywhere. Best hardware support on Apple devices; requires a careful SFU profile setup and testing with Android hardware encoders.
A native app for iOS. Gives background audio modes that a web page cannot have. Worth it only if long background calls are a core requirement.
How to test the fix
We wrote a manual matrix and ran it on real devices: Safari macOS to Chrome Android, iOS Safari to Chrome desktop, iOS to iOS, each with camera on and off. For codec checks:
const stats = await pc.getStats();
stats.forEach((s) => {
if (s.type === 'inbound-rtp' && s.kind === 'video') {
const codec = stats.get(s.codecId);
console.log(codec.mimeType, codec.sdpFmtpLine, s.framesDecoded);
}
});
A passing run shows framesDecoded increasing and the sdpFmtpLine matching the sender's outbound codec line.
Confirming in production
We tag quality beacons with browser family. For Safari sessions we track three counters: capture requests per session, video tracks with zero decoded frames after ten seconds, and recoveries after visibilitychange. After the release, capture requests per Safari session fell from a median of 3 to 1, zero-frame tracks went from 6 percent to under 0.5 percent, and 90 percent of background interruptions recovered video without the user leaving the call.
Regression guard
The device-lab matrix runs before each release on two iPhones and one Mac.
A unit test asserts that every module gets tracks from
initMedia()and that no other file callsgetUserMedia()directly, enforced with a lint rule.The SFU config is validated in CI against a list of allowed codec lines.
Security implications
Capturing once and keeping the stream means the camera is live for the whole session, so stop all tracks on leave and when the user turns the camera off, otherwise the capture indicator stays on. Do not try to avoid prompts by reading device labels or fingerprinting devices; labels are only available after permission for privacy reasons. No other change to attack surface.
Prevention checklist
Call
getUserMedia()from one place and reuse the tracks.Keep codec configuration consistent between clients and SFU; check
sdpFmtpLinein stats.Create remote video muted with
playsinline; start audio after a user gesture.Handle
mute,endedandvisibilitychangeand re-acquire capture on iOS.Test on real Apple devices for every release.
References
WebKit blog, A Closer Look Into WebRTC (MediaStream autoplay rules): https://webkit.org/blog/7726/a-closer-look-into-webrtc/
MDN,
RTCRtpTransceiver.setCodecPreferences(): https://developer.mozilla.org/en-US/docs/Web/API/RTCRtpTransceiver/setCodecPreferencesMDN,
RTCRtpSender.replaceTrack(): https://developer.mozilla.org/en-US/docs/Web/API/RTCRtpSender/replaceTrackMDN,
MediaDevices.getUserMedia(): https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMediaRFC 6184, RTP payload format for H.264 and
profile-level-id: https://datatracker.ietf.org/doc/html/rfc6184
Add a label
Embed this post
<iframe src="https://hibug.me/webrtc-safari-quirks-getusermedia-h264-autoplay" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I am a site reliability engineer on a platform team that runs the edge for dozens of internal services: API gateways, reverse proxies, load balancers and the resilience settings everyone copies from each other. The incidents I learn most from happen when a safety mechanism does the wrong thing. A rate limit that locked out an entire office behind one IP, a circuit breaker that never opened, a liveness probe that restarted every pod during a database blip, two nodes that both decided they were primary. Each post explains what the mechanism was meant to do, why it misfired in our setup, how we changed the configuration and how we drilled the failure afterwards to prove it. I keep the examples close to real configs so you can compare them with your own.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.