Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Stop headset play opening a different app after a cold launch on iOS

Barnabas8af7f926f263
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index 02d5ae9b..74d6cd9a 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -16,6 +16,16 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
private var volumeKeysChannel: FlutterMethodChannel?
private let volumeKeyWatcher = VolumeKeyWatcher()
+ // Native log lines emitted before Dart's channel handler registers, kept
+ // with their uptime so the flush can stamp when they happened. Flutter
+ // buffers only ONE pre-handler message per channel, so early lines
+ // (notably [NowPlayingPrimer]) otherwise overwrite each other and never
+ // reach the shared log.
+ private var pendingNativeLogs: [(Double, String)] = []
+ private var dartLogReady = false
+ private let launchUptime = ProcessInfo.processInfo.systemUptime
+ private var hasScheduledNowPlayingPrime = false
+
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
@@ -56,21 +66,30 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
// "log" method, which surfaces lines as `[WidgetDebug] [NativeCore] ...`
// in absorb's in-app log viewer. No Mac/Xcode needed to verify behavior.
AbsorbPlayerCore.logSink = { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
NowPlayingPrimer.logSink = { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
// Take the Now Playing slot for the last-played book, so the headset works
- // before the user has pressed play in the app. Slightly after launch so the
- // audio session plugin has settled and the log channel is listening.
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- NowPlayingPrimer.primeAtLaunch()
+ // before the user has pressed play in the app. Anchored to scene activation
+ // rather than a timer after launch: iOS quietly refuses audio started by an
+ // app that is not active yet, which would leave us half-claimed - session
+ // active and info published, but no audio ever rendered, so a headset press
+ // still launches whichever app genuinely played last. This notification
+ // also fires for the CarPlay scene, covering launches from the car with the
+ // phone locked. Primed once per process; foregrounding again is a no-op.
+ NotificationCenter.default.addObserver(
+ forName: UIScene.didActivateNotification,
+ object: nil, queue: .main
+ ) { [weak self] _ in
+ guard let self, !self.hasScheduledNowPlayingPrime else { return }
+ self.hasScheduledNowPlayingPrime = true
+ // A beat after activation so the audio session plugin has settled.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
+ NowPlayingPrimer.primeAtLaunch()
+ }
}
// Same routing for the EQ tap's format diagnostics, so when a user
@@ -78,31 +97,21 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
// PCM format the tap actually received (low-bitrate AAC m4b often
// shows up here as mono / unusual sample rate).
AudioEQProcessor.setFormatLogger { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
AbsorbAudioEQProcessor.setFormatLogger { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
IOSQueueAdvancer.logSink = { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
AbsorbAudioEngine.logSink = { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
AbsorbAudioBridge.logSink = { [weak self] line in
- DispatchQueue.main.async {
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
- }
+ self?.logToFlutter(line)
}
// Register the native player core as an AppIntent dependency. The widget
@@ -224,11 +233,20 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
/// Forwards a log line to the Dart LogService via the widget channel so it
/// appears in the in-app log viewer (NSLog alone only shows in Xcode /
- /// Console.app on a Mac).
+ /// Console.app on a Mac). Lines emitted before Dart signals "logReady" are
+ /// buffered and flushed then.
private func logToFlutter(_ message: String) {
NSLog("[WidgetDebug] %@", message)
DispatchQueue.main.async { [weak self] in
- self?.widgetChannel?.invokeMethod("log", arguments: ["msg": message])
+ guard let self else { return }
+ if self.dartLogReady {
+ self.widgetChannel?.invokeMethod("log", arguments: ["msg": message])
+ } else {
+ self.pendingNativeLogs.append((ProcessInfo.processInfo.systemUptime, message))
+ if self.pendingNativeLogs.count > 400 {
+ self.pendingNativeLogs.removeFirst(self.pendingNativeLogs.count - 400)
+ }
+ }
}
}
@@ -497,8 +515,21 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
let widgetChannel = FlutterMethodChannel(name: "com.absorb.widget",
binaryMessenger: messenger)
self.widgetChannel = widgetChannel
- widgetChannel.setMethodCallHandler { (call, result) in
+ widgetChannel.setMethodCallHandler { [weak self] (call, result) in
switch call.method {
+ case "logReady":
+ // Dart's log listener is live - flush everything buffered since
+ // launch, stamped with seconds-after-launch so timing survives the
+ // batch delivery.
+ guard let self else { result(true); return }
+ self.dartLogReady = true
+ let pending = self.pendingNativeLogs
+ self.pendingNativeLogs = []
+ for (uptime, line) in pending {
+ let stamp = String(format: "%.1f", uptime - self.launchUptime)
+ self.widgetChannel?.invokeMethod("log", arguments: ["msg": "[+\(stamp)s] \(line)"])
+ }
+ result(true)
case "getGroupContainerPath":
if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.barnabas.absorb") {
NSLog("[WidgetDebug] getGroupContainerPath resolved: %@", url.path)
diff --git a/ios/Runner/NowPlayingPrimer.swift b/ios/Runner/NowPlayingPrimer.swift
index 43edb231..dd0da45d 100644
--- a/ios/Runner/NowPlayingPrimer.swift
+++ b/ios/Runner/NowPlayingPrimer.swift
@@ -27,12 +27,55 @@ enum NowPlayingPrimer {
/// The silent player has to outlive this function or it deallocates before
/// the blip finishes and the claim never lands.
- private static var blipPlayer: AVPlayer?
+ private static var blipPlayer: AVAudioPlayer?
- /// A 44-byte WAV header with no samples: enough for iOS to count as playback,
- /// too short to be heard even if the volume guard failed.
- private static let silentWav =
- "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA="
+ /// Logs whether the blip actually rendered. play() returning true only means
+ /// the request was accepted; this is the ground truth.
+ private final class BlipDelegate: NSObject, AVAudioPlayerDelegate {
+ func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
+ DispatchQueue.main.async {
+ NowPlayingPrimer.logSink?("[NowPlayingPrimer] blip finished (rendered=\(flag))")
+ NowPlayingPrimer.blipPlayer = nil
+ }
+ }
+
+ func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
+ DispatchQueue.main.async {
+ NowPlayingPrimer.logSink?(
+ "[NowPlayingPrimer] blip decode error: \(error?.localizedDescription ?? "unknown")")
+ NowPlayingPrimer.blipPlayer = nil
+ }
+ }
+ }
+
+ private static let blipDelegate = BlipDelegate()
+
+ /// True silence as 16-bit mono 8kHz PCM. The samples must exist: a
+ /// header-only WAV with an empty data chunk renders nothing, and iOS does
+ /// not hand over the Now Playing slot for audio that never reached the
+ /// mixer - the whole point of the blip.
+ private static func makeSilentWav(durationMs: Int) -> Data {
+ let sampleRate = 8000
+ let dataSize = sampleRate * durationMs / 1000 * 2
+ var wav = Data(capacity: 44 + dataSize)
+ func u32(_ v: UInt32) { var x = v.littleEndian; wav.append(Data(bytes: &x, count: 4)) }
+ func u16(_ v: UInt16) { var x = v.littleEndian; wav.append(Data(bytes: &x, count: 2)) }
+ wav.append("RIFF".data(using: .ascii)!)
+ u32(UInt32(36 + dataSize))
+ wav.append("WAVE".data(using: .ascii)!)
+ wav.append("fmt ".data(using: .ascii)!)
+ u32(16) // PCM fmt chunk size
+ u16(1) // audio format = PCM
+ u16(1) // channels
+ u32(UInt32(sampleRate))
+ u32(UInt32(sampleRate * 2)) // byte rate
+ u16(2) // block align
+ u16(16) // bits per sample
+ wav.append("data".data(using: .ascii)!)
+ u32(UInt32(dataSize))
+ wav.append(Data(count: dataSize))
+ return wav
+ }
/// In the car the controls have to reach us even if something else is
/// playing, so CarPlay overrides the other-audio guard.
@@ -106,18 +149,24 @@ enum NowPlayingPrimer {
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
- guard let url = URL(string: silentWav) else { return }
- let player = AVPlayer(url: url)
- player.allowsExternalPlayback = false
- player.volume = 0
- blipPlayer = player
- player.play()
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
- blipPlayer = nil
+ do {
+ let player = try AVAudioPlayer(data: makeSilentWav(durationMs: 600))
+ player.volume = 0
+ player.delegate = blipDelegate
+ blipPlayer = player
+ let started = player.play()
+ logSink?(
+ "[NowPlayingPrimer] claimed Now Playing for \"\(title)\" at "
+ + "\(Int(elapsed))s (paused, blip started=\(started))")
+ } catch {
+ logSink?("[NowPlayingPrimer] blip init failed: \(error.localizedDescription)")
+ return
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
+ if blipPlayer != nil {
+ logSink?("[NowPlayingPrimer] blip never finished - releasing")
+ blipPlayer = nil
+ }
}
-
- logSink?(
- "[NowPlayingPrimer] claimed Now Playing for \"\(title)\" at "
- + "\(Int(elapsed))s (paused)")
}
}
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 2cb0737d..5008b998 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -102,6 +102,15 @@ class HomeWidgetService {
}
return null;
});
+
+ // Native buffers its early log lines (Flutter keeps only one
+ // pre-handler message per channel); this tells AppDelegate the handler
+ // is live so it can flush them and switch to sending directly.
+ try {
+ await _widgetChannel.invokeMethod('logReady');
+ } catch (e) {
+ debugPrint('[WidgetDebug] logReady failed: $e');
+ }
}
final player = AudioPlayerService();