Skip to content

Fix main-actor isolation crash on AVAudioSession route changes - #86

Merged
Mag1cByt3s merged 2 commits into
Evil-Project:mainfrom
Mag1cByt3s:fix/audio-session-notification-isolation
Jul 30, 2026
Merged

Fix main-actor isolation crash on AVAudioSession route changes#86
Mag1cByt3s merged 2 commits into
Evil-Project:mainfrom
Mag1cByt3s:fix/audio-session-notification-isolation

Conversation

@Mag1cByt3s

@Mag1cByt3s Mag1cByt3s commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes a Swift 6 main-actor isolation crash in AudioPlayerManager, plus a related teardown cleanup.

1. AVAudioSession notifications were delivered off the main queue

Three sinks observed AVAudioSession notifications without hopping to main first:

NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification)
    .sink { [weak self] note in self?.handleRouteChange(note) }

With SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, these sink closures inherit @MainActor. Combine delivers on the posting thread, so when that thread isn't main the closure traps rather than hopping.

AVAudioSession posts routeChangeNotification on a secondary thread, so unplugging headphones, connecting Bluetooth, or switching to AirPlay could crash the app. mediaServicesWereReset has no documented delivery thread and gets the same treatment. interruptionNotification is documented as main-thread, but is guarded too so it can't silently regress.

The watch and TV AudioManagers already guard the identical handleInterruption/handleRouteChange handlers this way — the iOS target was the only one missing it.

Verification. A standalone probe built with swiftc -swift-version 6 -default-isolation MainActor:

Probe Result
.sink without .receive(on:), posted from a background thread SIGILL (exit 132)
Same, with .receive(on: DispatchQueue.main) sink runs on main, exit 0

2. isolated deinit for teardown

The deinit wrapped its body in MainActor.assumeIsolated, which asserts that the last release happened on the main thread rather than ensuring it. The body invalidates a RunLoop.main timer, removes an AVPlayer time observer, and pauses the radio player — all main-actor work. isolated deinit runs the body on the main actor instead, and lets endBackgroundTask be called directly rather than deferred to a Task that could outlive the deinit.

This restores the pattern already used by AVEnginePlayback, AuthManager, and the watch/TV AudioManagers. It was removed in 0d7308f because isolated deinit needs a Swift 6.1+ compiler while the project was still in Swift 5 language mode; every target is on Swift 6 now, so that constraint is gone.

The class is also marked final with a private init. The deinit's reasoning depends on shared being the only instance, and it already is — this makes the invariant enforced rather than assumed.

Testing

  • iOS unit 95/95, iOS UI 12/12, watch unit 38/38, watch UI 5/5
  • Full recompile of iOS, watch, TV and widget targets with no new warnings
  • Device-tested on iPhone: playback, route changes and interruptions behave correctly

Notes

The route-change path is only reachable on a real device, so the crash isn't covered by the test suites. It was latent until the Swift 6 migration, which is what armed the isolation checks.

Summary by Sourcery

Guard AudioPlayerManager’s AVAudioSession notification handling and teardown against Swift 6 main-actor isolation crashes while enforcing its singleton usage.

New Features:

  • None.

Bug Fixes:

  • Ensure AVAudioSession interruption, route change, and media service reset notifications are delivered to AudioPlayerManager on the main queue to prevent Swift 6 main-actor isolation traps.
  • Run AudioPlayerManager teardown on the main actor via isolated deinit so main-actor-bound resources are cleaned up safely without relying on MainActor.assumeIsolated.

Enhancements:

  • Mark AudioPlayerManager as final with a private initializer to enforce its singleton invariant and align with other audio-related managers.

Summary by CodeRabbit

  • Bug Fixes
    • Improved audio session event handling to ensure interruptions, route changes, and media service resets are processed reliably on the main thread.
    • Enhanced audio player cleanup to stop timers, tasks, observers, and background activity safely during shutdown.

Three AudioPlayerManager sinks observed AVAudioSession notifications
without hopping to the main queue first:

  NotificationCenter.default.publisher(for: .routeChangeNotification)
      .sink { [weak self] note in self?.handleRouteChange(note) }

Under Swift 6 with SWIFT_DEFAULT_ACTOR_ISOLATION=MainActor these sink
closures inherit @mainactor, so Combine delivering them on the posting
thread traps instead of hopping. AVAudioSession posts routeChange on a
secondary thread, which means a headphone unplug, Bluetooth connect or
AirPlay switch could crash the app. mediaServicesWereReset has no
documented delivery thread, so it gets the same treatment;
interruption is documented as main-thread but is guarded for
consistency and to stop it silently regressing.

Verified with a standalone probe built as
`swiftc -swift-version 6 -default-isolation MainActor`: reproducing this
pattern and posting from a background thread dies with SIGILL, and
adding .receive(on: DispatchQueue.main) makes the sink run on main.

The watch and TV AudioManagers already guard the identical
handleInterruption/handleRouteChange handlers this way; the iOS target
was the only one missing it.
The deinit wrapped its body in MainActor.assumeIsolated, which asserts
that the last release happened on the main thread rather than making it
so. The body invalidates a RunLoop.main timer, removes an AVPlayer time
observer and pauses the radio player, all of which need the main actor.

`isolated deinit` runs the body on the main actor instead. It also lets
the endBackgroundTask call happen directly rather than being deferred to
a Task that could outlive the deinit.

This restores the pattern used by AVEnginePlayback, AuthManager and the
watch/TV AudioManagers. It was removed in 0d7308f because isolated
deinit needs a Swift 6.1+ compiler and the project was still in Swift 5
language mode; every target is on Swift 6 now, so that no longer
applies.

Also marks the class final with a private init. The deinit's reasoning
depends on `shared` being the only instance, and it already is -- this
makes the invariant enforced rather than assumed.
@sourcery-ai

sourcery-ai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR hardens AudioPlayerManager’s Swift 6 main-actor isolation by ensuring AVAudioSession-related Combine subscriptions hop to the main queue and by converting teardown to an isolated deinit on a single-instance, final class.

Sequence diagram for AVAudioSession route change handling on the main actor

sequenceDiagram
    participant AVAudioSession
    participant NotificationCenter
    participant DispatchQueue_main
    participant AudioPlayerManager

    AVAudioSession->>NotificationCenter: post routeChangeNotification
    NotificationCenter->>NotificationCenter: publisher(for: AVAudioSession.routeChangeNotification)
    NotificationCenter->>DispatchQueue_main: receive(on: DispatchQueue.main)
    DispatchQueue_main->>AudioPlayerManager: sink handleRouteChange(note)
Loading

File-Level Changes

Change Details Files
Make AudioPlayerManager a single-instance main-actor singleton with enforced invariants.
  • Changed AudioPlayerManager declaration from a non-final @mainactor class to a final class while keeping its main-actor semantics via Swift 6 default isolation.
  • Restricted the initializer to private to ensure shared remains the only instance and to align with process-wide audio and remote-command center singletons.
Twinskaraoke/Services/Audio/Audio/AudioPlayerManager.swift
Ensure AVAudioSession-related Combine sinks execute on the main actor to avoid Swift 6 isolation traps.
  • Added .receive(on: DispatchQueue.main) before sinks for AVAudioSession.interruptionNotification, routeChangeNotification, and mediaServicesWereResetNotification.
  • Documented in comments that AVAudioSession notifications may arrive off-main and that watch/TV AudioManagers already guard these handlers similarly.
Twinskaraoke/Services/Audio/Audio/AudioPlayerManager.swift
Convert teardown to isolated deinit so main-actor-bound cleanup runs safely on the main actor and avoids assumeIsolated traps.
  • Replaced deinit body wrapped in MainActor.assumeIsolated with an isolated deinit that performs all timer, task, AVPlayer, and time-observer cleanup directly.
  • Simplified background task teardown by calling UIApplication.shared.endBackgroundTask directly in deinit instead of dispatching it to a separate Task, relying on isolated deinit’s main-actor execution.
Twinskaraoke/Services/Audio/Audio/AudioPlayerManager.swift

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 35760a14-6c71-435d-bed8-958bf24286a0

📥 Commits

Reviewing files that changed from the base of the PR and between 4eb6705 and 1427696.

📒 Files selected for processing (1)
  • Twinskaraoke/Services/Audio/AudioPlayerManager.swift

📝 Walkthrough

Walkthrough

AudioPlayerManager is finalized as a singleton, audio-session notification handling is moved onto the main queue, and teardown now uses isolated deinitialization for main-actor-bound cleanup.

Changes

AudioPlayerManager updates

Layer / File(s) Summary
Singleton ownership
Twinskaraoke/Services/Audio/AudioPlayerManager.swift
AudioPlayerManager is declared final, and its initializer is restricted to private access.
Main-actor audio lifecycle
Twinskaraoke/Services/Audio/AudioPlayerManager.swift
Interruption, route-change, and media-services-reset notification pipelines receive on DispatchQueue.main; teardown uses isolated deinit to cancel resources, remove observers, and end the background task directly. וה

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: xiaoyuan151

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main fix: preventing a main-actor isolation crash during AVAudioSession route changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Mag1cByt3s
Mag1cByt3s merged commit 318fc57 into Evil-Project:main Jul 30, 2026
4 checks passed
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