TypeScript
fix(mobile): release iOS audio session after video playback (#18539)
Julius Marmingec079503d0773
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swiftindex 08b7e712396..3289fe90363 100644--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift@@ -1,3 +1,4 @@+import AVFoundationimport ExpoModulesCoreimport Securityimport UIKit@@ -97,6 +98,18 @@ public final class T3NativeControlsModule: Module {dismissVideoPresentation(identifier: identifier)}+ // expo-video activates the session for inline playback but never deactivates+ // it. Any other category or mode means another feature (recording) owns it.+ @JS+ @MainActor+ func releaseVideoAudioSession() async {+ // The fullscreen presentation releases the session in its own teardown.+ guard videoPresentation == nil else { return }+ let session = AVAudioSession.sharedInstance()+ guard session.category == .playback, session.mode == .moviePlayback else { return }+ try? session.setActive(false, options: [.notifyOthersOnDeactivation])+ }+@JS@MainActorfunc dismissFile(identifier: String) async {diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swiftindex 74d2f1c7551..388e12cb668 100644--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift@@ -152,15 +152,19 @@ final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate,if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) }backgroundObserver = nillet audioSession = AVAudioSession.sharedInstance()+ // Still what present() set, allowing the .mixWithOthers flip expo-video+ // makes when the inline players pause under this preview. A recorder that+ // claimed the session since owns it.if let previousAudioSession, audioSession.category == .playback,- audioSession.mode == .moviePlayback, audioSession.categoryOptions.isEmpty {- // AVPlayer owns activation. Deactivating the shared session here could- // stop another player or recorder that was active before this preview.+ audioSession.mode == .moviePlayback,+ audioSession.categoryOptions.isSubset(of: [.mixWithOthers]) {try? audioSession.setCategory(previousAudioSession.category,mode: previousAudioSession.mode,options: previousAudioSession.options)+ // Deactivating with notification lets interrupted apps resume.+ try? audioSession.setActive(false, options: [.notifyOthersOnDeactivation])}completion(playbackError)}diff --git a/apps/mobile/src/components/AudioFilePreview.tsx b/apps/mobile/src/components/AudioFilePreview.tsxindex cea4acfb461..1e0c71ef011 100644--- a/apps/mobile/src/components/AudioFilePreview.tsx+++ b/apps/mobile/src/components/AudioFilePreview.tsx@@ -1,7 +1,8 @@import { useAudioPlayer, useAudioPlayerStatus } from "expo-audio";-import { useState } from "react";+import { useEffect, useState } from "react";import { Pressable, View } from "react-native";import { AppText as Text } from "./AppText";+import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession";function timestamp(seconds: number) {const value = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;@@ -12,6 +13,12 @@ export function AudioFilePreview(props: { uri: string; onRetry: () => void }) {const player = useAudioPlayer({ uri: props.uri }, { updateInterval: 500 });const status = useAudioPlayerStatus(player);const [seekError, setSeekError] = useState(false);+ // Video teardown deactivates the shared iOS session, which would stop this player.+ useMediaAudioSessionHold(status.playing);+ const fullscreenVideoOpen = useFullscreenVideoOpen();+ useEffect(() => {+ if (fullscreenVideoOpen) player.pause();+ }, [fullscreenVideoOpen, player]);const seek = (seconds: number, play = false) => {setSeekError(false);void playerdiff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsxindex c35195cd3a5..c36bcd024a6 100644--- a/apps/mobile/src/components/MediaVideoPlayer.tsx+++ b/apps/mobile/src/components/MediaVideoPlayer.tsx@@ -10,6 +10,7 @@ import { SymbolView } from "./AppSymbol";import { VideoThumbnailImage } from "./VideoThumbnailImage";import { useMediaActions } from "../state/mediaActions";import { type MediaActionsSource } from "../lib/mediaActionsSource";+import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession";import { MediaActionsMenu } from "./MediaActionsMenu";/** Loads only after Play or opening the viewer. Source replacement never starts playback itself. */@@ -20,6 +21,8 @@ function LoadedMediaVideo(props: {readonly paused: boolean;}) {const focused = useIsFocused();+ const fullscreenVideoOpen = useFullscreenVideoOpen();+ const paused = props.paused || fullscreenVideoOpen;const active = useRef(focused && AppState.currentState === "active");const fullscreen = useRef(false);const [attempt, setAttempt] = useState(0);@@ -30,6 +33,8 @@ function LoadedMediaVideo(props: {player.bufferOptions = { preferredForwardBufferDuration: 5 };});const { status } = useEvent(player, "statusChange", { status: player.status });+ const { isPlaying } = useEvent(player, "playingChange", { isPlaying: player.playing });+ useMediaAudioSessionHold(isPlaying);const loadSource = useEffectEvent(async (signal: AbortSignal) => {const uri = props.resolvePlaybackUri ? await props.resolvePlaybackUri() : props.uri;if (signal.aborted) return;@@ -40,16 +45,16 @@ function LoadedMediaVideo(props: {});useEffect(() => {- active.current = focused && !props.paused && AppState.currentState === "active";- if (!focused || props.paused || (!active.current && !fullscreen.current)) player.pause();+ active.current = focused && !paused && AppState.currentState === "active";+ if (!focused || paused || (!active.current && !fullscreen.current)) player.pause();// Native background handling distinguishes Android's fullscreen activity// from leaving the app; React Native reports both as background.const subscription = AppState.addEventListener("change", (state) => {- active.current = focused && !props.paused && state === "active";+ active.current = focused && !paused && state === "active";if (state === "inactive" || (state === "background" && !fullscreen.current)) player.pause();});return () => subscription.remove();- }, [focused, player, props.paused]);+ }, [focused, player, paused]);useEffect(() => {const controller = new AbortController();diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsxindex ae69e0ead89..4cae4d30db4 100644--- a/apps/mobile/src/components/VideoPreviewModal.ios.tsx+++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx@@ -4,6 +4,7 @@ import { useEffect, useEffectEvent, useId, useState } from "react";import { Alert, Keyboard } from "react-native";import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";+import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioSession";import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource";import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";import { usePreparedConnection } from "../state/session";@@ -51,6 +52,10 @@ function NativeVideoPreview(props: {: null;useEffect(() => Keyboard.dismiss(), []);+ useEffect(() => {+ fullscreenVideoOpened();+ return () => fullscreenVideoClosed();+ }, []);useEffect(() => {if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);}, [playbackUrl, resolvedUrl]);diff --git a/apps/mobile/src/lib/videoAudioSession.test.ts b/apps/mobile/src/lib/videoAudioSession.test.tsnew file mode 100644index 00000000000..3deb938efe5--- /dev/null+++ b/apps/mobile/src/lib/videoAudioSession.test.ts@@ -0,0 +1,54 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({+ platform: { OS: "ios" as "ios" | "android" },+ release: vi.fn(async (): Promise<void> => {}),+}));+vi.mock("react-native", () => ({ Platform: mocks.platform }));+vi.mock("expo", () => ({+ requireOptionalNativeModule: () => ({ releaseVideoAudioSession: mocks.release }),+}));++let session: typeof import("./videoAudioSession");++beforeEach(async () => {+ vi.resetModules();+ vi.useFakeTimers();+ mocks.platform.OS = "ios";+ mocks.release.mockClear().mockResolvedValue(undefined);+ session = await import("./videoAudioSession");+});++afterEach(() => vi.useRealTimers());++describe("video audio session", () => {+ it("releases once, after the last playing player stops, unless playback restarts first", () => {+ session.mediaPlaybackStarted();+ session.mediaPlaybackStarted();+ session.mediaPlaybackStopped();+ vi.advanceTimersByTime(1_000);+ expect(mocks.release).not.toHaveBeenCalled();++ // A player starting inside the deferral window keeps the session.+ session.mediaPlaybackStopped();+ session.mediaPlaybackStarted();+ vi.advanceTimersByTime(1_000);+ expect(mocks.release).not.toHaveBeenCalled();++ session.mediaPlaybackStopped();+ vi.advanceTimersByTime(1_000);+ expect(mocks.release).toHaveBeenCalledTimes(1);+ });++ it("stays fullscreen until every overlapping presentation closes", () => {+ const listener = vi.fn();+ session.subscribeFullscreenVideo(listener);+ session.fullscreenVideoOpened();+ session.fullscreenVideoOpened();+ session.fullscreenVideoClosed();+ expect(session.isFullscreenVideoOpen()).toBe(true);+ session.fullscreenVideoClosed();+ expect(session.isFullscreenVideoOpen()).toBe(false);+ expect(listener).toHaveBeenCalledTimes(4);+ });+});diff --git a/apps/mobile/src/lib/videoAudioSession.ts b/apps/mobile/src/lib/videoAudioSession.tsnew file mode 100644index 00000000000..a09299531ec--- /dev/null+++ b/apps/mobile/src/lib/videoAudioSession.ts@@ -0,0 +1,74 @@+import { requireOptionalNativeModule } from "expo";+import { useEffect, useSyncExternalStore } from "react";+import { Platform } from "react-native";++const nativeControls = requireOptionalNativeModule<{+ releaseVideoAudioSession(): Promise<void>;+}>("T3NativeControls");++// Players report not playing during seeks and buffering stalls, and another+// player may start right after one stops. Both keep the session.+const RELEASE_DELAY_MS = 1_000;++let playingCount = 0;+let releaseTimer: ReturnType<typeof setTimeout> | undefined;++/** Pairs with `mediaPlaybackStopped` for each inline video or audio player holding the session. */+export function mediaPlaybackStarted(): void {+ playingCount += 1;+}++/**+ * expo-video activates the iOS playback session but never deactivates it, so+ * interrupted apps (Spotify, Podcasts) are never told they may resume. The+ * last player to stop releases it. In-app audio previews count too, since+ * deactivating stops them.+ */+export function mediaPlaybackStopped(): void {+ playingCount -= 1;+ if (playingCount > 0 || Platform.OS !== "ios") return;+ clearTimeout(releaseTimer);+ releaseTimer = setTimeout(() => {+ if (playingCount > 0) return;+ void nativeControls?.releaseVideoAudioSession().catch(() => undefined);+ }, RELEASE_DELAY_MS);+}++let fullscreenCount = 0;+const fullscreenListeners = new Set<() => void>();++/** Pairs with `fullscreenVideoClosed` while the native fullscreen player is open. */+export function fullscreenVideoOpened(): void {+ fullscreenCount += 1;+ for (const listener of fullscreenListeners) listener();+}++export function fullscreenVideoClosed(): void {+ fullscreenCount -= 1;+ for (const listener of fullscreenListeners) listener();+}++export function subscribeFullscreenVideo(listener: () => void): () => void {+ fullscreenListeners.add(listener);+ return () => {+ fullscreenListeners.delete(listener);+ };+}++export function isFullscreenVideoOpen(): boolean {+ return fullscreenCount > 0;+}++/** In-app players pause while the iOS fullscreen player owns playback and the session. */+export function useFullscreenVideoOpen(): boolean {+ return useSyncExternalStore(subscribeFullscreenVideo, isFullscreenVideoOpen);+}++/** Holds the session for as long as `active`, releasing it with the last holder. */+export function useMediaAudioSessionHold(active: boolean): void {+ useEffect(() => {+ if (!active) return;+ mediaPlaybackStarted();+ return () => mediaPlaybackStopped();+ }, [active]);+}