A cross platform Audiobookshelf client for Android and iOS
Dart
Fix iOS background queue, attempt 12 - advance instead of replace
Barnabasda822bfade35
diff --git a/ios/Runner/IOSQueueAdvancer.swift b/ios/Runner/IOSQueueAdvancer.swiftindex c8e75b58..e3848fe0 100644--- a/ios/Runner/IOSQueueAdvancer.swift+++ b/ios/Runner/IOSQueueAdvancer.swift@@ -4,11 +4,12 @@ import Foundationimport MediaPlayerimport UIKit-/// Drives the cross-book audio transition in queue mode. Builds a fresh-/// AVPlayerItem for the next book and swaps it into the AVQueuePlayer that-/// just_audio owns via replaceCurrentItem + explicit play + rate. Updates-/// MPNowPlayingInfoCenter from Swift so the lock screen never blanks out-/// during the swap.+/// Drives the cross-book audio transition in queue mode. The next book is+/// already queued in just_audio's AVQueuePlayer via its pre-buffer; this+/// class calls advanceToNextItem at the moment of transition, then forces+/// play + rate so iOS doesn't drop the background audio route. Now Playing+/// is published from Swift in the same step so the lock screen stays alive+/// through the swap.final class IOSQueueAdvancer: NSObject {static let shared = IOSQueueAdvancer()@@ -19,14 +20,11 @@ final class IOSQueueAdvancer: NSObject {private weak var _justAudioPlayer: AVQueuePlayer?private var _justAudioPlayerId: String?- private var _preparedItem: AVPlayerItem?- private var _preparedTitle: String = ""- private var _preparedArtist: String = ""- private var _preparedDurationS: Double = 0- private var _preparedCoverPath: String?- private var _preparedStartS: Double = 0-- private var _flutterChannel: FlutterMethodChannel?+ private var _nextTitle: String = ""+ private var _nextArtist: String = ""+ private var _nextDurationS: Double = 0+ private var _nextCoverPath: String?+ private var _nextStartS: Double = 0private override init() {super.init()@@ -67,7 +65,6 @@ final class IOSQueueAdvancer: NSObject {channel.setMethodCallHandler { [weak self] call, result inself?.handle(call, result: result)}- _flutterChannel = channelemit("[QueueAdvancer] channel registered")}@@ -75,106 +72,43 @@ final class IOSQueueAdvancer: NSObject {let args = call.arguments as? [String: Any]switch call.method {case "prepareNext":- let url = (args?["url"] as? String) ?? ""- let isLocal = (args?["isLocal"] as? Bool) ?? false- let headers = (args?["headers"] as? [String: String]) ?? [:]let title = (args?["title"] as? String) ?? ""let artist = (args?["artist"] as? String) ?? ""let duration = (args?["durationS"] as? Double) ?? 0let coverPath = args?["coverPath"] as? Stringlet startS = (args?["startS"] as? Double) ?? 0- prepareNext(- urlStr: url,- isLocal: isLocal,- headers: headers,- title: title,- artist: artist,- durationS: duration,- coverPath: coverPath,- startS: startS,- completion: { ok in result(ok) }- )+ queue.async { [weak self] in+ self?._nextTitle = title+ self?._nextArtist = artist+ self?._nextDurationS = duration+ self?._nextCoverPath = coverPath+ self?._nextStartS = startS+ self?.emit("[QueueAdvancer] prepared \(title) start=\(startS)")+ }+ result(true)case "commitAdvance":let speed = (args?["speed"] as? Double) ?? 1.0commitAdvance(speed: speed, completion: { ok in result(ok) })case "clear":- queue.async { [weak self] in self?.dropPrepared() }+ queue.async { [weak self] in+ self?._nextTitle = ""+ self?._nextArtist = ""+ self?._nextDurationS = 0+ self?._nextCoverPath = nil+ self?._nextStartS = 0+ }result(true)case "isReady":result(_justAudioPlayer != nil)- case "isPrepared":- result(_preparedItem != nil)-default:result(FlutterMethodNotImplemented)}}- private func prepareNext(- urlStr: String,- isLocal: Bool,- headers: [String: String],- title: String,- artist: String,- durationS: Double,- coverPath: String?,- startS: Double,- completion: @escaping (Bool) -> Void- ) {- queue.async { [weak self] in- guard let self = self else { completion(false); return }- guard !urlStr.isEmpty else {- self.emit("[QueueAdvancer] prepareNext: empty url")- completion(false)- return- }- let url: URL?- if isLocal {- let path = urlStr.hasPrefix("file://") ? String(urlStr.dropFirst(7)) : urlStr- url = URL(fileURLWithPath: path)- } else {- url = URL(string: urlStr)- }- guard let assetUrl = url else {- self.emit("[QueueAdvancer] prepareNext: bad url \(urlStr)")- completion(false)- return- }-- var options: [String: Any] = [:]- if !headers.isEmpty {- options["AVURLAssetHTTPHeaderFieldsKey"] = headers- }- let asset = AVURLAsset(url: assetUrl, options: options)- asset.loadValuesAsynchronously(forKeys: ["tracks", "duration"]) { [weak self] in- guard let self = self else { return }- self.queue.async {- var trackErr: NSError?- let status = asset.statusOfValue(forKey: "tracks", error: &trackErr)- if status != .loaded {- self.emit("[QueueAdvancer] prepareNext: asset tracks not loaded status=\(status.rawValue) err=\(trackErr?.localizedDescription ?? "nil")")- completion(false)- return- }- let item = AVPlayerItem(asset: asset)- item.audioTimePitchAlgorithm = .timeDomain- self._preparedItem = item- self._preparedTitle = title- self._preparedArtist = artist- self._preparedDurationS = durationS- self._preparedCoverPath = coverPath- self._preparedStartS = startS- self.emit("[QueueAdvancer] prepared \(title) (\(assetUrl.lastPathComponent)) start=\(startS)")- completion(true)- }- }- }- }-private func commitAdvance(speed: Double, completion: @escaping (Bool) -> Void) {queue.async { [weak self] inguard let self = self else { completion(false); return }@@ -183,50 +117,44 @@ final class IOSQueueAdvancer: NSObject {completion(false)return}- guard let item = self._preparedItem else {- self.emit("[QueueAdvancer] commitAdvance: nothing prepared")- completion(false)- return- }-self.activateSession()self.publishNowPlaying(rate: speed)let target = Float(speed > 0 ? speed : 1.0)- let startS = self._preparedStartS+ let startS = self._nextStartS+ let queueCount = player.items().countDispatchQueue.main.async {- // Clear other queued items so a stale auto-advance can't race us.- for queued in player.items() where queued !== item {- player.remove(queued)- }- player.replaceCurrentItem(with: item)- if startS > 0 {- item.seek(to: CMTime(seconds: startS, preferredTimescale: 1000), completionHandler: { _ in+ if queueCount >= 2 {+ // Next IndexedPlayerItem is queued by just_audio's pre-buffer.+ // Advance manually so we control the moment of the swap.+ player.advanceToNextItem()+ if startS > 0, let item = player.currentItem {+ item.seek(to: CMTime(seconds: startS, preferredTimescale: 1000), completionHandler: { _ in+ player.play()+ player.rate = target+ })+ } else {player.play()player.rate = target- })+ }} else {- player.play()- player.rate = target+ // AVQueuePlayer already auto-advanced (or there's only one item).+ // Pause briefly then play to force the audio engine to re-emit.+ player.pause()+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.04) {+ player.play()+ player.rate = target+ }}self.queue.async {- self.emit("[QueueAdvancer] commitAdvance done rate=\(player.rate) item=\(self._preparedTitle)")- self._preparedItem = nil+ self.emit("[QueueAdvancer] commitAdvance done queueCount=\(queueCount) target=\(target)")+ self.publishNowPlaying(rate: Double(target))completion(true)}}}}- private func dropPrepared() {- _preparedItem = nil- _preparedTitle = ""- _preparedArtist = ""- _preparedDurationS = 0- _preparedCoverPath = nil- _preparedStartS = 0- }-private func activateSession() {let session = AVAudioSession.sharedInstance()do {@@ -240,11 +168,11 @@ final class IOSQueueAdvancer: NSObject {}private func publishNowPlaying(rate: Double) {- let title = _preparedTitle- let artist = _preparedArtist- let duration = _preparedDurationS- let coverPath = _preparedCoverPath- let elapsed = _preparedStartS+ let title = _nextTitle+ let artist = _nextArtist+ let duration = _nextDurationS+ let coverPath = _nextCoverPath+ let elapsed = _nextStartSguard !title.isEmpty else { return }var info: [String: Any] = [MPMediaItemPropertyTitle: title,diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 76470676..7123c833 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -64,20 +64,31 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {// Strip the call sites + the channel once #243 is closed.static const _absorbDiagChannel = MethodChannel('com.absorb.audio_diag');- static Future<void> _logAbsorbDiag(String tag) async {- if (!Platform.isAndroid) return;+ /// Fetch the raw diag snapshot from the Java side. Returns null on iOS or+ /// when the channel is unavailable. Used by click() to also read the+ /// keycode for intent disambiguation, not just to log it.+ static Future<Map<String, dynamic>?> _absorbDiagSnapshot() async {+ if (!Platform.isAndroid) return null;try {- final snap = await _absorbDiagChannel.invokeMapMethod<String, dynamic>('snapshot');- if (snap == null) return;- debugPrint('[AbsorbDiag] $tag: '- 'keyCode=${snap['lastKeyCode']} keyAgeMs=${snap['lastKeyAgeMs']} '- 'lastPlayCaller=${snap['lastPlayCaller']} playAgeMs=${snap['lastPlayCallerAgeMs']} '- 'lastPauseCaller=${snap['lastPauseCaller']} pauseAgeMs=${snap['lastPauseCallerAgeMs']}');+ return await _absorbDiagChannel.invokeMapMethod<String, dynamic>('snapshot');} catch (e) {- debugPrint('[AbsorbDiag] $tag: snapshot failed: $e');+ debugPrint('[AbsorbDiag] snapshot failed: $e');+ return null;}}+ static void _logAbsorbDiagFromSnapshot(String tag, Map<String, dynamic>? snap) {+ if (snap == null) return;+ debugPrint('[AbsorbDiag] $tag: '+ 'keyCode=${snap['lastKeyCode']} keyAgeMs=${snap['lastKeyAgeMs']} '+ 'lastPlayCaller=${snap['lastPlayCaller']} playAgeMs=${snap['lastPlayCallerAgeMs']} '+ 'lastPauseCaller=${snap['lastPauseCaller']} pauseAgeMs=${snap['lastPauseCallerAgeMs']}');+ }++ static Future<void> _logAbsorbDiag(String tag) async {+ _logAbsorbDiagFromSnapshot(tag, await _absorbDiagSnapshot());+ }+/// Force-push current PlaybackState so the notification picks up/// new chapter-relative position immediately (e.g. on chapter change).void refreshPlaybackState() {@@ -409,6 +420,12 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {int _clickCount = 0;DateTime? _hardwareButtonTime; // cooldown after hardware next/prevDateTime? _noisyPauseAt; // suppress clicks for a window after BT disconnect+ // Keycode of the media button event that arrived at the most recent click().+ // Read from the [AbsorbDiag] snapshot at click arrival and consumed by the+ // 400ms resolver to honor PAUSE/PLAY intent instead of blindly toggling -+ // Android Auto sends KEYCODE_MEDIA_PAUSE when the user switches to Radio,+ // and the old toggle path bounced it back as a phantom resume (GH #243).+ int? _lastClickKeyCode;// True while the click resolver is synchronously calling pause()/play().// pause() uses this to skip stamping _noisyPauseAt for click-driven pauses,// so legit user pause-then-play flows are not blocked by the disconnect guard.@@ -484,7 +501,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {@overrideFuture<void> click([MediaButton button = MediaButton.media]) async {debugPrint('[Handler] click(button=$button) count=${_clickCount + 1} playing=${_player.playing}');- await _logAbsorbDiag('click');+ final diagSnap = await _absorbDiagSnapshot();+ _logAbsorbDiagFromSnapshot('click', diagSnap);// Pre-fetch BT-route state so the snapshot can fill in the AA-disconnect// heuristic and the suppression branch below has a value to test against.final btNow = await AudioPlayerService._isBluetoothAudioConnected();@@ -547,6 +565,19 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {}}+ // Stash the keycode for the resolver if it belongs to this click. Only+ // do this for clicks that actually count - early-return guards above+ // skip the stash so they can't poison the keycode of a click that does+ // make it to the resolver. 500ms cap is a safety margin; typical+ // keyAgeMs from the Java side is 0-2ms.+ if (diagSnap != null) {+ final age = diagSnap['lastKeyAgeMs'];+ final kc = diagSnap['lastKeyCode'];+ if (age is int && age >= 0 && age < 500 && kc is int && kc != 0) {+ _lastClickKeyCode = kc;+ }+ }+_clickCount++;_clickTimer?.cancel();_clickTimer = Timer(const Duration(milliseconds: 400), () async {@@ -559,7 +590,33 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {case 1:_inClickResolver = true;try {- if (_player.playing) {+ // Honor the actual keycode the system dispatched when we can.+ // audio_service collapses MEDIA_PLAY / MEDIA_PAUSE / PLAY_PAUSE /+ // HEADSETHOOK all into MediaButton.media, but Android Auto sends+ // MEDIA_PAUSE specifically when the user switches to another media+ // app - blindly toggling there resumes us right after we paused+ // (GH #243). For the unambiguous play / pause keycodes, follow the+ // intent. PLAY_PAUSE / HEADSETHOOK / unknown / stale stay as+ // toggles so single-button BT remotes keep working.+ const keycodeMediaPlay = 126;+ const keycodeMediaPause = 127;+ final kc = _lastClickKeyCode;+ _lastClickKeyCode = null;+ if (kc == keycodeMediaPause) {+ if (_player.playing) {+ debugPrint('[Handler] → single press (MEDIA_PAUSE) → PAUSE');+ await pause();+ } else {+ debugPrint('[Handler] → single press (MEDIA_PAUSE while paused) → no-op (suppressed phantom toggle to PLAY)');+ }+ } else if (kc == keycodeMediaPlay) {+ if (!_player.playing) {+ debugPrint('[Handler] → single press (MEDIA_PLAY) → PLAY');+ await play();+ } else {+ debugPrint('[Handler] → single press (MEDIA_PLAY while playing) → no-op');+ }+ } else if (_player.playing) {debugPrint('[Handler] → single press → PAUSE');await pause();} else {@@ -1206,16 +1263,6 @@ class AudioPlayerService extends ChangeNotifier {List<dynamic>? audioTracks,Map<String, String>? audioHeaders) async {try {- String? url;- bool isLocal = false;- if (localPaths != null && localPaths.isNotEmpty) {- url = localPaths.first;- isLocal = true;- } else if (audioTracks != null && audioTracks.isNotEmpty) {- url = (audioTracks.first as Map<String, dynamic>)['url'] as String?;- }- if (url == null || url.isEmpty) return false;-String? coverPath;final itemId = next['itemId'] as String?;if (itemId != null) {@@ -1223,7 +1270,6 @@ class AudioPlayerService extends ChangeNotifier {if (local != null && local.isNotEmpty) coverPath = local;}- // Resume position for the next book.double startS = 0;if (itemId != null) {final progressKey = next['episodeId'] != null@@ -1236,9 +1282,6 @@ class AudioPlayerService extends ChangeNotifier {}final ok = await _queueAdvancerChannel.invokeMethod<bool>('prepareNext', {- 'url': url,- 'isLocal': isLocal,- 'headers': audioHeaders ?? <String, String>{},'title': next['title'] ?? '','artist': next['author'] ?? '','durationS': (next['duration'] as num?)?.toDouble() ?? 0,diff --git a/pubspec.yaml b/pubspec.yamlindex 4b633845..9d054cf7 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: An Audiobookshelf Clientpublish_to: 'none'-version: 1.8.91+146+version: 1.8.91+147environment:sdk: '>=3.1.0 <4.0.0'