Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix iOS background queue, attempt 13 - replace + foreground resync

Barnabase115ab82348c
diff --git a/ios/Runner/IOSQueueAdvancer.swift b/ios/Runner/IOSQueueAdvancer.swift
index e3848fe0..f1c0bae9 100644
--- a/ios/Runner/IOSQueueAdvancer.swift
+++ b/ios/Runner/IOSQueueAdvancer.swift
@@ -4,12 +4,12 @@ import Foundation
import MediaPlayer
import UIKit
-/// 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.
+/// 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. The item
+/// is foreign to just_audio, so the Dart side re-syncs just_audio on the
+/// next foreground enter. MPNowPlayingInfoCenter is updated from Swift in
+/// the same step so the lock screen stays alive through the swap.
final class IOSQueueAdvancer: NSObject {
static let shared = IOSQueueAdvancer()
@@ -20,11 +20,12 @@ final class IOSQueueAdvancer: NSObject {
private weak var _justAudioPlayer: AVQueuePlayer?
private var _justAudioPlayerId: String?
- private var _nextTitle: String = ""
- private var _nextArtist: String = ""
- private var _nextDurationS: Double = 0
- private var _nextCoverPath: String?
- private var _nextStartS: Double = 0
+ 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 override init() {
super.init()
@@ -72,43 +73,112 @@ 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) ?? 0
let coverPath = args?["coverPath"] as? String
let startS = (args?["startS"] as? Double) ?? 0
- 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)
+ prepareNext(
+ urlStr: url,
+ isLocal: isLocal,
+ headers: headers,
+ title: title,
+ artist: artist,
+ durationS: duration,
+ coverPath: coverPath,
+ startS: startS,
+ completion: { ok in result(ok) }
+ )
case "commitAdvance":
let speed = (args?["speed"] as? Double) ?? 1.0
commitAdvance(speed: speed, completion: { ok in result(ok) })
- case "clear":
+ case "getPositionS":
queue.async { [weak self] in
- self?._nextTitle = ""
- self?._nextArtist = ""
- self?._nextDurationS = 0
- self?._nextCoverPath = nil
- self?._nextStartS = 0
+ let pos = self?._justAudioPlayer?.currentItem?.currentTime().seconds ?? 0
+ result(pos.isFinite ? pos : 0.0)
}
+
+ case "clear":
+ queue.async { [weak self] in self?.dropPrepared() }
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: 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] in
guard let self = self else { completion(false); return }
@@ -117,37 +187,35 @@ 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._nextStartS
- let queueCount = player.items().count
+ let startS = self._preparedStartS
DispatchQueue.main.async {
- 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 {
+ // Drop stale queued items so AVQueuePlayer can't race us into one.
+ 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
player.play()
player.rate = target
- }
+ })
} else {
- // 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
- }
+ player.play()
+ player.rate = target
}
self.queue.async {
- self.emit("[QueueAdvancer] commitAdvance done queueCount=\(queueCount) target=\(target)")
+ self.emit("[QueueAdvancer] commitAdvance done rate=\(player.rate) item=\(self._preparedTitle)")
+ self._preparedItem = nil
self.publishNowPlaying(rate: Double(target))
completion(true)
}
@@ -155,6 +223,15 @@ final class IOSQueueAdvancer: NSObject {
}
}
+ private func dropPrepared() {
+ _preparedItem = nil
+ _preparedTitle = ""
+ _preparedArtist = ""
+ _preparedDurationS = 0
+ _preparedCoverPath = nil
+ _preparedStartS = 0
+ }
+
private func activateSession() {
let session = AVAudioSession.sharedInstance()
do {
@@ -168,11 +245,11 @@ final class IOSQueueAdvancer: NSObject {
}
private func publishNowPlaying(rate: Double) {
- let title = _nextTitle
- let artist = _nextArtist
- let duration = _nextDurationS
- let coverPath = _nextCoverPath
- let elapsed = _nextStartS
+ let title = _preparedTitle
+ let artist = _preparedArtist
+ let duration = _preparedDurationS
+ let coverPath = _preparedCoverPath
+ let elapsed = _preparedStartS
guard !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.dart
index 7123c833..c1edf305 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1168,6 +1168,7 @@ class AudioPlayerService extends ChangeNotifier {
_currentBookTrackCount = 0;
_nextBookPreloading = false;
_preloadedNextBook = null;
+ _iosResyncPending = false;
if (Platform.isIOS) {
_queueAdvancerChannel.invokeMethod('clear').catchError((Object e) {
debugPrint('[QueueAdvance] clear failed: $e');
@@ -1263,6 +1264,16 @@ 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) {
@@ -1282,6 +1293,9 @@ 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,
@@ -1351,6 +1365,11 @@ class AudioPlayerService extends ChangeNotifier {
_autoQueueAdvancing = false;
}
+ // Set when native commitAdvance swaps in a foreign AVPlayerItem. just_audio
+ // sees _index = -1 from then on; we need to rebuild its source the next
+ // time the app is foregrounded so position and pause work normally.
+ bool _iosResyncPending = false;
+
Future<void> _iosAutoAdvanceKick() async {
final speed = _player?.speed ?? 1.0;
try {
@@ -1358,14 +1377,15 @@ class AudioPlayerService extends ChangeNotifier {
} catch (e) {
debugPrint('[QueueAdvance] setActive failed: $e');
}
- // Only run the native pause+play kick when backgrounded. In foreground the
- // AVQueuePlayer auto-advance already produces audio, and the kick would
- // glitch playback for no benefit.
if (_isBackgrounded) {
try {
- await _queueAdvancerChannel.invokeMethod<bool>('commitAdvance', {
+ final ok = await _queueAdvancerChannel.invokeMethod<bool>('commitAdvance', {
'speed': speed,
});
+ if (ok == true) {
+ _iosResyncPending = true;
+ debugPrint('[QueueAdvance] native commit succeeded, resync armed');
+ }
} catch (e) {
debugPrint('[QueueAdvance] commitAdvance failed: $e');
}
@@ -1380,6 +1400,41 @@ class AudioPlayerService extends ChangeNotifier {
});
}
+ Future<void> _iosForegroundResyncIfNeeded() async {
+ if (!_iosResyncPending) return;
+ _iosResyncPending = false;
+ final itemId = _currentItemId;
+ final api = _api;
+ if (itemId == null || api == null) {
+ debugPrint('[QueueAdvance] resync: missing item or api, skipping');
+ return;
+ }
+ double startS = 0;
+ try {
+ final pos = await _queueAdvancerChannel.invokeMethod<double>('getPositionS');
+ if (pos != null && pos > 0) startS = pos;
+ } catch (e) {
+ debugPrint('[QueueAdvance] getPositionS failed: $e');
+ }
+ debugPrint('[QueueAdvance] Resyncing just_audio for $itemId at ${startS.toStringAsFixed(1)}s');
+ try {
+ await playItem(
+ api: api,
+ itemId: itemId,
+ title: _currentTitle ?? '',
+ author: _currentAuthor ?? '',
+ coverUrl: _currentCoverUrl,
+ totalDuration: _totalDuration,
+ chapters: _chapters,
+ startTime: startS,
+ forceStartTime: true,
+ episodeId: _currentEpisodeId,
+ );
+ } catch (e) {
+ debugPrint('[QueueAdvance] resync playItem failed: $e');
+ }
+ }
+
Future<void> _primeNowPlaying({
required String title,
required String artist,
@@ -1855,6 +1910,9 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[ClickDebug] App foregrounded: sincePrevPauseMs=$sincePrevPauseMs, '
'sincePrevPlayMs=$sincePrevPlayMs, aaDisconnectSuspect=$aaDisconnectSuspect');
service._positionSyncFailures = 0; // retry on foreground
+ if (Platform.isIOS && service._iosResyncPending) {
+ unawaited(service._iosForegroundResyncIfNeeded());
+ }
if (!service.hasBook) return;
final sessionAlive = service._playbackSessionId != null;
debugPrint('[MediaSession] Foregrounded - refreshing (playing=${service.isPlaying}, session=$sessionAlive, item=${service._currentItemId})');
diff --git a/pubspec.yaml b/pubspec.yaml
index 7ffd06f1..e9e79ed9 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.91+148
+version: 1.8.91+149
environment:
sdk: '>=3.1.0 <4.0.0'