A cross platform Audiobookshelf client for Android and iOS
Dart
Nothing loads or claims the lock screen anymore until you actually press play
Barnabasd92114f86aef
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex e75fb696..2cce577d 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -24,7 +24,6 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlprivate var pendingNativeLogs: [(Double, String)] = []private var dartLogReady = falseprivate let launchUptime = ProcessInfo.processInfo.systemUptime- private var hasScheduledNowPlayingPrime = falseoverride func application(_ application: UIApplication,@@ -72,25 +71,6 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlNowPlayingPrimer.logSink = { [weak self] line inself?.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. 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// reports "EQ on, this book has no sound" we can see the post-decodediff --git a/ios/Runner/NowPlayingPrimer.swift b/ios/Runner/NowPlayingPrimer.swiftindex 4c311639..a4aab13d 100644--- a/ios/Runner/NowPlayingPrimer.swift+++ b/ios/Runner/NowPlayingPrimer.swift@@ -1,33 +1,29 @@import AVFoundation-import MediaPlayer-import UIKit-/// Claims the iOS Now Playing slot for Absorb, so a headset play button reaches-/// this app rather than whatever played last.+/// Takes the iOS Now Playing slot back for Absorb mid-session, so headset+/// controls keep reaching this app after something else played.////// iOS hands remote control commands to whichever app it considers "now/// playing", and an app only becomes a candidate once it has an active audio-/// session AND has actually rendered audio. Absorb used to do neither until the-/// user pressed play inside the app, which is why a headset press after a cold-/// launch went nowhere - or worse, to another device on a multipoint headset.-/// Users reported having to pull the phone out, open Absorb and press play-/// before their headphones would work at all.-///-/// Two parts, both needed:-/// - activate the session, which the app deliberately avoided at launch because-/// it interrupts other apps' audio. That only happens when something else is-/// actually playing, so the guard below is what makes it safe rather than-/// skipping it entirely.+/// session AND has actually rendered audio. So the reclaim is two parts, both+/// needed:+/// - activate the session, guarded so it never interrupts another app that is+/// actually playing (CarPlay excepted - in the car the controls must reach+/// us regardless)./// - render half a second of silence, because an active session that never/// produces audio does not reliably win the slot. Build 249 activated and/// published metadata without rendering, and lost the slot twice in the/// field; 251 added real samples and held it. Anything that wants the slot/// back has to come through here for that reason.+///+/// This used to also claim the slot at every launch from the app-group stash,+/// so a headset press worked before the user ever pressed play in the app -+/// that never worked reliably in the field and put a phantom paused book on+/// the lock screen at every app open, so it was removed. Until the user+/// plays, Absorb makes no claim.enum NowPlayingPrimer {static var logSink: ((String) -> Void)?- private static let appGroup = "group.com.barnabas.absorb"-/// The silent player has to outlive this function or it deallocates before/// the blip finishes and the claim never lands.private static var blipPlayer: AVAudioPlayer?@@ -86,14 +82,6 @@ enum NowPlayingPrimer {session.currentRoute.outputs.contains { $0.portType == .carAudio }}- /// Launch: publish what the last-played book was and take the slot for it.- /// Reads the app-group stash the widget already keeps up to date, so this- /// needs neither the Flutter engine nor the network - it runs before either- /// is ready.- static func primeAtLaunch() {- _ = claim(reason: "launch", publishFromStash: true)- }-/// Take the slot back mid-session, after something else may have won it: the/// user opened another app that played audio, an interruption came and went/// while Absorb sat suspended, or the headphones were stowed. Metadata is@@ -103,27 +91,27 @@ enum NowPlayingPrimer {/// (rendered=)" line is the ground truth for whether it landed.@discardableResultstatic func reclaim(reason: String) -> Bool {- return claim(reason: reason, publishFromStash: false)+ return claim(reason: reason)}@discardableResult- private static func claim(reason: String, publishFromStash: Bool) -> Bool {+ private static func claim(reason: String) -> Bool {let session = AVAudioSession.sharedInstance()// A blip already on its way is the same claim. Starting a second one// replaces the player and deallocates the first mid-render, so neither- // lands - and at launch the scene-activate prime and the first foreground- // reassert can arrive within a few hundred milliseconds of each other.+ // lands - reasserts from different triggers can arrive within a few+ // hundred milliseconds of each other.if blipPlayer != nil {logSink?("[NowPlayingPrimer] \(reason): skipped, a claim is already in flight")return false}// Our own engine is already playing (a headset press launched the process- // and the native core streamed from the stash before the scene activated).+ // and the native core streamed from the stash before Flutter came up).// The other-audio check below can't see it - isOtherAudioPlaying only- // reports OTHER apps - and stamping the stash's paused, stale info over- // live audio put a frozen tile on the lock screen in the field.+ // reports OTHER apps - and it already owns the slot; blipping over live+ // audio has nothing to win.if AbsorbAudioEngine.shared.isPlaying {logSink?("[NowPlayingPrimer] \(reason): skipped, our own engine is playing")return false@@ -141,24 +129,6 @@ enum NowPlayingPrimer {return false}- let defaults = UserDefaults(suiteName: appGroup)- var title = ""- var elapsed: Double = 0-- if publishFromStash {- guard let itemId = defaults?.string(forKey: "np_item_id"), !itemId.isEmpty else {- logSink?("[NowPlayingPrimer] skipped, nothing has been played on this device yet")- return false- }-- // Launched by the widget to start playing, so audio is already on its- // way. Priming now would stamp a paused, stale state over the real one.- if defaults?.bool(forKey: "widget_is_playing") == true {- logSink?("[NowPlayingPrimer] skipped, playback is already running")- return false- }- }-do {// Re-setting a category that already matches makes iOS emit a route// change, which is log noise on every foreground reassert.@@ -172,45 +142,13 @@ enum NowPlayingPrimer {return false}- if publishFromStash {- title = defaults?.string(forKey: "np_title")- ?? defaults?.string(forKey: "widget_title") ?? ""- let author = defaults?.string(forKey: "np_author")- ?? defaults?.string(forKey: "widget_author") ?? ""- let coverPath = defaults?.string(forKey: "np_cover_path")- ?? defaults?.string(forKey: "widget_cover_path")- elapsed = defaults?.double(forKey: "np_position_s") ?? 0- let duration = defaults?.double(forKey: "np_total_s") ?? 0-- var info: [String: Any] = [- MPMediaItemPropertyTitle: title,- MPMediaItemPropertyArtist: author,- MPNowPlayingInfoPropertyElapsedPlaybackTime: elapsed,- // Paused: nothing is playing yet, we are only claiming the controls.- MPNowPlayingInfoPropertyPlaybackRate: 0.0,- MPNowPlayingInfoPropertyDefaultPlaybackRate: 1.0,- MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue,- MPMediaItemPropertyMediaType: MPMediaType.audioBook.rawValue,- ]- if duration > 0 {- info[MPMediaItemPropertyPlaybackDuration] = duration- }- if let coverPath, let img = UIImage(contentsOfFile: coverPath) {- info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: img.size) { _ in img }- }- MPNowPlayingInfoCenter.default().nowPlayingInfo = info- }-do {let player = try AVAudioPlayer(data: makeSilentWav(durationMs: 600))player.volume = 0player.delegate = blipDelegateblipPlayer = playerlet started = player.play()- let opening = publishFromStash- ? "claimed Now Playing for \"\(title)\" at \(Int(elapsed))s (paused"- : "reclaimed Now Playing (\(reason)"- logSink?("[NowPlayingPrimer] \(opening), blip started=\(started))")+ logSink?("[NowPlayingPrimer] reclaimed Now Playing (\(reason), blip started=\(started))")DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {if blipPlayer != nil {logSink?("[NowPlayingPrimer] blip never finished - releasing")diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 93d04046..c458cc08 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -2265,13 +2265,12 @@ class AudioPlayerService extends ChangeNotifier {// get here before the native core has even LOADED the engine (a field// log had this check lose by two milliseconds), and a stream then// buffers for a while before isPlaying flips. Deciding on the first- // read sent a streamed relaunch down the hot-load path (which skips- // streamed books) and left Dart bookless under live audio. So poll: a- // press-loaded engine shows up within the first second, and once it is- // loaded, give the buffer the rest of the budget. On a normal launch- // nothing ever loads and this waits out the budget before the- // hot-load - harmless, since the primer has the lock screen and the- // command center routes any early press to the cold-start restore.+ // read left Dart bookless under live audio. So poll: a press-loaded+ // engine shows up within the first second, and once it is loaded, give+ // the buffer the rest of the budget. On a normal launch nothing ever+ // loads and this waits out the budget then does nothing - harmless,+ // since the primer has the lock screen and the command center routes+ // any early press to the cold-start restore.var waited = 0;while ((state == null || !state.isLoaded || !state.isPlaying) &&waited < 4000) {@@ -2292,12 +2291,11 @@ class AudioPlayerService extends ChangeNotifier {if (restore != null) await restore();return;}- // Idle engine: load the last played item paused instead, so a headset- // press in the first seconds of a cold start has a live target - the- // native core defers presses to Flutter the moment its heartbeat- // exists, and with nothing loaded that press used to land on neither- // layer.- await HomeWidgetService().loadLastPlayedPaused();+ // Idle engine: leave the player empty. The book only loads when the+ // user actually plays - an early headset press still works because the+ // handler routes play-with-nothing-loaded to the cold-start restore.+ // (This used to load the last played book paused as a press target,+ // which put an unasked-for book in the player on every launch.)} catch (e) {debugPrint('[Player] boot engine adopt failed: $e');}diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex b7bdae06..3ade5955 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -541,37 +541,6 @@ class HomeWidgetService {);}- /// iOS cold start: load the last played item into the player paused, so a- /// headset press always has a live target. Without this, a press arriving- /// after Dart boots gets deferred by the native core to an audio_service- /// with nothing loaded, and lands on neither layer. Downloaded items only- /// (a stream would need a server session just to sit paused); no session- /// starts until a real play.- Future<void> loadLastPlayedPaused() async {- final player = AudioPlayerService();- if (player.hasBook) return;- final prefs = await SharedPreferences.getInstance();- final itemId = prefs.getString('widget_item_id');- if (itemId == null) return;- final api = _apiFromPrefs(prefs);- if (api == null) return;- final episodeId = prefs.getString('widget_episode_id');- try {- final ok = await _resumeFromDownloadRecord(- player,- api,- itemId,- episodeId,- loadOnly: true,- );- debugPrint(- '[HomeWidget] launch load-paused: ${ok ? "loaded $itemId" : "last played not downloaded - skipped"}',- );- } catch (e) {- debugPrint('[HomeWidget] launch load-paused failed: $e');- }- }-Future<bool> _resumeFromDownloadRecord(AudioPlayerService player,ApiService api,