Skip to content

perf(ios): activate the audio session while the video core is created - #3034

Merged
edde746 merged 2 commits into
mainfrom
perf/apple-preactivate-audio-session
Nov 10, 2026
Merged

edde746 merged 2 commits into
mainfrom
perf/apple-preactivate-audio-session

Conversation

@edde746

@edde746 edde746 commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

What

On iPhone and iPad a video player core now activates the audio session itself while it is created, on a serial queue of its own, instead of leaving that to mpv's audio output. tvOS, macOS and the music core are unchanged.

  • MpvAudioSessionActivation (new, in MpvPlayerCoreBase.swift, iOS only) makes the two calls ao_avfoundation makes before it activates: setCategory(.playback, mode: .moviePlayback) and setActive(true). setupMpv() asks for them before mpv_create, so they overlap mpv's creation, the option writes and the app resolving what to play. loadfile does not wait for them.
  • Once no mpv context is left in the process, a session that a video core activated is deactivated with .notifyOthersOnDeactivation. Until now only an audio output that had opened did that, and a core that never opens one (a failed open, a file without an audio track) would otherwise leave the session active.
  • Music cores are counted as live contexts, so that this deactivation can never cut their audio, but they activate nothing: a music core can exist long before it plays.
  • Contexts are counted under a lock on the thread that creates or destroys them, and a queued deactivation reads the count when it runs. Otherwise a deactivation queued behind a slow activation would not see a music core created since, whose output may already be playing. A failed activation (a call in progress) or deactivation leaves the flag as it was, so nothing is deactivated that this code did not activate, and a failed deactivation is retried by the next one.

Why

mpv's audio output activates AVAudioSession when it opens, synchronously on mpv's core thread, after the first video frame has been decoded and before it is shown. The frame waits for the audio server. Done ahead of time, the output finds the session active and opens in a few milliseconds.

The calls block on the audio server wherever they run (15.8 ms + 25.7 ms measured, see below), so they must not run on the main thread while the player screen opens. They run on a private serial queue.

Measurements

iPhone Air (iOS 27.0.1), local 1080p H.264 + AAC MP4, loadfile to PLAYBACK_RESTART with in-process monotonic timestamps, n = 5 per row, rows interleaved, median (min-max). Measured with a bench app that hosts libmpv with Plezy's option set and observed properties, not in Plezy, and with a newer libmpv than the one pinned here.

who activates the session loadfile to PLAYBACK_RESTART
the host, before the load 49.7 ms (47.8-50.3)
mpv's audio output, first load of the process 92.2 ms (91.3-94.2)
mpv's audio output, a later load in the same process (the output deactivated the session when the previous file stopped) 74.4 ms (73.9-77.0)

setCategory + setActive from the host took 15.8 ms + 25.7 ms (n = 60).

What that means for Plezy, to be read with care:

  • The "first load" row started from the system's default category. Plezy sets .playback at launch, so its first open should lie between the second and the third row. The expected gain per newly opened player is therefore about 25 to 42 ms, not a flat 42 ms.
  • It applies to the first file of a newly created video core. A later file in the same core is unaffected: either mpv keeps its audio output open across the files, or the output was closed in between (which deactivates the session) and activates it again itself, as today.
  • When a video core replaces another, the old core's audio output deactivates the session as it is torn down, which can land after the new core's activation. The new output then activates the session itself, as today: the gain is lost, nothing else changes.

When other apps' audio stops

The session is non-mixing, so activating it interrupts other apps' audio. That happens at a different moment now:

before after
a video that opens and plays when mpv's audio output opens for the file, shortly before the first frame when the player core is created, i.e. when the player screen opens and before the stream is resolved. Earlier by the time it takes to resolve and open the stream.
a video without an audio track, or with audio deselected when the media controls get their first "playing" state (they activate the session on that) when the player core is created
an open that fails, or a player that is closed before anything was loaded never when the player core is created. The core lives as long as the player screen (the failure view keeps it for Retry), so the session stays active until the screen is left; then the core is destroyed, the session is deactivated and other apps are notified. Apps that honour the notification resume; others stay paused until the user resumes them.
muted playback, or a file opened paused as the first row: mpv opens its audio output regardless as the first row

Android already claims audio focus at the same point (requestAudioFocus runs in parallel with the player's setup).

Everything else is as before: the app delegate still only sets the category at launch, the PiP controller still makes its own (redundant) activation, interruptions and route changes are still observed by os_media_controls and handled in Dart, the media controls still activate on "playing" and deactivate when they are cleared, and mpv's audio output still deactivates the session when it closes. mpv's own activation is untouched, so audio does not depend on this change: if the early activation fails or is undone, the output activates the session itself exactly as today.

Verified

  • Read in mpv v0.41.0 with the patch series of the libmpv build pinned here: ao_avfoundation sets category and mode and calls setActive:YES on every open and setActive:NO (notifying others) on every close and on a failed open; ao_audiounit does the same; ao_spatial activates and never deactivates; the output is opened when the first audio is decoded, whether or not playback is paused, and closed on stop, on teardown, when audio is deselected and when the format changes. None of this is reference counted: an activation by the host does not change when mpv deactivates.
  • New XCTests (iOS):
    • a video context's activation runs off the main thread and its caller returns while the activation is still blocked;
    • the last mpv context to go deactivates what a video context activated, once;
    • no deactivation while another context (a replacing video core, or a music core) is alive;
    • music contexts cause no session calls at all;
    • a deactivation queued behind a still-blocked activation spares a music context created before it runs (fails on the first revision of this PR);
    • a failed activation leads to no deactivation (fails on the first revision);
    • with the real AVAudioSession on the simulator: creating the real video core moves the session from the launch configuration to .playback / .moviePlayback before any file is loaded, and a file then plays through ao_avfoundation on the same core. With the activation switched off this test fails on the mode, so it does observe the change. It puts the session back to the launch mode afterwards.
  • xcodebuild test -scheme Runner -configuration Debug as in the "Apple native reliability" CI job:
    • second revision, iOS (iPhone 17 simulator): MpvPlayerContractTests, 32 tests, 0 failures, including the two new ones; tvOS and macOS not rerun (the change is inside #if os(iOS))
    • first revision, iOS (iPhone 17 simulator, iOS 27.0): 31 tests, 0 failures, including the five new ones
    • tvOS (Apple TV 4K simulator, tvOS 26.5): 51 tests, 0 failures; tvos/scripts/test_wire_mpv.rb and test_wire_top_shelf.rb pass (no tvOS behaviour changes: the shared file is compiled there)
    • macOS (27.2): 16 tests, 0 failures (the shared file is compiled there)
  • One-off local XCTests (not part of this PR), iOS simulator: the real video core played an H.264 + AAC file and an H.264 file without audio through vo_avfoundation; the second opened no audio output, and after its disposal repeating the activation and the deactivation on the real session raised no error.
  • scripts/format_native.sh --check: passed. The Dart checks of scripts/ci_checks.sh were not rerun: no Dart file is touched.
  • Local toolchain: Xcode 27.2; Flutter 3.47.8 for iOS and macOS, 3.47.1 (CI's version) for tvOS.

On main's latest CI run the iOS job of "Apple native reliability" fails in testSpeedWrittenWhilePausedTakesEffectOnPlay, a test this PR does not touch. It passed in the local runs above.

Not verified

  • No timing was measured in Plezy. The simulator cannot show it, and no physical device was used for this change. The numbers above are the bench app's on an iPhone Air.
  • How other apps' audio actually stops and resumes on a device (the table above follows from the code and from Apple's documentation of setActive), Bluetooth and AirPlay routes, and activation while a call is in progress.
  • tvOS is left out on purpose: nothing was measured there, its first audio output is ao_audiounit, which configures the session differently, and the session uses the long-form route sharing policy.

Risk and how to turn it off

The risk is in when the session is active, not in whether audio plays. To turn the change off, pass activatingAudioSession: false in setupMpv() (or drop the argument): no core activates, and the deactivation never runs because nothing was activated by a core.

If stopping other apps' audio at player creation is too early, the same calls could be started when the first loadfile is issued instead. Most failed opens would then not interrupt anything, but the activation would race the output's own instead of preceding it, which is not the configuration the bench measured.

AI-assisted: Claude (Anthropic), model id anthropic/claude-fable-5-2.

mpv's audio output activates AVAudioSession when it opens, on mpv's core
thread, after the first video frame is decoded and before it is shown.
On iPhone and iPad a video core now makes the same calls itself as it is
created, on a serial queue of its own, so they overlap mpv's creation and
the app resolving what to play, and the output finds the session active.
Nothing waits for them, and the output still activates the session
itself, so audio does not depend on this.

Only an output that opened deactivated the session, so once no mpv
context is left, a session that a video core activated is deactivated
too: a failed open or a file without audio would otherwise leave other
apps' audio stopped. Music cores count as contexts but activate nothing.

The session is non-mixing: other apps' audio now stops when the player
core is created rather than when the output opens, and also when the
open then fails.

On an iPhone Air, with a bench app hosting libmpv with Plezy's options
rather than Plezy, loadfile to PLAYBACK_RESTART took 49.7 ms with the
session active beforehand against 74.4 to 92.2 ms when the output
activated it (n = 5). tvOS, macOS and the music core are unchanged.
…ivation spares new music

A video core torn down while its audio session activation still waited on the audio server queued a deactivation that counted contexts only when it ran on the activation queue, after a music core created in the meantime had registered itself there. That deactivation could stop the music its output had already started. Contexts are now counted under a lock on the caller's thread, and the queued deactivation reads the count when it runs. The activation also counts as done only once setActive succeeds, so a failed one (a call in progress) no longer leads to deactivating a session something else activated, and a failed deactivation is retried by the next one. The real-session test puts the process-wide session back to the launch mode for the tests after it.
@edde746
edde746 merged commit e8074c4 into main Nov 10, 2026
29 of 30 checks passed
@edde746
edde746 deleted the perf/apple-preactivate-audio-session branch November 11, 2026 01:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant