Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Run all iOS playback through one engine so the widget can't start a second stream

Barnabas2b6bb39944c8
diff --git a/ios/Runner/AbsorbPlayerCore.swift b/ios/Runner/AbsorbPlayerCore.swift
index f99eafaa..9a2a3003 100644
--- a/ios/Runner/AbsorbPlayerCore.swift
+++ b/ios/Runner/AbsorbPlayerCore.swift
@@ -4,10 +4,13 @@ import Foundation
import MediaPlayer
import UIKit
-/// Native player core for iOS. Drives downloaded and streaming audiobooks
-/// via AVPlayer when Flutter isn't alive, exposes lock-screen / Control
-/// Center / CarPlay metadata, handles remote commands, and pushes progress
-/// directly to ABS so the server stays in sync during widget-only sessions.
+/// Controller that drives audiobook playback while Flutter is suspended.
+///
+/// It does NOT own an AVPlayer. All audio runs through the single process-wide
+/// `AbsorbAudioEngine.shared`, which also serves in-app playback and survives
+/// Flutter suspension. So a widget play just resumes the already-loaded engine
+/// rather than starting a second AVPlayer - that's what made bug #285 possible
+/// (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
@@ -21,21 +24,14 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
private let queue = DispatchQueue(label: "com.barnabas.absorb.nativecore")
- private var _player: AVPlayer?
+ // Bookkeeping for server push + Now Playing. The actual audio state lives in
+ // AbsorbAudioEngine.shared; these just mirror what book we last targeted.
private var _currentItemId: String?
private var _currentEpisodeId: String?
- // Multi-track state
- private var _trackUrls: [URL] = []
- private var _trackHeaders: [String: String] = [:]
- private var _trackOffsets: [Double] = [0]
- private var _trackIndex: Int = 0
-
- private var _periodicObserver: Any?
- private var _itemEndObserver: NSObjectProtocol?
private var _commandsConfigured = false
- // Server sync timer (separate from periodic position observer)
+ // Server sync timer (separate from the engine's position observer).
private var _serverSyncTimer: Timer?
private static let serverSyncIntervalSec: TimeInterval = 60.0
@@ -53,17 +49,15 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.emit("[NativeCore] play(): Flutter is alive, bailing")
return
}
- self.ensureLoaded()
- guard let p = self._player else {
- self.emit("[NativeCore] play(): no player loaded")
+ guard self.ensureLoaded() else {
+ self.emit("[NativeCore] play(): no engine source loaded")
return
}
self.activateAudioSession()
- p.play()
- self.applySpeed(to: p)
- self.emit("[NativeCore] play(): rate=\(p.rate) trackIdx=\(self._trackIndex)")
+ AbsorbAudioEngine.shared.play()
+ self.emit("[NativeCore] play(): global=\(self.globalPosition())s")
self.startServerSyncTimer()
- self.updateNowPlayingInfo(rate: Double(p.rate))
+ self.updateNowPlayingInfo(rate: Double(self.currentSpeed()))
}
}
@@ -74,11 +68,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.emit("[NativeCore] pause(): Flutter is alive, bailing")
return
}
- guard let p = self._player else {
- self.emit("[NativeCore] pause(): no player")
- return
- }
- p.pause()
+ AbsorbAudioEngine.shared.pause()
self.emit("[NativeCore] pause(): pos=\(self.globalPosition())s")
self.savePosition()
self.pushProgressToServer()
@@ -94,13 +84,12 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.emit("[NativeCore] toggle(): Flutter is alive, bailing")
return
}
- self.ensureLoaded()
- guard let p = self._player else {
- self.emit("[NativeCore] toggle(): no player loaded")
+ guard self.ensureLoaded() else {
+ self.emit("[NativeCore] toggle(): no engine source loaded")
return
}
- if p.rate > 0 {
- p.pause()
+ if AbsorbAudioEngine.shared.isPlaying {
+ AbsorbAudioEngine.shared.pause()
self.emit("[NativeCore] toggle(): paused at \(self.globalPosition())s")
self.savePosition()
self.pushProgressToServer()
@@ -108,11 +97,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.updateNowPlayingInfo(rate: 0)
} else {
self.activateAudioSession()
- p.play()
- self.applySpeed(to: p)
- self.emit("[NativeCore] toggle(): playing rate=\(p.rate) global=\(self.globalPosition())s")
+ AbsorbAudioEngine.shared.play()
+ self.emit("[NativeCore] toggle(): playing global=\(self.globalPosition())s")
self.startServerSyncTimer()
- self.updateNowPlayingInfo(rate: Double(p.rate))
+ self.updateNowPlayingInfo(rate: Double(self.currentSpeed()))
}
}
}
@@ -124,6 +112,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.emit("[NativeCore] skipForward(\(seconds)): Flutter is alive, bailing")
return
}
+ guard self.ensureLoaded() else { return }
let now = self.globalPosition()
let dur = self.totalDuration()
let target = min(dur > 0 ? dur : .greatestFiniteMagnitude, now + Double(seconds))
@@ -139,6 +128,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self.emit("[NativeCore] skipBackward(\(seconds)): Flutter is alive, bailing")
return
}
+ guard self.ensureLoaded() else { return }
let now = self.globalPosition()
let target = max(0, now - Double(seconds))
self.emit("[NativeCore] skipBackward(\(seconds)s): \(now)s -> \(target)s")
@@ -164,17 +154,32 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
// MARK: - State plumbing
- /// Build the URL list, track offsets, headers, and active-track index
- /// from app group state. Loads the AVPlayer to the right starting track.
- private func ensureLoaded() {
+ /// Make sure the shared engine holds the book the app group points at.
+ ///
+ /// Warm case: the engine is already on this book (`currentItemId` matches) -
+ /// do nothing and adopt its live position. This is the common widget-resume
+ /// path and is what keeps a single stream.
+ ///
+ /// Cold case: the engine has nothing (or a different book) loaded - build
+ /// the source from app-group state and load it at the saved position.
+ ///
+ /// Returns false only when there's no playable source at all.
+ @discardableResult
+ private func ensureLoaded() -> Bool {
let defaults = UserDefaults(suiteName: Self.appGroup)
guard let itemId = defaults?.string(forKey: "np_item_id") else {
emit("[NativeCore] ensureLoaded: no np_item_id in app group")
- return
+ return false
}
let episodeId = defaults?.string(forKey: "np_episode_id")
- if _player != nil && itemId == _currentItemId && episodeId == _currentEpisodeId {
- return
+
+ // Engine already holds this exact book: adopt it, no reload.
+ if AbsorbAudioEngine.shared.currentItemId == itemId, AbsorbAudioEngine.shared.isLoaded {
+ _currentItemId = itemId
+ _currentEpisodeId = episodeId
+ configureRemoteCommandsIfNeeded()
+ emit("[NativeCore] ensureLoaded: engine already on \(itemId), adopting live playback")
+ return true
}
let isDownloaded = defaults?.bool(forKey: "np_is_downloaded") ?? false
@@ -205,17 +210,16 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
emit("[NativeCore] ensureLoaded: \(itemId) streaming, \(urls.count) tracks, \(headers.count) custom headers")
} else {
emit("[NativeCore] ensureLoaded: no playable source for \(itemId)")
- return
+ return false
}
if urls.isEmpty {
emit("[NativeCore] ensureLoaded: source list empty after filtering for \(itemId)")
- return
+ return false
}
- // Track offsets (cumulative, length = urls.count + 1). Fall back to
- // [0, +inf] if the stash is missing or shorter than expected so we
- // still play track 0.
+ // Track offsets (cumulative, length = urls.count + 1). The engine
+ // normalizes/fills in a fallback if the stash is missing or short.
var offsets: [Double] = [0]
if let offsetsJson = defaults?.string(forKey: "np_track_offsets_json"),
let offsetsData = offsetsJson.data(using: .utf8),
@@ -223,173 +227,65 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
raw.count >= urls.count + 1 {
offsets = raw.map { $0.doubleValue }
} else {
- // Fallback: assume single track, or unknown durations -> can't seek
- // across tracks correctly but at least track 0 plays.
- offsets = [0]
- for _ in urls { offsets.append(.greatestFiniteMagnitude) }
- emit("[NativeCore] ensureLoaded: track offsets unknown, falling back to single-track logic")
+ offsets = []
+ emit("[NativeCore] ensureLoaded: track offsets unknown, engine will fall back")
}
let savedPos = defaults?.double(forKey: "np_position_s") ?? 0
- let startTrackIndex = trackIndexForGlobal(savedPos, offsets: offsets)
- let localStart = savedPos - offsets[startTrackIndex]
+ let totalS = defaults?.double(forKey: "np_total_s") ?? 0
+ let speed = defaults?.double(forKey: "np_speed") ?? 1.0
+ // Mirrored from the default prefs into the app group by home_widget_service
+ // (eq_enabled itself isn't in the group suite).
+ let eqEnabled = defaults?.bool(forKey: "np_eq_enabled") ?? false
- _trackUrls = urls
- _trackHeaders = headers
- _trackOffsets = offsets
- _trackIndex = startTrackIndex
_currentItemId = itemId
_currentEpisodeId = episodeId
- let player = AVPlayer()
- _player = player
- loadCurrentTrack(seekTo: localStart)
+ let tracks = urls.map { (url: $0, headers: headers) }
+ AbsorbAudioEngine.shared.load(
+ tracks: tracks,
+ trackOffsets: offsets,
+ startPositionS: savedPos,
+ totalDurationS: totalS,
+ speed: Float(speed > 0 ? speed : 1.0),
+ volume: 1.0,
+ eqEnabled: eqEnabled,
+ itemId: itemId
+ ) { _ in }
+
configureRemoteCommandsIfNeeded()
updateNowPlayingInfo(rate: 0)
-
- emit("[NativeCore] ensureLoaded done: \(itemId) trackIdx=\(startTrackIndex)/\(urls.count) localStart=\(localStart)s globalStart=\(savedPos)s")
+ emit("[NativeCore] ensureLoaded done: \(itemId) global=\(savedPos)s speed=\(speed) eq=\(eqEnabled)")
+ return true
}
- /// Build an AVPlayerItem for the current track (with auth headers if
- /// streaming) and assign it to the player. Sets up end-of-track observer
- /// so playback rolls onto the next track automatically.
- private func loadCurrentTrack(seekTo localSeconds: Double) {
- guard let p = _player, _trackIndex < _trackUrls.count else { return }
- let url = _trackUrls[_trackIndex]
- var options: [String: Any] = [:]
- if !_trackHeaders.isEmpty {
- options["AVURLAssetHTTPHeaderFieldsKey"] = _trackHeaders
- }
- let asset = AVURLAsset(url: url, options: options)
- let item = AVPlayerItem(asset: asset)
- p.replaceCurrentItem(with: item)
- if localSeconds > 0 {
- p.seek(to: CMTime(seconds: localSeconds, preferredTimescale: 1000))
- }
- observeItemEnd(item)
- addPeriodicObserver(player: p)
- emit("[NativeCore] loadCurrentTrack: idx=\(_trackIndex) url=\(url) localSeek=\(localSeconds)s")
- }
-
- private func trackIndexForGlobal(_ globalSeconds: Double, offsets: [Double]) -> Int {
- if globalSeconds <= 0 { return 0 }
- // offsets is [0, dur0, dur0+dur1, ..., total]. Find largest index i
- // where offsets[i] <= globalSeconds. Number of tracks = offsets.count - 1
- // so result must be in [0, offsets.count - 2].
- let trackCount = max(1, offsets.count - 1)
- for i in 0..<trackCount {
- let nextOffset = i + 1 < offsets.count ? offsets[i + 1] : .greatestFiniteMagnitude
- if globalSeconds < nextOffset {
- return i
- }
- }
- return trackCount - 1
- }
-
- /// Compute global position = trackOffset + position-within-current-track.
- /// Returns 0 if state hasn't loaded.
+ /// Global position straight from the engine (already offset-aware).
private func globalPosition() -> Double {
- guard let p = _player else { return 0 }
- let local = p.currentTime().seconds
- guard local.isFinite else { return _trackOffsets.indices.contains(_trackIndex) ? _trackOffsets[_trackIndex] : 0 }
- let baseOffset = _trackOffsets.indices.contains(_trackIndex) ? _trackOffsets[_trackIndex] : 0
- return baseOffset + local
+ return AbsorbAudioEngine.shared.globalPositionS()
}
private func totalDuration() -> Double {
let defaults = UserDefaults(suiteName: Self.appGroup)
let stashed = defaults?.double(forKey: "np_total_s") ?? 0
- if stashed > 0 { return stashed }
- return _trackOffsets.last ?? 0
+ return stashed > 0 ? stashed : 0
}
- private func seekToGlobal(_ globalSeconds: Double) {
- guard !_trackOffsets.isEmpty else { return }
- let targetIndex = trackIndexForGlobal(globalSeconds, offsets: _trackOffsets)
- let localTarget = max(0, globalSeconds - _trackOffsets[targetIndex])
-
- if targetIndex == _trackIndex {
- // Same track, simple seek.
- _player?.seek(
- to: CMTime(seconds: localTarget, preferredTimescale: 1000),
- toleranceBefore: .zero, toleranceAfter: .zero
- ) { [weak self] _ in
- self?.queue.async {
- self?.savePosition()
- self?.updateNowPlayingInfo(rate: Double(self?._player?.rate ?? 0))
- self?.emit("[NativeCore] seekToGlobal in-track: \(globalSeconds)s")
- }
- }
- } else {
- // Cross-track seek: load the new track, then seek inside it.
- let wasPlaying = (_player?.rate ?? 0) > 0
- _trackIndex = targetIndex
- loadCurrentTrack(seekTo: localTarget)
- if wasPlaying {
- _player?.play()
- applySpeed(to: _player!)
- }
- savePosition()
- updateNowPlayingInfo(rate: Double(_player?.rate ?? 0))
- emit("[NativeCore] seekToGlobal cross-track: \(globalSeconds)s -> idx=\(targetIndex) local=\(localTarget)s")
- }
- }
-
- private func applySpeed(to player: AVPlayer) {
+ private func currentSpeed() -> Float {
let defaults = UserDefaults(suiteName: Self.appGroup)
let speed = defaults?.double(forKey: "np_speed") ?? 1.0
- player.rate = Float(speed > 0 ? speed : 1.0)
+ return Float(speed > 0 ? speed : 1.0)
}
- private func observeItemEnd(_ item: AVPlayerItem) {
- if let prev = _itemEndObserver {
- NotificationCenter.default.removeObserver(prev)
- }
- _itemEndObserver = NotificationCenter.default.addObserver(
- forName: .AVPlayerItemDidPlayToEndTime,
- object: item,
- queue: nil
- ) { [weak self] _ in
+ private func seekToGlobal(_ globalSeconds: Double) {
+ AbsorbAudioEngine.shared.seekToGlobal(globalSeconds) { [weak self] _ in
self?.queue.async {
- self?.handleTrackEnd()
+ self?.savePosition()
+ self?.updateNowPlayingInfo(rate: Double(AbsorbAudioEngine.shared.isPlaying ? (self?.currentSpeed() ?? 1.0) : 0))
+ self?.emit("[NativeCore] seekToGlobal done: \(globalSeconds)s")
}
}
}
- private func handleTrackEnd() {
- let nextIndex = _trackIndex + 1
- if nextIndex < _trackUrls.count {
- emit("[NativeCore] track \(_trackIndex) ended, advancing to \(nextIndex)")
- _trackIndex = nextIndex
- loadCurrentTrack(seekTo: 0)
- let wasPlaying = (_player?.rate ?? 0) > 0
- if wasPlaying {
- _player?.play()
- if let p = _player { applySpeed(to: p) }
- }
- savePosition()
- updateNowPlayingInfo(rate: Double(_player?.rate ?? 0))
- } else {
- emit("[NativeCore] last track ended, stopping")
- savePosition()
- pushProgressToServer()
- stopServerSyncTimer()
- updateNowPlayingInfo(rate: 0)
- }
- }
-
- private func addPeriodicObserver(player: AVPlayer) {
- if let prev = _periodicObserver {
- player.removeTimeObserver(prev)
- }
- _periodicObserver = player.addPeriodicTimeObserver(
- forInterval: CMTime(seconds: 5, preferredTimescale: 1),
- queue: .main
- ) { [weak self] _ in
- self?.queue.async { self?.savePosition() }
- }
- }
-
private func activateAudioSession() {
let session = AVAudioSession.sharedInstance()
do {
@@ -405,7 +301,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
if !pos.isFinite { return }
let defaults = UserDefaults(suiteName: Self.appGroup)
defaults?.set(pos, forKey: "np_position_s")
- defaults?.set((_player?.rate ?? 0) > 0, forKey: "widget_is_playing")
+ defaults?.set(AbsorbAudioEngine.shared.isPlaying, forKey: "widget_is_playing")
}
// MARK: - Server sync
@@ -483,7 +379,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
// MARK: - MPNowPlayingInfoCenter
private func updateNowPlayingInfo(rate: Double) {
- guard _player != nil else { return }
+ guard _currentItemId != nil else { return }
let defaults = UserDefaults(suiteName: Self.appGroup)
let title = defaults?.string(forKey: "np_title")
?? defaults?.string(forKey: "widget_title")
@@ -535,7 +431,7 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
// Each handler bails when Flutter is alive so audio_service handlers
// win on the lock screen. When native is in charge, these drive the
- // AVPlayer directly.
+ // shared engine directly.
cc.playCommand.addTarget { [weak self] _ in
if self?.flutterIsAlive() == true {
self?.emit("[NativeCore] remote: play - Flutter is alive, deferring")
@@ -593,7 +489,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self?.emit("[NativeCore] remote: scrub - Flutter is alive, deferring")
return .success
}
- self?.queue.async { self?.seekToGlobal(event.positionTime) }
+ self?.queue.async {
+ guard self?.ensureLoaded() == true else { return }
+ self?.seekToGlobal(event.positionTime)
+ }
return .success
}
emit("[NativeCore] remote command center wired")
diff --git a/ios/Runner/Audio/AbsorbAudioBridge.swift b/ios/Runner/Audio/AbsorbAudioBridge.swift
index 4f94bca9..6449a459 100644
--- a/ios/Runner/Audio/AbsorbAudioBridge.swift
+++ b/ios/Runner/Audio/AbsorbAudioBridge.swift
@@ -54,6 +54,7 @@ final class AbsorbAudioBridge: NSObject {
let speed = (args?["speed"] as? Double).map { Float($0) } ?? 1.0
let volume = (args?["volume"] as? Double).map { Float($0) } ?? 1.0
let eq = (args?["eqEnabled"] as? Bool) ?? false
+ let itemId = args?["itemId"] as? String
AbsorbAudioEngine.shared.load(
tracks: trackList,
trackOffsets: offsets,
@@ -61,7 +62,8 @@ final class AbsorbAudioBridge: NSObject {
totalDurationS: dur,
speed: speed,
volume: volume,
- eqEnabled: eq
+ eqEnabled: eq,
+ itemId: itemId
) { duration in
result(["durationS": duration as Any])
}
@@ -101,11 +103,13 @@ final class AbsorbAudioBridge: NSObject {
let offsets = (args?["trackOffsets"] as? [NSNumber])?.map { $0.doubleValue } ?? []
let start = (args?["startPositionS"] as? Double) ?? 0
let dur = (args?["totalDurationS"] as? Double) ?? 0
+ let nextItemId = args?["itemId"] as? String
AbsorbAudioEngine.shared.setNextSource(
tracks: trackList,
trackOffsets: offsets,
startPositionS: start,
- totalDurationS: dur
+ totalDurationS: dur,
+ itemId: nextItemId
) { ok in result(ok) }
} else {
AbsorbAudioEngine.shared.clearNextSource()
@@ -130,6 +134,18 @@ final class AbsorbAudioBridge: NSObject {
case "getBufferedPositionS":
result(AbsorbAudioEngine.shared.getBufferedPositionS())
+ case "engineState":
+ // Lets Dart reconcile after a widget-driven session: read what book the
+ // engine actually holds and whether it's playing, so foreground resume
+ // can adopt rather than reload.
+ result([
+ "itemId": AbsorbAudioEngine.shared.currentItemId as Any,
+ "isLoaded": AbsorbAudioEngine.shared.isLoaded,
+ "isPlaying": AbsorbAudioEngine.shared.isPlaying,
+ "trackIndex": AbsorbAudioEngine.shared.currentTrackIndex,
+ "globalPositionS": AbsorbAudioEngine.shared.globalPositionS(),
+ ])
+
case "dispose":
AbsorbAudioEngine.shared.stop()
result(true)
diff --git a/ios/Runner/Audio/AbsorbAudioEngine.swift b/ios/Runner/Audio/AbsorbAudioEngine.swift
index 4eb1083b..bb50ccc1 100644
--- a/ios/Runner/Audio/AbsorbAudioEngine.swift
+++ b/ios/Runner/Audio/AbsorbAudioEngine.swift
@@ -31,6 +31,12 @@ final class AbsorbAudioEngine: NSObject {
private var currentItem: AVPlayerItem?
private var currentEpoch: UInt = 0
+ // Book id of whatever is currently loaded. Set by load() so the
+ // Flutter-suspended controller (AbsorbPlayerCore) can tell whether the engine
+ // already holds the book it was asked to resume - if so it just resumes the
+ // live engine rather than reloading. Read off the engine queue.
+ private var _currentItemId: String?
+
// Pre-prepared next book waiting for the cross-book swap.
private var nextTrackUrls: [URL] = []
private var nextTrackHeaders: [String: String] = [:]
@@ -38,6 +44,7 @@ final class AbsorbAudioEngine: NSObject {
private var nextTotalDurationS: Double = 0
private var nextItem: AVPlayerItem?
private var nextStartS: Double = 0
+ private var nextItemId: String?
// Configured player state.
private var speed: Float = 1.0
@@ -77,11 +84,13 @@ final class AbsorbAudioEngine: NSObject {
speed: Float,
volume: Float,
eqEnabled: Bool,
+ itemId: String? = nil,
completion: @escaping (Double?) -> Void) {
queue.async { [weak self] in
guard let self = self else { completion(nil); return }
self.activateSession()
+ if let itemId = itemId { self._currentItemId = itemId }
self.trackUrls = tracks.map { $0.url }
self.trackHeaders = tracks.first?.headers ?? [:]
self.trackOffsets = Self.normalizeOffsets(trackOffsets, trackCount: tracks.count, totalDurationS: totalDurationS)
@@ -121,6 +130,7 @@ final class AbsorbAudioEngine: NSObject {
queue.async { [weak self] in
guard let self = self else { return }
self.currentItem = nil
+ self._currentItemId = nil
self.processingState = .idle
self.emitState()
DispatchQueue.main.async {
@@ -184,6 +194,7 @@ final class AbsorbAudioEngine: NSObject {
trackOffsets: [Double],
startPositionS: Double,
totalDurationS: Double,
+ itemId: String? = nil,
completion: @escaping (Bool) -> Void) {
queue.async { [weak self] in
guard let self = self else { completion(false); return }
@@ -192,6 +203,7 @@ final class AbsorbAudioEngine: NSObject {
self.nextTrackOffsets = Self.normalizeOffsets(trackOffsets, trackCount: tracks.count, totalDurationS: totalDurationS)
self.nextTotalDurationS = totalDurationS
self.nextStartS = startPositionS
+ self.nextItemId = itemId
guard let firstUrl = tracks.first?.url else {
self.nextItem = nil
@@ -229,6 +241,7 @@ final class AbsorbAudioEngine: NSObject {
self?.nextTotalDurationS = 0
self?.nextStartS = 0
self?.nextItem = nil
+ self?.nextItemId = nil
}
}
@@ -278,6 +291,56 @@ final class AbsorbAudioEngine: NSObject {
return bufferedLocal.isFinite ? max(0, bufferedLocal) : 0
}
+ // MARK: - Adoption helpers (for the Flutter-suspended controller)
+ //
+ // AbsorbPlayerCore drives this same shared engine when Flutter is suspended.
+ // These let it decide whether to reload, and read/save position in the
+ // global coordinate space (the engine works in track-local space internally,
+ // but the app group and server store global seconds).
+
+ /// Book id of the currently-loaded book, or nil if nothing is loaded.
+ var currentItemId: String? {
+ queue.sync { _currentItemId }
+ }
+
+ /// True once a source has been loaded (and not stopped).
+ var isLoaded: Bool {
+ queue.sync { !trackUrls.isEmpty && currentItem != nil }
+ }
+
+ /// True while the player is actively playing (rate > 0).
+ var isPlaying: Bool {
+ player.rate > 0 || player.timeControlStatus == .playing
+ }
+
+ /// Current track index within the loaded book.
+ var currentTrackIndex: Int {
+ queue.sync { trackIndex }
+ }
+
+ /// Global position = track-local position + the current track's offset.
+ func globalPositionS() -> Double {
+ queue.sync {
+ let local = player.currentItem?.currentTime().seconds ?? 0
+ let safeLocal = local.isFinite ? max(0, local) : 0
+ let base = trackOffsets.indices.contains(trackIndex) ? trackOffsets[trackIndex] : 0
+ let baseSafe = base.isFinite ? base : 0
+ return baseSafe + safeLocal
+ }
+ }
+
+ /// Convert a global position to (localS, trackIndex) and seek there. Used by
+ /// the controller's skip / scrub handlers, which think in global seconds.
+ func seekToGlobal(_ globalSeconds: Double, completion: @escaping (Bool) -> Void) {
+ queue.async { [weak self] in
+ guard let self = self else { completion(false); return }
+ let target = self.trackIndexFor(globalSeconds: globalSeconds)
+ let base = self.trackOffsets.indices.contains(target) ? self.trackOffsets[target] : 0
+ let local = max(0, globalSeconds - (base.isFinite ? base : 0))
+ self.seek(toLocalS: local, trackIndex: target, completion: completion)
+ }
+ }
+
// MARK: - Track loading
private func loadTrack(atIndex index: Int,
@@ -463,6 +526,10 @@ final class AbsorbAudioEngine: NSObject {
trackOffsets = nextTrackOffsets
totalDurationS = nextTotalDurationS
trackIndex = 0
+ // Promote the next book's id so the widget controller recognises the book
+ // the engine is now actually playing (otherwise a widget tap after an
+ // auto-advance would reload and restart the new book's stream).
+ if let nextId = nextItemId { _currentItemId = nextId }
currentItem = item
currentEpoch &+= 1
@@ -477,6 +544,7 @@ final class AbsorbAudioEngine: NSObject {
nextTotalDurationS = 0
nextStartS = 0
nextItem = nil
+ nextItemId = nil
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
diff --git a/lib/services/_audio_player.dart b/lib/services/_audio_player.dart
index 5088c0d7..fa0b0fcc 100644
--- a/lib/services/_audio_player.dart
+++ b/lib/services/_audio_player.dart
@@ -92,10 +92,13 @@ class AudioPlayer {
Duration? initialPosition,
int? initialIndex,
bool preload = true,
+ String? itemId,
}) async {
if (_isNative) {
- return _native!.setAudioSource(source, initialPosition: initialPosition, initialIndex: initialIndex, preload: preload);
+ return _native!.setAudioSource(source, initialPosition: initialPosition, initialIndex: initialIndex, preload: preload, itemId: itemId);
}
+ // just_audio doesn't track an item id; it's only meaningful for the iOS
+ // engine, which uses it to recognise a book on widget-driven resume.
return _ja!.setAudioSource(source, initialPosition: initialPosition, initialIndex: initialIndex, preload: preload);
}
@@ -103,9 +106,9 @@ class AudioPlayer {
/// On iOS-native this swaps via replaceCurrentItem when current ends.
/// On just_audio this is left as a no-op; caller still appends to its
/// ConcatenatingAudioSource the old way.
- Future<bool> setNextSource(ja.AudioSource? source, {double startPositionS = 0, double totalDurationS = 0}) async {
+ Future<bool> setNextSource(ja.AudioSource? source, {double startPositionS = 0, double totalDurationS = 0, String? itemId}) async {
if (_isNative) {
- return _native!.setNextSource(source, startPositionS: startPositionS, totalDurationS: totalDurationS);
+ return _native!.setNextSource(source, startPositionS: startPositionS, totalDurationS: totalDurationS, itemId: itemId);
}
return false;
}
@@ -118,6 +121,17 @@ class AudioPlayer {
if (_isNative) await _native!.detachEqualizerTap();
}
+ /// iOS-only: read the native engine's live state for foreground-resume
+ /// reconciliation. Null off iOS or on failure.
+ Future<NativeEngineState?> engineState() async =>
+ _isNative ? _native!.engineState() : null;
+
+ /// iOS-only: sync the Dart mirror to the engine's actual playing state
+ /// without issuing a new play/pause command.
+ void adoptPlayingState(bool playing) {
+ if (_isNative) _native!.adoptPlayingState(playing);
+ }
+
// ─── Control ───
Future<void> play() => _isNative ? _native!.play() : _ja!.play();
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 013667cd..4c38e792 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1425,6 +1425,7 @@ class AudioPlayerService extends ChangeNotifier {
source,
startPositionS: startS,
totalDurationS: (next['duration'] as num?)?.toDouble() ?? 0,
+ itemId: nextItemId,
);
if (!ok) {
debugPrint('[PreBuffer] Native setNextSource failed');
@@ -1629,6 +1630,55 @@ class AudioPlayerService extends ChangeNotifier {
}
}
+ /// iOS foreground reconciliation after a possible widget-driven session.
+ ///
+ /// The shared engine (AbsorbAudioEngine) persists across Flutter suspension,
+ /// so when the user tapped the widget while we were suspended the engine kept
+ /// playing the same book. On resume we must NOT reload it - that restarts the
+ /// stream. Instead, if the engine is still on our current book, adopt its
+ /// playing-state, track index, and global position. If the engine has been
+ /// stopped or holds a different book, leave the existing paths to handle it
+ /// (the idle-on-resume re-init in play(), or a fresh playItem).
+ Future<void> _iosReconcileEngineOnForeground() async {
+ if (!Platform.isIOS) return;
+ final player = _player;
+ final itemId = _currentItemId;
+ if (player == null || itemId == null) return;
+ final state = await player.engineState();
+ if (state == null) return;
+ // Engine isn't on our book (stopped, disposed, or swapped) - nothing to
+ // adopt; the normal play()/idle-reinit path will rebuild if needed.
+ if (!state.isLoaded || state.itemId != itemId) {
+ debugPrint('[Player] iOS resume: engine not on current book '
+ '(engine=${state.itemId} loaded=${state.isLoaded}) - skipping adopt');
+ return;
+ }
+ // Sync our track index to whatever track the engine actually reached while
+ // we were suspended, so absolute-position math is correct.
+ if (_trackStartOffsets.length > 1) {
+ final clamped = state.trackIndex.clamp(0, _trackStartOffsets.length - 2);
+ if (clamped != _currentTrackIndex) {
+ debugPrint('[Player] iOS resume: track index $_currentTrackIndex -> $clamped (from engine)');
+ _currentTrackIndex = clamped;
+ }
+ }
+ // Adopt the engine's playing-state without issuing a new command, then let
+ // the handler re-publish so the lock screen / notification reflect reality.
+ final wasPlaying = isPlaying;
+ player.adoptPlayingState(state.isPlaying);
+ debugPrint('[Player] iOS resume: adopted engine state playing=${state.isPlaying} '
+ '(was $wasPlaying) global=${state.globalPositionS.toStringAsFixed(1)}s');
+ // Persist the adopted position locally so a subsequent sync/save doesn't
+ // overwrite it with a stale value.
+ if (state.globalPositionS > 0) {
+ _lastKnownPositionSec = state.globalPositionS;
+ await _saveProgressLocal(
+ Duration(milliseconds: (state.globalPositionS * 1000).round()));
+ }
+ _handler?.refreshPlaybackState();
+ notifyListeners();
+ }
+
Future<void> _primeNowPlaying({
required String title,
required String artist,
@@ -2186,6 +2236,12 @@ class AudioPlayerService extends ChangeNotifier {
if (Platform.isIOS && service._iosResyncPending) {
unawaited(service._iosForegroundResyncIfNeeded());
}
+ // After a widget-driven session the shared engine may have kept playing
+ // (or advanced) while Flutter was suspended. Adopt its live state rather
+ // than reloading - reloading would restart the same stream (bug #285).
+ if (Platform.isIOS && service.hasBook) {
+ await service._iosReconcileEngineOnForeground();
+ }
if (!service.hasBook) return;
final sessionAlive = service._playbackSessionId != null;
debugPrint('[MediaSession] Foregrounded - refreshing (playing=${service.isPlaying}, session=$sessionAlive, item=${service._currentItemId})');
@@ -2486,7 +2542,7 @@ class AudioPlayerService extends ChangeNotifier {
source = ConcatenatingAudioSource(children: sources);
}
- await _player!.setAudioSource(source);
+ await _player!.setAudioSource(source, itemId: _currentItemId);
// Seek to the same absolute position
final posSeconds = currentAbsolutePos.inMilliseconds / 1000.0;
@@ -2653,7 +2709,7 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] Pre-source setActive failed (local): $e');
}
_resetPreBufferState();
- final decoded = await _player!.setAudioSource(source);
+ final decoded = await _player!.setAudioSource(source, itemId: _currentItemId);
_activeConcatSource = source;
_currentBookTrackCount = trackSources.length;
@@ -2787,7 +2843,7 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] Pre-source setActive failed (cached-session): $e');
}
_resetPreBufferState();
- await _player!.setAudioSource(source);
+ await _player!.setAudioSource(source, itemId: _currentItemId);
_activeConcatSource = source as ConcatenatingAudioSource;
_currentBookTrackCount = trackSources.length;
@@ -3050,7 +3106,7 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] Pre-source setActive failed (stream): $e');
}
_resetPreBufferState();
- await _player!.setAudioSource(source);
+ await _player!.setAudioSource(source, itemId: _currentItemId);
_activeConcatSource = source;
_currentBookTrackCount = trackSources.length;
@@ -3156,7 +3212,7 @@ class AudioPlayerService extends ChangeNotifier {
}
retrySource = ConcatenatingAudioSource(children: sources);
}
- await _player!.setAudioSource(retrySource);
+ await _player!.setAudioSource(retrySource, itemId: _currentItemId);
if (totalDuration > 0 && startTime >= totalDuration - 1.0) startTime = 0;
if (startTime > 0) await _seekAbsolute(startTime);
clearSeekTarget();
@@ -3256,7 +3312,7 @@ class AudioPlayerService extends ChangeNotifier {
}
retrySource = ConcatenatingAudioSource(children: sources);
}
- await _player!.setAudioSource(retrySource);
+ await _player!.setAudioSource(retrySource, itemId: _currentItemId);
if (startTime > 0) await _seekAbsolute(startTime);
clearSeekTarget();
_subscribeTrackIndex();
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 409f590b..fca753c0 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -604,6 +604,12 @@ class HomeWidgetService {
await HomeWidget.saveWidgetData<String>('np_api_token', api.token);
}
+ // EQ-enabled flag in the app group so a cold widget-launch (engine never
+ // loaded this process) applies the user's EQ. `eq_enabled` itself lives in
+ // the default (non-group) prefs, so mirror it here as `np_eq_enabled`.
+ final eqEnabled = await ScopedPrefs.getBool('eq_enabled') ?? false;
+ await HomeWidget.saveWidgetData<bool>('np_eq_enabled', eqEnabled);
+
// Cover path piggybacks on the existing widget_cover_path entry, but
// expose it under the np_ namespace too for clarity on the native side.
final coverPath = await HomeWidget.getWidgetData<String>('widget_cover_path');
diff --git a/lib/services/native_ios_audio_player.dart b/lib/services/native_ios_audio_player.dart
index 01d06981..8895ca86 100644
--- a/lib/services/native_ios_audio_player.dart
+++ b/lib/services/native_ios_audio_player.dart
@@ -82,6 +82,7 @@ class NativeIosAudioPlayer {
Duration? initialPosition,
int? initialIndex,
bool preload = true,
+ String? itemId,
}) async {
final tracks = _flattenSource(source);
if (tracks.isEmpty) return null;
@@ -96,6 +97,9 @@ class NativeIosAudioPlayer {
'speed': _speed,
'volume': _volume,
'eqEnabled': eqEnabled,
+ // Lets AbsorbPlayerCore recognise this book on a widget-driven resume so
+ // it adopts the live engine instead of starting a duplicate stream.
+ if (itemId != null) 'itemId': itemId,
});
final durS = result?['durationS'] as double?;
if (durS != null) {
@@ -107,7 +111,7 @@ class NativeIosAudioPlayer {
/// New: pre-buffer the next book so the engine can swap to it gaplessly when
/// the current item ends. Not part of just_audio's API.
- Future<bool> setNextSource(ja.AudioSource? source, {double startPositionS = 0, double totalDurationS = 0}) async {
+ Future<bool> setNextSource(ja.AudioSource? source, {double startPositionS = 0, double totalDurationS = 0, String? itemId}) async {
if (source == null) {
await _methodChannel.invokeMethod('clearNextSource');
return true;
@@ -119,6 +123,8 @@ class NativeIosAudioPlayer {
'trackOffsets': _buildTrackOffsets(tracks),
'startPositionS': startPositionS,
'totalDurationS': totalDurationS,
+ // So the engine can adopt the right book id after it auto-advances.
+ if (itemId != null) 'itemId': itemId,
});
return result ?? false;
}
@@ -180,6 +186,39 @@ class NativeIosAudioPlayer {
throw UnsupportedError('NativeIosAudioPlayer.setAsset is not implemented; use ja.AudioPlayer for the chime.');
}
+ /// Snapshot of what the native engine is actually doing right now. Used on
+ /// foreground resume to reconcile after a widget-driven session: the engine
+ /// may have kept playing (or advanced) while Flutter was suspended. Returns
+ /// null on failure.
+ Future<NativeEngineState?> engineState() async {
+ try {
+ final raw = await _methodChannel
+ .invokeMethod<Map<dynamic, dynamic>>('engineState');
+ if (raw == null) return null;
+ return NativeEngineState(
+ itemId: raw['itemId'] as String?,
+ isLoaded: (raw['isLoaded'] as bool?) ?? false,
+ isPlaying: (raw['isPlaying'] as bool?) ?? false,
+ trackIndex: (raw['trackIndex'] as int?) ?? 0,
+ globalPositionS: (raw['globalPositionS'] as num?)?.toDouble() ?? 0,
+ );
+ } catch (e) {
+ debugPrint('[NativeIosAudioPlayer] engineState failed: $e');
+ return null;
+ }
+ }
+
+ /// Adopt the engine's current playing-state without issuing a new command.
+ /// Called when foreground resume finds the engine already playing the right
+ /// book - we just sync the Dart mirror so the UI reflects reality.
+ void adoptPlayingState(bool playing) {
+ _playing = playing;
+ _processingState = ja.ProcessingState.ready;
+ _processingStateController.add(_processingState);
+ _emitPlayerState();
+ _playbackEventController.add(_buildPlaybackEvent());
+ }
+
Future<void> attachEqualizerTap() async {
await _methodChannel.invokeMethod('attachEqualizerTap');
}
@@ -342,3 +381,20 @@ class _NativeTrack {
final bool isLocal;
final Map<String, String> headers;
}
+
+/// Snapshot of the native iOS engine's live state, read over the method
+/// channel for foreground-resume reconciliation.
+class NativeEngineState {
+ NativeEngineState({
+ required this.itemId,
+ required this.isLoaded,
+ required this.isPlaying,
+ required this.trackIndex,
+ required this.globalPositionS,
+ });
+ final String? itemId;
+ final bool isLoaded;
+ final bool isPlaying;
+ final int trackIndex;
+ final double globalPositionS;
+}