Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix the iOS widget playing a second stream of the same book and showing the wrong play state

Barnabasdc3eefc0e500
diff --git a/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/AbsorbPlayerCoreProtocol.swift b/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/AbsorbPlayerCoreProtocol.swift
index a09eff31..df82d499 100644
--- a/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/AbsorbPlayerCoreProtocol.swift
+++ b/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/AbsorbPlayerCoreProtocol.swift
@@ -15,6 +15,14 @@ public protocol AbsorbPlayerCoreProtocol: Sendable {
func skipForward(seconds: Int)
func skipBackward(seconds: Int)
+ /// What a toggle() issued right now would leave playback doing. The widget
+ /// play/pause intent writes this prediction to `widget_is_playing` for
+ /// instant icon feedback. Unlike blindly inverting the stored flag, this
+ /// stays correct when the flag is stale (e.g. iOS killed the app while it
+ /// was playing, so the flag stuck on true and a cold widget play would
+ /// otherwise show the wrong icon).
+ func willPlayAfterToggle() -> Bool
+
/// Routes a log line through to the host app's Flutter log sink so it
/// surfaces in absorb's in-app log viewer. Widget intents running in the
/// host app process via @Dependency can use this to record progress
diff --git a/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swift b/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swift
index 07793a1c..558dd5df 100644
--- a/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swift
+++ b/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swift
@@ -17,6 +17,53 @@ public func postAbsorbDarwinNotification(_ name: String) {
CFNotificationCenterPostNotification(center, CFNotificationName(name as CFString), nil, nil, true)
}
+// MARK: - Audio ownership (#285)
+//
+// iOS can end up with two processes of the app alive at once: a widget
+// AudioPlaybackIntent can launch a headless background process, and a later
+// foreground launch can be a separate process. Both boot a full Flutter
+// engine, so every shared flag used to be written by both sides and a single
+// widget tap could actuate playback in both processes - two overlapping
+// streams of the same book.
+//
+// The arbitration is now pid-based: `audio_owner_pid` names the one process
+// allowed to act on widget taps, and each process's Flutter proves it is
+// alive via its own pid-scoped `flutter_alive_at_<pid>` heartbeat, so no
+// process can vouch for (or impersonate) another.
+
+/// Pid of the process that currently owns audio, or 0 when never claimed.
+public func absorbAudioOwnerPid() -> Int {
+ return UserDefaults(suiteName: absorbAppGroup)?.integer(forKey: "audio_owner_pid") ?? 0
+}
+
+/// True when `pid`'s Flutter engine wrote its heartbeat within the last 30s.
+/// The key is pid-scoped so a stray background process's heartbeat can't
+/// make another process's Flutter look alive.
+public func absorbFlutterAlive(pid: Int) -> Bool {
+ guard pid > 0,
+ let aliveAt = UserDefaults(suiteName: absorbAppGroup)?
+ .object(forKey: "flutter_alive_at_\(pid)") as? Int
+ else { return false }
+ let ageMs = Int(Date().timeIntervalSince1970 * 1000) - aliveAt
+ return ageMs >= 0 && ageMs < 30_000
+}
+
+/// Claim audio ownership for this process unless the current owner's Flutter
+/// is verifiably alive in another process. Called from each widget intent's
+/// perform(): iOS chose this process to handle a user-initiated audio action,
+/// which is as authoritative as a foreground scene - but only when the
+/// recorded owner is dead (app killed) or has gone quiet (suspended while
+/// paused). A live owner elsewhere keeps ownership and its process actuates
+/// via the Darwin broadcast instead.
+public func absorbClaimOwnershipIfOwnerDead() {
+ let me = Int(getpid())
+ let owner = absorbAudioOwnerPid()
+ if owner == me { return }
+ if absorbFlutterAlive(pid: owner) { return }
+ UserDefaults(suiteName: absorbAppGroup)?.set(me, forKey: "audio_owner_pid")
+ NSLog("[WidgetDebug] intent claimed audio ownership: pid \(me) (previous owner \(owner) not alive)")
+}
+
/// Activate the system audio session from inside an AudioPlaybackIntent's
/// perform(). AVAudioSession is system-wide, so flipping it on here keeps
/// it active by the time the host app's audio engine runs play() a few
@@ -66,6 +113,7 @@ public struct AbsorbSkipBackIntent: AudioPlaybackIntent {
public func perform() async throws -> some IntentResult {
core.log("[NativeCore] SkipBackIntent.perform fired (host process)")
+ absorbClaimOwnershipIfOwnerDead()
activateAbsorbAudioSession()
let seconds = UserDefaults(suiteName: absorbAppGroup)?
.integer(forKey: "widget_skip_back")
@@ -88,10 +136,13 @@ public struct AbsorbPlayPauseIntent: AudioPlaybackIntent {
public func perform() async throws -> some IntentResult {
core.log("[NativeCore] PlayPauseIntent.perform fired (host process)")
- let defaults = UserDefaults(suiteName: absorbAppGroup)
- let wasPlaying = defaults?.bool(forKey: "widget_is_playing") ?? false
- defaults?.set(!wasPlaying, forKey: "widget_is_playing")
- core.log("[NativeCore] wasPlaying=\(wasPlaying) -> \(!wasPlaying) defaults=\(defaults == nil ? "nil" : "ok")")
+ absorbClaimOwnershipIfOwnerDead()
+ // Instant icon feedback: predict what the toggle will do rather than
+ // blindly inverting the stored flag (which is stale after a force-kill).
+ // Whichever side actually actuates writes the real state right after.
+ let willPlay = core.willPlayAfterToggle()
+ UserDefaults(suiteName: absorbAppGroup)?.set(willPlay, forKey: "widget_is_playing")
+ core.log("[NativeCore] predicted willPlay=\(willPlay)")
activateAbsorbAudioSession()
core.toggle()
postAbsorbDarwinNotification("com.barnabas.absorb.widget.playPause")
@@ -112,6 +163,7 @@ public struct AbsorbSkipForwardIntent: AudioPlaybackIntent {
public func perform() async throws -> some IntentResult {
core.log("[NativeCore] SkipForwardIntent.perform fired (host process)")
+ absorbClaimOwnershipIfOwnerDead()
activateAbsorbAudioSession()
let seconds = UserDefaults(suiteName: absorbAppGroup)?
.integer(forKey: "widget_skip_forward")
diff --git a/ios/Runner/AbsorbPlayerCore.swift b/ios/Runner/AbsorbPlayerCore.swift
index 41698f0d..bc92316f 100644
--- a/ios/Runner/AbsorbPlayerCore.swift
+++ b/ios/Runner/AbsorbPlayerCore.swift
@@ -3,6 +3,7 @@ import AVFoundation
import Foundation
import MediaPlayer
import UIKit
+import WidgetKit
/// Controller that drives audiobook playback while Flutter is suspended.
///
@@ -13,8 +14,11 @@ import UIKit
/// (two concurrent streams from the same book).
///
/// State source: app group `np_*` keys written by `home_widget_service.dart`.
-/// Hand-off: `audio_owner_alive_at` heartbeat - if recent, Flutter is in
-/// charge and native bails on every entry point.
+/// Hand-off: the pid-scoped `flutter_alive_at_<pid>` heartbeat - if THIS
+/// process's Flutter wrote it recently, Flutter is in charge and native bails
+/// on every entry point. Pid-scoped because a stray background process runs
+/// its own full Flutter engine, and a shared heartbeat let it make every
+/// process think Flutter was alive (#285).
final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sendable {
static let shared = AbsorbPlayerCore()
@@ -58,6 +62,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.emit("[NativeCore] play(): global=\(self.globalPosition())s")
self.startServerSyncTimer()
self.updateNowPlayingInfo(rate: Double(self.currentSpeed()))
+ self.syncWidgetState()
}
}
@@ -74,6 +79,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.pushProgressToServer()
self.stopServerSyncTimer()
self.updateNowPlayingInfo(rate: 0)
+ self.syncWidgetState()
}
}
@@ -102,6 +108,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.startServerSyncTimer()
self.updateNowPlayingInfo(rate: Double(self.currentSpeed()))
}
+ self.syncWidgetState()
}
}
@@ -158,20 +165,42 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
}
self.emit("[NativeCore] yieldToForegroundOwner: stopping at \(self.globalPosition())s so the foreground app can take over")
self.savePosition()
- UserDefaults(suiteName: Self.appGroup)?.set(false, forKey: "widget_is_playing")
self.stopServerSyncTimer()
AbsorbAudioEngine.shared.stop()
+ self.syncWidgetState()
+ // Relinquish Now Playing so iOS routes lock screen / Control Center
+ // commands to the new owner instead of this stray process. A stale
+ // entry here is what left Control Center greyed out while the other
+ // process's audio kept going.
+ DispatchQueue.main.async {
+ MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
+ }
}
}
private func flutterIsAlive() -> Bool {
- let defaults = UserDefaults(suiteName: Self.appGroup)
- guard let aliveAt = defaults?.object(forKey: "audio_owner_alive_at") as? Int else {
- return false
+ // Only THIS process's Flutter counts - the actions below run in-process,
+ // so another process's live Flutter is irrelevant here.
+ return absorbFlutterAlive(pid: Int(getpid()))
+ }
+
+ /// See AbsorbPlayerCoreProtocol. Runs the prediction on the core queue so
+ /// engine state reads are consistent with any in-flight actuation.
+ func willPlayAfterToggle() -> Bool {
+ return queue.sync {
+ let myPid = Int(getpid())
+ if absorbFlutterAlive(pid: myPid) || absorbFlutterAlive(pid: absorbAudioOwnerPid()) {
+ // A live Flutter (here or in the owning process) will do the toggle,
+ // and it keeps the stored flag accurate - inverting it is safe.
+ let stored = UserDefaults(suiteName: Self.appGroup)?.bool(forKey: "widget_is_playing") ?? false
+ return !stored
+ }
+ if AbsorbAudioEngine.shared.isLoaded {
+ return !AbsorbAudioEngine.shared.isPlaying
+ }
+ // Cold native start: ensureLoaded + play.
+ return true
}
- let nowMs = Int(Date().timeIntervalSince1970 * 1000)
- let ageMs = nowMs - aliveAt
- return ageMs >= 0 && ageMs < 30_000
}
// MARK: - State plumbing
@@ -303,6 +332,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self?.queue.async {
self?.savePosition()
self?.updateNowPlayingInfo(rate: Double(AbsorbAudioEngine.shared.isPlaying ? (self?.currentSpeed() ?? 1.0) : 0))
+ self?.syncWidgetState()
self?.emit("[NativeCore] seekToGlobal done: \(globalSeconds)s")
}
}
@@ -326,6 +356,23 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
defaults?.set(AbsorbAudioEngine.shared.isPlaying, forKey: "widget_is_playing")
}
+ /// Write the engine's real play state (and progress) for the widget, then
+ /// reload its timeline. Flutter does the equivalent whenever it actuates;
+ /// without this the native paths only corrected the flag on pause, so a
+ /// native play from a stale flag left the widget icon inverted until the
+ /// next 5-minute timeline refresh.
+ private func syncWidgetState() {
+ let defaults = UserDefaults(suiteName: Self.appGroup)
+ defaults?.set(AbsorbAudioEngine.shared.isPlaying, forKey: "widget_is_playing")
+ let total = totalDuration()
+ if total > 0 {
+ let permille = Int((globalPosition() / total * 1000).rounded())
+ defaults?.set(min(1000, max(0, permille)), forKey: "widget_progress")
+ }
+ WidgetCenter.shared.reloadTimelines(ofKind: "NowPlayingWidget")
+ WidgetCenter.shared.reloadTimelines(ofKind: "NowPlayingArtWidget")
+ }
+
// MARK: - Server sync
private func startServerSyncTimer() {
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index c4ddd78b..a7a5c42d 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -15,10 +15,6 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
private var volumeKeysChannel: FlutterMethodChannel?
private let volumeKeyWatcher = VolumeKeyWatcher()
- /// True once this process has become the foreground audio owner. Used to
- /// ignore our own takeover broadcast so we don't stop our own playback (#285).
- private var didClaimAudioOwnership = false
-
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
@@ -244,13 +240,13 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
// A foreground process claimed audio ownership. If that's not us,
// stop this process's engine so two streams can't overlap (#285).
- // The owner itself set didClaimAudioOwnership and is .active, so it
- // ignores its own broadcast.
+ // Ownership is arbitrated by pid: the owner reads its own pid back
+ // and ignores its own broadcast.
if rawName == "com.barnabas.absorb.host.takeover" {
DispatchQueue.main.async {
- if appDelegate.didClaimAudioOwnership { return }
+ if absorbAudioOwnerPid() == Int(getpid()) { return }
if UIApplication.shared.applicationState == .active { return }
- NSLog("[WidgetDebug] takeover: foreground app claimed audio, stopping this process's engine")
+ NSLog("[WidgetDebug] takeover: another process claimed audio, stopping this process's engine")
AbsorbPlayerCore.shared.yieldToForegroundOwner()
}
return
@@ -263,6 +259,19 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
case "com.barnabas.absorb.widget.skipForward": action = "skipForward"
default: return
}
+ // Every live process receives this broadcast, so exactly one may
+ // act on it: the audio owner, and only via a Flutter that is
+ // actually responsive. Anything else would actuate in parallel -
+ // a stray background process's headless Flutter toggling next to
+ // the foreground app is how one widget tap produced two streams
+ // of the same book (#285), and a suspended-then-resumed Flutter
+ // replaying the action after the native core already handled it
+ // is how the play state got double-toggled.
+ let myPid = Int(getpid())
+ guard absorbAudioOwnerPid() == myPid, absorbFlutterAlive(pid: myPid) else {
+ NSLog("[WidgetDebug] AppDelegate dropping widget action \(action) (owner=\(absorbAudioOwnerPid()) me=\(myPid)) - the acting process's native core covers it")
+ return
+ }
// Re-activate the audio session as soon as the host app process
// sees the notification, before the async hop to Flutter. The
// widget extension already activates it in perform(), but doing it
@@ -291,8 +300,19 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
/// engine, so two streams can't overlap (#285). A no-op when this is the only
/// process. Called from SceneDelegate.sceneDidBecomeActive.
func claimAudioOwnershipAndNotifyOthers() {
- didClaimAudioOwnership = true
- UserDefaults(suiteName: absorbAppGroup)?.set(Int(getpid()), forKey: "audio_owner_pid")
+ let defaults = UserDefaults(suiteName: absorbAppGroup)
+ defaults?.set(Int(getpid()), forKey: "audio_owner_pid")
+ // Sweep heartbeat keys left by long-dead processes - each app launch
+ // writes its own pid-scoped key, so without this they pile up forever.
+ if let dict = defaults?.dictionaryRepresentation() {
+ let nowMs = Int(Date().timeIntervalSince1970 * 1000)
+ let myKey = "flutter_alive_at_\(getpid())"
+ for (key, value) in dict where key.hasPrefix("flutter_alive_at_") && key != myKey {
+ if let ts = value as? Int, nowMs - ts > 3_600_000 {
+ defaults?.removeObject(forKey: key)
+ }
+ }
+ }
postAbsorbDarwinNotification("com.barnabas.absorb.host.takeover")
}
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index e71481ff..db86bfc1 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -121,9 +121,12 @@ class HomeWidgetService {
_ensureStatsTimer();
// Phase 1.4 hand-off heartbeat. The iOS native player core checks this
- // before driving audio: a recent timestamp means Flutter is alive and
- // owns playback, so the native side bails. Stale or missing means
- // Flutter is dead and the widget can take over.
+ // before driving audio: a recent timestamp means this process's Flutter
+ // is alive and owns playback, so the native side bails. Stale or missing
+ // means Flutter is dead and the widget can take over. The key is
+ // pid-scoped: a widget intent can launch a second, headless copy of the
+ // app whose Flutter also heartbeats, and on a shared key that made every
+ // process think its own Flutter was alive (#285).
if (Platform.isIOS) {
_writeOwnerHeartbeat();
_heartbeatTimer?.cancel();
@@ -137,7 +140,7 @@ class HomeWidgetService {
Future<void> _writeOwnerHeartbeat() async {
try {
await HomeWidget.saveWidgetData<int>(
- 'audio_owner_alive_at',
+ 'flutter_alive_at_$pid',
DateTime.now().millisecondsSinceEpoch,
);
} catch (e) {