Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Native iOS audio engine

Barnabas2926bdd69957
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
index 7022fd93..6ca8109b 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -248,11 +248,11 @@ class MainActivity : AudioServiceActivity() {
private fun handleSetEnabled(enabled: Boolean, result: MethodChannel.Result) {
try {
+ // Master switch gates only the band EQ. Bass / virtualizer /
+ // loudness are independent and track their own values, so they
+ // keep working with the equalizer off.
eqEnabled = enabled
equalizer?.enabled = enabled
- bassBoost?.enabled = enabled
- virtualizer?.enabled = enabled
- loudnessEnhancer?.enabled = enabled && eqLoudnessGainMb > 0
result.success(true)
} catch (e: Exception) {
result.error("EQ_ERROR", e.message, null)
@@ -270,7 +270,10 @@ class MainActivity : AudioServiceActivity() {
private fun handleSetBassBoost(strength: Int, result: MethodChannel.Result) {
try {
- bassBoost?.setStrength(strength.toShort().coerceIn(0, 1000))
+ val s = strength.toShort().coerceIn(0, 1000)
+ bassBoost?.setStrength(s)
+ // Independent of the band-EQ master: on when there's something to do.
+ bassBoost?.enabled = s > 0
result.success(true)
} catch (e: Exception) {
result.error("EQ_ERROR", e.message, null)
@@ -279,7 +282,9 @@ class MainActivity : AudioServiceActivity() {
private fun handleSetVirtualizer(strength: Int, result: MethodChannel.Result) {
try {
- virtualizer?.setStrength(strength.toShort().coerceIn(0, 1000))
+ val s = strength.toShort().coerceIn(0, 1000)
+ virtualizer?.setStrength(s)
+ virtualizer?.enabled = s > 0
result.success(true)
} catch (e: Exception) {
result.error("EQ_ERROR", e.message, null)
@@ -290,7 +295,7 @@ class MainActivity : AudioServiceActivity() {
try {
eqLoudnessGainMb = gain
loudnessEnhancer?.setTargetGain(gain)
- loudnessEnhancer?.enabled = eqEnabled && gain > 0
+ loudnessEnhancer?.enabled = gain > 0
result.success(true)
} catch (e: Exception) {
result.error("EQ_ERROR", e.message, null)
diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj
index 064bd2c9..fadedf65 100644
--- a/ios/Runner.xcodeproj/project.pbxproj
+++ b/ios/Runner.xcodeproj/project.pbxproj
@@ -22,6 +22,10 @@
AB10020000000000000E0003 /* NowPlayingWidgetExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = AB10010000000000000E0004 /* NowPlayingWidgetExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
BB10020000000000000E0001 /* AbsorbPlayerCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0001 /* AbsorbPlayerCore.swift */; };
BB10020000000000000E0002 /* IOSQueueAdvancer.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0002 /* IOSQueueAdvancer.swift */; };
+ BB10020000000000000E0003 /* AbsorbAudioEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0003 /* AbsorbAudioEngine.swift */; };
+ BB10020000000000000E0004 /* AbsorbAudioEngineEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0004 /* AbsorbAudioEngineEvents.swift */; };
+ BB10020000000000000E0005 /* AudioEQProcessor.m in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0005 /* AudioEQProcessor.m */; };
+ BB10020000000000000E0007 /* AbsorbAudioBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0007 /* AbsorbAudioBridge.swift */; };
BB10020000000000000E0020 /* AbsorbPlayerCore in Frameworks */ = {isa = PBXBuildFile; productRef = BB10010000000000000E0020 /* AbsorbPlayerCore */; };
BB10020000000000000E0021 /* AbsorbPlayerCore in Frameworks */ = {isa = PBXBuildFile; productRef = BB10010000000000000E0021 /* AbsorbPlayerCore */; };
/* End PBXBuildFile section */
@@ -96,6 +100,11 @@
AB10010000000000000E0006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
BB10010000000000000E0001 /* AbsorbPlayerCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsorbPlayerCore.swift; sourceTree = "<group>"; };
BB10010000000000000E0002 /* IOSQueueAdvancer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSQueueAdvancer.swift; sourceTree = "<group>"; };
+ BB10010000000000000E0003 /* AbsorbAudioEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsorbAudioEngine.swift; sourceTree = "<group>"; };
+ BB10010000000000000E0004 /* AbsorbAudioEngineEvents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsorbAudioEngineEvents.swift; sourceTree = "<group>"; };
+ BB10010000000000000E0005 /* AudioEQProcessor.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AudioEQProcessor.m; sourceTree = "<group>"; };
+ BB10010000000000000E0006 /* AudioEQProcessor.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AudioEQProcessor.h; sourceTree = "<group>"; };
+ BB10010000000000000E0007 /* AbsorbAudioBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsorbAudioBridge.swift; sourceTree = "<group>"; };
B7990BE5669E13951B2BAD46 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
DAACD72AEC68ADA3FA213E6C /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
E4A191144C46AC47851AEE49 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
@@ -209,11 +218,24 @@
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
BB10010000000000000E0001 /* AbsorbPlayerCore.swift */,
BB10010000000000000E0002 /* IOSQueueAdvancer.swift */,
+ BB10010000000000000E0030 /* Audio */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
);
path = Runner;
sourceTree = "<group>";
};
+ BB10010000000000000E0030 /* Audio */ = {
+ isa = PBXGroup;
+ children = (
+ BB10010000000000000E0003 /* AbsorbAudioEngine.swift */,
+ BB10010000000000000E0004 /* AbsorbAudioEngineEvents.swift */,
+ BB10010000000000000E0007 /* AbsorbAudioBridge.swift */,
+ BB10010000000000000E0006 /* AudioEQProcessor.h */,
+ BB10010000000000000E0005 /* AudioEQProcessor.m */,
+ );
+ path = Audio;
+ sourceTree = "<group>";
+ };
AB10030000000000000E0001 /* NowPlayingWidget */ = {
isa = PBXGroup;
children = (
@@ -500,6 +522,10 @@
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
BB10020000000000000E0001 /* AbsorbPlayerCore.swift in Sources */,
BB10020000000000000E0002 /* IOSQueueAdvancer.swift in Sources */,
+ BB10020000000000000E0003 /* AbsorbAudioEngine.swift in Sources */,
+ BB10020000000000000E0004 /* AbsorbAudioEngineEvents.swift in Sources */,
+ BB10020000000000000E0005 /* AudioEQProcessor.m in Sources */,
+ BB10020000000000000E0007 /* AbsorbAudioBridge.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index ef8f42b8..55b270a4 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -62,6 +62,11 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
}
}
+ AbsorbAudioEQProcessor.setFormatLogger { [weak self] line in
+ DispatchQueue.main.async {
+ self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
+ }
+ }
IOSQueueAdvancer.logSink = { [weak self] line in
DispatchQueue.main.async {
@@ -69,6 +74,17 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
}
}
+ AbsorbAudioEngine.logSink = { [weak self] line in
+ DispatchQueue.main.async {
+ self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
+ }
+ }
+ AbsorbAudioBridge.logSink = { [weak self] line in
+ DispatchQueue.main.async {
+ self?.widgetChannel?.invokeMethod("log", arguments: ["msg": line])
+ }
+ }
+
// Register the native player core as an AppIntent dependency. The widget
// intent declares `@Dependency var core: AbsorbPlayerCoreProtocol` - that
// signals to iOS to launch this host app process to run the intent's
@@ -236,6 +252,7 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
let messenger = flutterEngine.binaryMessenger
IOSQueueAdvancer.shared.register(with: messenger)
+ AbsorbAudioBridge.shared.register(with: messenger)
// iOS audio output device switching is not implemented yet — iOS routes
// through the system's MPVolumeView/AVRoutePicker rather than letting apps
@@ -389,17 +406,20 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
case "setEnabled":
let enabled = args?["enabled"] as? Bool ?? false
AudioEQProcessor.shared.setEnabled(enabled)
+ AbsorbAudioEQProcessor.shared.setEnabled(enabled)
result(true)
case "setBand":
let band = args?["band"] as? Int ?? 0
let level = args?["level"] as? Int ?? 0
AudioEQProcessor.shared.setBandLevel(Int32(level), forBand: Int32(band))
+ AbsorbAudioEQProcessor.shared.setBandLevel(Int32(level), forBand: Int32(band))
result(true)
case "setBassBoost":
let strength = args?["strength"] as? Int ?? 0
AudioEQProcessor.shared.setBassBoostStrength(Int32(strength))
+ AbsorbAudioEQProcessor.shared.setBassBoostStrength(Int32(strength))
result(true)
case "setVirtualizer":
@@ -409,11 +429,13 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
case "setLoudness":
let gain = args?["gain"] as? Int ?? 0
AudioEQProcessor.shared.setLoudnessGain(Int32(gain))
+ AbsorbAudioEQProcessor.shared.setLoudnessGain(Int32(gain))
result(true)
case "setMono":
let enabled = args?["enabled"] as? Bool ?? false
AudioEQProcessor.shared.setMonoEnabled(enabled)
+ AbsorbAudioEQProcessor.shared.setMonoEnabled(enabled)
result(true)
default:
diff --git a/ios/Runner/Audio/AbsorbAudioBridge.swift b/ios/Runner/Audio/AbsorbAudioBridge.swift
new file mode 100644
index 00000000..4f94bca9
--- /dev/null
+++ b/ios/Runner/Audio/AbsorbAudioBridge.swift
@@ -0,0 +1,233 @@
+import Flutter
+import Foundation
+
+/// Wires AbsorbAudioEngine to Dart over a method channel + event channel.
+final class AbsorbAudioBridge: NSObject {
+ static let shared = AbsorbAudioBridge()
+
+ static var logSink: ((String) -> Void)?
+
+ private weak var methodChannel: FlutterMethodChannel?
+ private weak var eventChannel: FlutterEventChannel?
+ private var eventSink: FlutterEventSink?
+
+ private let streamHandler = StreamHandler()
+
+ private override init() {
+ super.init()
+ AbsorbAudioEngine.shared.delegate = self
+ streamHandler.onSinkUpdate = { [weak self] sink in
+ self?.eventSink = sink
+ }
+ }
+
+ func register(with messenger: FlutterBinaryMessenger) {
+ let method = FlutterMethodChannel(
+ name: "com.absorb.audio_engine",
+ binaryMessenger: messenger
+ )
+ method.setMethodCallHandler { [weak self] call, result in
+ self?.handle(call, result: result)
+ }
+ methodChannel = method
+
+ let events = FlutterEventChannel(
+ name: "com.absorb.audio_engine.events",
+ binaryMessenger: messenger
+ )
+ events.setStreamHandler(streamHandler)
+ eventChannel = events
+
+ emit("[AudioBridge] registered")
+ }
+
+ // MARK: - Method dispatch
+
+ private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ let args = call.arguments as? [String: Any]
+ switch call.method {
+ case "load":
+ let trackList = parseTracks(args?["tracks"])
+ let offsets = (args?["trackOffsets"] as? [NSNumber])?.map { $0.doubleValue } ?? []
+ let start = (args?["startPositionS"] as? Double) ?? 0
+ let dur = (args?["totalDurationS"] as? Double) ?? 0
+ 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
+ AbsorbAudioEngine.shared.load(
+ tracks: trackList,
+ trackOffsets: offsets,
+ startPositionS: start,
+ totalDurationS: dur,
+ speed: speed,
+ volume: volume,
+ eqEnabled: eq
+ ) { duration in
+ result(["durationS": duration as Any])
+ }
+
+ case "play":
+ AbsorbAudioEngine.shared.play()
+ result(true)
+
+ case "pause":
+ AbsorbAudioEngine.shared.pause()
+ result(true)
+
+ case "stop":
+ AbsorbAudioEngine.shared.stop()
+ result(true)
+
+ case "seek":
+ let pos = (args?["positionS"] as? Double) ?? 0
+ let index = args?["index"] as? Int
+ AbsorbAudioEngine.shared.seek(toLocalS: pos, trackIndex: index) { ok in
+ result(ok)
+ }
+
+ case "setSpeed":
+ let s = (args?["speed"] as? Double).map { Float($0) } ?? 1.0
+ AbsorbAudioEngine.shared.setSpeed(s)
+ result(true)
+
+ case "setVolume":
+ let v = (args?["volume"] as? Double).map { Float($0) } ?? 1.0
+ AbsorbAudioEngine.shared.setVolume(v)
+ result(true)
+
+ case "setNextSource":
+ if let tracksArg = args?["tracks"] {
+ let trackList = parseTracks(tracksArg)
+ let offsets = (args?["trackOffsets"] as? [NSNumber])?.map { $0.doubleValue } ?? []
+ let start = (args?["startPositionS"] as? Double) ?? 0
+ let dur = (args?["totalDurationS"] as? Double) ?? 0
+ AbsorbAudioEngine.shared.setNextSource(
+ tracks: trackList,
+ trackOffsets: offsets,
+ startPositionS: start,
+ totalDurationS: dur
+ ) { ok in result(ok) }
+ } else {
+ AbsorbAudioEngine.shared.clearNextSource()
+ result(true)
+ }
+
+ case "clearNextSource":
+ AbsorbAudioEngine.shared.clearNextSource()
+ result(true)
+
+ case "attachEqualizerTap":
+ AbsorbAudioEngine.shared.attachEqualizerTap()
+ result(true)
+
+ case "detachEqualizerTap":
+ AbsorbAudioEngine.shared.detachEqualizerTap()
+ result(true)
+
+ case "getPositionS":
+ result(AbsorbAudioEngine.shared.getPositionS())
+
+ case "getBufferedPositionS":
+ result(AbsorbAudioEngine.shared.getBufferedPositionS())
+
+ case "dispose":
+ AbsorbAudioEngine.shared.stop()
+ result(true)
+
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
+ private func parseTracks(_ raw: Any?) -> [(url: URL, headers: [String: String])] {
+ guard let list = raw as? [[String: Any]] else { return [] }
+ var out: [(URL, [String: String])] = []
+ for entry in list {
+ guard let urlStr = entry["url"] as? String, !urlStr.isEmpty else { continue }
+ let isLocal = (entry["isLocal"] as? Bool) ?? false
+ let headers = (entry["headers"] as? [String: String]) ?? [:]
+ let url: URL?
+ if isLocal {
+ let path = urlStr.hasPrefix("file://") ? String(urlStr.dropFirst(7)) : urlStr
+ url = URL(fileURLWithPath: path)
+ } else {
+ url = URL(string: urlStr)
+ }
+ if let u = url { out.append((u, headers)) }
+ }
+ return out
+ }
+
+ private func sendEvent(_ payload: [String: Any]) {
+ DispatchQueue.main.async { [weak self] in
+ self?.eventSink?(payload)
+ }
+ }
+
+ private func emit(_ line: String) {
+ NSLog("%@", line)
+ Self.logSink?(line)
+ }
+}
+
+// MARK: - Engine delegate
+
+extension AbsorbAudioBridge: AbsorbAudioEngineDelegate {
+ func engineDidEmitPosition(_ positionS: Double) {
+ sendEvent(["type": "position", "positionS": positionS])
+ }
+
+ func engineDidChangeState(_ state: EngineStateSnapshot) {
+ sendEvent([
+ "type": "state",
+ "playing": state.playing,
+ "processingState": state.processingState.rawValue,
+ "timeControlStatus": state.timeControlStatus,
+ "reasonForWaitingToPlay": state.reasonForWaitingToPlay as Any,
+ ])
+ }
+
+ func engineDidLoadDuration(_ durationS: Double?) {
+ sendEvent(["type": "duration", "durationS": durationS as Any])
+ }
+
+ func engineDidChangeTrack(trackIndex: Int, totalTracks: Int) {
+ sendEvent([
+ "type": "trackChanged",
+ "trackIndex": trackIndex,
+ "totalTracks": totalTracks,
+ ])
+ }
+
+ func engineDidCompleteBook() {
+ sendEvent(["type": "bookCompleted"])
+ }
+
+ func engineDidAutoAdvance() {
+ sendEvent(["type": "bookAutoAdvanced"])
+ }
+
+ func engineDidEmitBufferedPosition(_ bufferedPositionS: Double) {
+ sendEvent(["type": "bufferedPosition", "bufferedPositionS": bufferedPositionS])
+ }
+
+ func engineDidError(message: String, code: String?) {
+ sendEvent(["type": "error", "message": message, "code": code as Any])
+ }
+}
+
+// MARK: - Stream handler
+
+private final class StreamHandler: NSObject, FlutterStreamHandler {
+ var onSinkUpdate: ((FlutterEventSink?) -> Void)?
+
+ func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
+ onSinkUpdate?(events)
+ return nil
+ }
+
+ func onCancel(withArguments arguments: Any?) -> FlutterError? {
+ onSinkUpdate?(nil)
+ return nil
+ }
+}
diff --git a/ios/Runner/Audio/AbsorbAudioEngine.swift b/ios/Runner/Audio/AbsorbAudioEngine.swift
new file mode 100644
index 00000000..4eb1083b
--- /dev/null
+++ b/ios/Runner/Audio/AbsorbAudioEngine.swift
@@ -0,0 +1,615 @@
+import AVFoundation
+import Foundation
+import UIKit
+
+/// Single AVPlayer that owns audio playback for the entire app lifetime.
+/// All transitions (intra-book track boundaries, cross-book swaps) go through
+/// `replaceCurrentItem` on the same player. The player is never destroyed,
+/// so iOS keeps granting background audio output across transitions.
+final class AbsorbAudioEngine: NSObject {
+ static let shared = AbsorbAudioEngine()
+
+ static var logSink: ((String) -> Void)?
+
+ weak var delegate: AbsorbAudioEngineDelegate?
+
+ private let queue = DispatchQueue(label: "com.barnabas.absorb.audioengine")
+
+ private let player: AVPlayer = {
+ let p = AVPlayer()
+ p.automaticallyWaitsToMinimizeStalling = false
+ p.allowsExternalPlayback = false
+ return p
+ }()
+
+ // Track list of the currently-loaded book.
+ private var trackUrls: [URL] = []
+ private var trackHeaders: [String: String] = [:]
+ private var trackOffsets: [Double] = [0]
+ private var trackIndex: Int = 0
+ private var totalDurationS: Double = 0
+ private var currentItem: AVPlayerItem?
+ private var currentEpoch: UInt = 0
+
+ // Pre-prepared next book waiting for the cross-book swap.
+ private var nextTrackUrls: [URL] = []
+ private var nextTrackHeaders: [String: String] = [:]
+ private var nextTrackOffsets: [Double] = [0]
+ private var nextTotalDurationS: Double = 0
+ private var nextItem: AVPlayerItem?
+ private var nextStartS: Double = 0
+
+ // Configured player state.
+ private var speed: Float = 1.0
+ private var volume: Float = 1.0
+ private var eqEnabled: Bool = false
+ // Whether the current item physically has the processing tap installed.
+ // Lets us avoid rebuilding the item to re-apply effects when a tap is
+ // already present (it reads the live DSP params on its own).
+ private var tapAttached: Bool = false
+ private var processingState: EngineProcessingState = .idle
+
+ // Observers.
+ private var timeObserver: Any?
+ private var itemEndObserver: NSObjectProtocol?
+ private var statusObservation: NSKeyValueObservation?
+ private var tcsObservation: NSKeyValueObservation?
+ private var bufferedObservation: NSKeyValueObservation?
+ private var playbackBufferEmptyObs: NSKeyValueObservation?
+
+ // Position emit throttling. Set up a 5 Hz observer; sampling rate to delegate
+ // is 5 Hz foreground, 1 Hz background.
+ private var lastEmittedSecondInt: Int = -1
+ private var isBackgrounded: Bool = false
+
+ private override init() {
+ super.init()
+ addPeriodicTimeObserver()
+ observeAppLifecycle()
+ }
+
+ // MARK: - Public API
+
+ func load(tracks: [(url: URL, headers: [String: String])],
+ trackOffsets: [Double],
+ startPositionS: Double,
+ totalDurationS: Double,
+ speed: Float,
+ volume: Float,
+ eqEnabled: Bool,
+ completion: @escaping (Double?) -> Void) {
+ queue.async { [weak self] in
+ guard let self = self else { completion(nil); return }
+ self.activateSession()
+
+ self.trackUrls = tracks.map { $0.url }
+ self.trackHeaders = tracks.first?.headers ?? [:]
+ self.trackOffsets = Self.normalizeOffsets(trackOffsets, trackCount: tracks.count, totalDurationS: totalDurationS)
+ self.totalDurationS = totalDurationS
+ self.speed = speed
+ self.volume = volume
+ self.eqEnabled = eqEnabled
+ self.player.volume = volume
+
+ let targetIndex = self.trackIndexFor(globalSeconds: startPositionS)
+ self.trackIndex = targetIndex
+ let localStart = max(0, startPositionS - self.trackOffsets[targetIndex])
+
+ self.loadTrack(atIndex: targetIndex, localStart: localStart, autoPlay: false, completion: completion)
+ }
+ }
+
+ func play() {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.activateSession()
+ self.player.play()
+ self.player.rate = self.speed
+ self.emitState()
+ }
+ }
+
+ func pause() {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.player.pause()
+ self.emitState()
+ }
+ }
+
+ func stop() {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.currentItem = nil
+ self.processingState = .idle
+ self.emitState()
+ DispatchQueue.main.async {
+ self.player.pause()
+ self.player.replaceCurrentItem(with: nil)
+ }
+ }
+ }
+
+ /// Seek to `localS` within track `trackIndex` (nil = current track).
+ func seek(toLocalS localS: Double, trackIndex: Int?, completion: @escaping (Bool) -> Void) {
+ queue.async { [weak self] in
+ guard let self = self else { completion(false); return }
+ guard !self.trackUrls.isEmpty else { completion(false); return }
+ let requested = trackIndex ?? self.trackIndex
+ let target = max(0, min(requested, self.trackUrls.count - 1))
+ let localTarget = localS.isFinite ? max(0, localS) : 0
+
+ if target == self.trackIndex, self.currentItem != nil {
+ let wasPlaying = self.player.rate > 0
+ self.player.seek(
+ to: CMTime(seconds: localTarget, preferredTimescale: 1000),
+ toleranceBefore: .zero, toleranceAfter: .zero
+ ) { [weak self] finished in
+ self?.queue.async {
+ self?.emitPositionImmediate()
+ if wasPlaying { self?.player.rate = self?.speed ?? 1.0 }
+ completion(finished)
+ }
+ }
+ } else {
+ let wasPlaying = self.player.rate > 0
+ self.trackIndex = target
+ self.loadTrack(atIndex: target, localStart: localTarget, autoPlay: wasPlaying) { _ in
+ completion(true)
+ }
+ self.delegate?.engineDidChangeTrack(trackIndex: target, totalTracks: self.trackUrls.count)
+ }
+ }
+ }
+
+ func setSpeed(_ newSpeed: Float) {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.speed = newSpeed
+ if self.player.rate > 0 {
+ self.player.rate = newSpeed
+ }
+ }
+ }
+
+ func setVolume(_ newVolume: Float) {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.volume = newVolume
+ self.player.volume = newVolume
+ }
+ }
+
+ func setNextSource(tracks: [(url: URL, headers: [String: String])],
+ trackOffsets: [Double],
+ startPositionS: Double,
+ totalDurationS: Double,
+ completion: @escaping (Bool) -> Void) {
+ queue.async { [weak self] in
+ guard let self = self else { completion(false); return }
+ self.nextTrackUrls = tracks.map { $0.url }
+ self.nextTrackHeaders = tracks.first?.headers ?? [:]
+ self.nextTrackOffsets = Self.normalizeOffsets(trackOffsets, trackCount: tracks.count, totalDurationS: totalDurationS)
+ self.nextTotalDurationS = totalDurationS
+ self.nextStartS = startPositionS
+
+ guard let firstUrl = tracks.first?.url else {
+ self.nextItem = nil
+ completion(false)
+ return
+ }
+ let item = self.makePlayerItem(url: firstUrl, headers: tracks.first?.headers ?? [:])
+ let asset = item.asset
+ asset.loadValuesAsynchronously(forKeys: ["tracks", "duration"]) { [weak self] in
+ guard let self = self else { return }
+ var err: NSError?
+ let status = asset.statusOfValue(forKey: "tracks", error: &err)
+ if status != .loaded {
+ self.emit("[AudioEngine] setNextSource: tracks not loaded status=\(status.rawValue) err=\(err?.localizedDescription ?? "nil")")
+ self.queue.async {
+ self.nextItem = nil
+ completion(false)
+ }
+ return
+ }
+ self.queue.async {
+ self.nextItem = item
+ self.emit("[AudioEngine] setNextSource prepared: \(firstUrl.lastPathComponent)")
+ completion(true)
+ }
+ }
+ }
+ }
+
+ func clearNextSource() {
+ queue.async { [weak self] in
+ self?.nextTrackUrls = []
+ self?.nextTrackHeaders = [:]
+ self?.nextTrackOffsets = [0]
+ self?.nextTotalDurationS = 0
+ self?.nextStartS = 0
+ self?.nextItem = nil
+ }
+ }
+
+ /// Ensure the processing tap is live so EQ/effects apply. A tap can't be
+ /// added to an already-playing item, so if one isn't attached we rebuild the
+ /// current track in place (brief reload). If a tap is already present it
+ /// reads the live DSP params itself - nothing to do.
+ func attachEqualizerTap() {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.eqEnabled = true
+ if self.tapAttached { return }
+ guard let item = self.currentItem else { return }
+ if self.player.rate > 0 {
+ let local = item.currentTime().seconds
+ self.loadTrack(atIndex: self.trackIndex,
+ localStart: local.isFinite ? max(0, local) : 0,
+ autoPlay: true) { _ in }
+ } else {
+ AbsorbAudioEQProcessor.shared.attachTapSync(to: item)
+ self.tapAttached = true
+ }
+ }
+ }
+
+ /// Stop applying effects. Lazy: the DSP params are already zeroed by the
+ /// caller, so the tap (if attached) just passes through. We leave it in place
+ /// to avoid a reload blip; it won't reattach on the next track load.
+ func detachEqualizerTap() {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ self.eqEnabled = false
+ }
+ }
+
+ /// Track-local position; Dart adds the track offset (just_audio contract).
+ func getPositionS() -> Double {
+ let local = player.currentItem?.currentTime().seconds ?? 0
+ return local.isFinite ? max(0, local) : 0
+ }
+
+ func getBufferedPositionS() -> Double {
+ guard let item = player.currentItem else { return 0 }
+ guard let last = item.loadedTimeRanges.last as? NSValue else { return 0 }
+ let range = last.timeRangeValue
+ let bufferedLocal = CMTimeGetSeconds(range.start + range.duration)
+ return bufferedLocal.isFinite ? max(0, bufferedLocal) : 0
+ }
+
+ // MARK: - Track loading
+
+ private func loadTrack(atIndex index: Int,
+ localStart: Double,
+ autoPlay: Bool,
+ completion: @escaping (Double?) -> Void) {
+ guard index < trackUrls.count else { completion(nil); return }
+ let url = trackUrls[index]
+ let headers = trackHeaders
+ let eqEnabled = self.eqEnabled
+
+ let item = makePlayerItem(url: url, headers: headers)
+ currentEpoch &+= 1
+ let myEpoch = currentEpoch
+ processingState = .loading
+ emitState()
+
+ // Preload tracks so the EQ tap can attach synchronously before playback
+ // (attachTapSync), and so load failures surface early.
+ let asset = item.asset
+ asset.loadValuesAsynchronously(forKeys: ["tracks", "duration"]) { [weak self] in
+ guard let self = self else { completion(nil); return }
+ var err: NSError?
+ let status = asset.statusOfValue(forKey: "tracks", error: &err)
+ if status != .loaded {
+ self.emit("[AudioEngine] loadTrack idx=\(index) tracks-load failed status=\(status.rawValue) err=\(err?.localizedDescription ?? "nil")")
+ }
+ DispatchQueue.main.async { [weak self] in
+ guard let self = self else { completion(nil); return }
+ guard self.currentEpoch == myEpoch else {
+ self.queue.async {
+ self.emit("[AudioEngine] loadTrack idx=\(index) skipped (stale epoch)")
+ completion(nil)
+ }
+ return
+ }
+ // Detach the outgoing item before promoting the new one, so its EQ
+ // detach can't wipe the attach below.
+ self.detachCurrentItem()
+ self.currentItem = item
+ self.observeNewCurrentItem(item)
+ if eqEnabled {
+ // audioMix must be set before playback starts or the tap is ignored.
+ AbsorbAudioEQProcessor.shared.attachTapSync(to: item)
+ self.tapAttached = true
+ } else {
+ self.tapAttached = false
+ }
+ self.player.replaceCurrentItem(with: item)
+
+ let finish: (Bool) -> Void = { _ in
+ if autoPlay {
+ self.player.play()
+ self.player.rate = self.speed
+ }
+ self.queue.async {
+ self.emit("[AudioEngine] loadTrack idx=\(index) localStart=\(localStart) autoPlay=\(autoPlay)")
+ completion(self.totalDurationS > 0 ? self.totalDurationS : nil)
+ }
+ }
+
+ if localStart > 0 {
+ item.seek(to: CMTime(seconds: localStart, preferredTimescale: 1000),
+ toleranceBefore: .zero, toleranceAfter: .zero, completionHandler: finish)
+ } else {
+ finish(true)
+ }
+ }
+ }
+ }
+
+ private func makePlayerItem(url: URL, headers: [String: String]) -> AVPlayerItem {
+ var options: [String: Any] = [:]
+ if !headers.isEmpty {
+ options["AVURLAssetHTTPHeaderFieldsKey"] = headers
+ }
+ let asset = AVURLAsset(url: url, options: options)
+ let item = AVPlayerItem(asset: asset)
+ item.audioTimePitchAlgorithm = .timeDomain
+ return item
+ }
+
+ private func detachCurrentItem() {
+ if let item = currentItem, eqEnabled {
+ AbsorbAudioEQProcessor.shared.detach(from: item)
+ }
+ if let prev = itemEndObserver {
+ NotificationCenter.default.removeObserver(prev)
+ itemEndObserver = nil
+ }
+ statusObservation?.invalidate()
+ statusObservation = nil
+ tcsObservation?.invalidate()
+ tcsObservation = nil
+ bufferedObservation?.invalidate()
+ bufferedObservation = nil
+ playbackBufferEmptyObs?.invalidate()
+ playbackBufferEmptyObs = nil
+ }
+
+ private func observeNewCurrentItem(_ item: AVPlayerItem) {
+ itemEndObserver = NotificationCenter.default.addObserver(
+ forName: .AVPlayerItemDidPlayToEndTime,
+ object: item,
+ queue: nil
+ ) { [weak self] _ in
+ self?.queue.async { self?.handleItemEnd() }
+ }
+
+ statusObservation = item.observe(\.status, options: [.new]) { [weak self] item, _ in
+ self?.queue.async {
+ switch item.status {
+ case .readyToPlay:
+ self?.processingState = .ready
+ self?.emitState()
+ let d = item.asset.duration.seconds
+ if d.isFinite { self?.delegate?.engineDidLoadDuration(d) }
+ case .failed:
+ self?.processingState = .idle
+ self?.emit("[AudioEngine] item failed: \(item.error?.localizedDescription ?? "unknown")")
+ self?.delegate?.engineDidError(message: item.error?.localizedDescription ?? "item failed", code: nil)
+ default:
+ break
+ }
+ }
+ }
+
+ tcsObservation = player.observe(\.timeControlStatus, options: [.new]) { [weak self] _, _ in
+ self?.queue.async {
+ guard let self = self else { return }
+ switch self.player.timeControlStatus {
+ case .paused:
+ if self.processingState == .buffering { self.processingState = .ready }
+ case .waitingToPlayAtSpecifiedRate:
+ self.processingState = .buffering
+ case .playing:
+ self.processingState = .ready
+ @unknown default:
+ break
+ }
+ self.emitState()
+ }
+ }
+
+ playbackBufferEmptyObs = item.observe(\.isPlaybackBufferEmpty, options: [.new]) { [weak self] item, _ in
+ self?.queue.async {
+ if item.isPlaybackBufferEmpty {
+ self?.processingState = .buffering
+ self?.emitState()
+ }
+ }
+ }
+ }
+
+ private func handleItemEnd() {
+ let nextTrack = trackIndex + 1
+ if nextTrack < trackUrls.count {
+ trackIndex = nextTrack
+ // Player is paused now that the item ended; reading player.rate would
+ // wrongly report autoPlay=false. Intra-book advance should keep playing.
+ loadTrack(atIndex: nextTrack, localStart: 0, autoPlay: true) { _ in }
+ delegate?.engineDidChangeTrack(trackIndex: nextTrack, totalTracks: trackUrls.count)
+ return
+ }
+
+ if nextItem != nil {
+ swapToNextBook()
+ return
+ }
+
+ processingState = .completed
+ emitState()
+ delegate?.engineDidCompleteBook()
+ }
+
+ private func swapToNextBook() {
+ guard let item = nextItem else { return }
+
+ detachCurrentItem()
+
+ trackUrls = nextTrackUrls
+ trackHeaders = nextTrackHeaders
+ trackOffsets = nextTrackOffsets
+ totalDurationS = nextTotalDurationS
+ trackIndex = 0
+
+ currentItem = item
+ currentEpoch &+= 1
+
+ observeNewCurrentItem(item)
+
+ let startS = nextStartS
+ // Inline clear so the next swap can be armed before our async block runs.
+ nextTrackUrls = []
+ nextTrackHeaders = [:]
+ nextTrackOffsets = [0]
+ nextTotalDurationS = 0
+ nextStartS = 0
+ nextItem = nil
+
+ DispatchQueue.main.async { [weak self] in
+ guard let self = self else { return }
+ if self.eqEnabled {
+ // audioMix must be set before playback starts or the tap is ignored.
+ AbsorbAudioEQProcessor.shared.attachTapSync(to: item)
+ self.tapAttached = true
+ } else {
+ self.tapAttached = false
+ }
+ self.player.replaceCurrentItem(with: item)
+ if startS > 0 {
+ item.seek(to: CMTime(seconds: startS, preferredTimescale: 1000),
+ toleranceBefore: .zero, toleranceAfter: .zero) { _ in
+ self.queue.async {
+ self.player.play()
+ self.player.rate = self.speed
+ self.emit("[AudioEngine] swapToNextBook done at startS=\(startS) rate=\(self.player.rate)")
+ self.delegate?.engineDidAutoAdvance()
+ self.delegate?.engineDidLoadDuration(self.totalDurationS > 0 ? self.totalDurationS : nil)
+ }
+ }
+ } else {
+ self.player.play()
+ self.player.rate = self.speed
+ self.queue.async {
+ self.emit("[AudioEngine] swapToNextBook done at startS=0 rate=\(self.player.rate)")
+ self.delegate?.engineDidAutoAdvance()
+ self.delegate?.engineDidLoadDuration(self.totalDurationS > 0 ? self.totalDurationS : nil)
+ }
+ }
+ }
+ }
+
+ // MARK: - Audio session
+
+ private func activateSession() {
+ let session = AVAudioSession.sharedInstance()
+ do {
+ if session.category != .playback {
+ try session.setCategory(.playback, mode: .spokenAudio, policy: .longFormAudio)
+ }
+ try session.setActive(true)
+ } catch {
+ emit("[AudioEngine] session activate failed: \(error.localizedDescription)")
+ }
+ }
+
+ // MARK: - Position emit + lifecycle
+
+ private func addPeriodicTimeObserver() {
+ let interval = CMTime(seconds: 0.2, preferredTimescale: 1000)
+ timeObserver = player.addPeriodicTimeObserver(
+ forInterval: interval, queue: .main
+ ) { [weak self] _ in
+ self?.queue.async { self?.maybeEmitPosition() }
+ }
+ }
+
+ private func maybeEmitPosition() {
+ let pos = getPositionS()
+ guard pos.isFinite else { return }
+ let posInt = Int(pos)
+ let stride = isBackgrounded ? 1 : 0
+ if isBackgrounded {
+ if posInt == lastEmittedSecondInt { return }
+ lastEmittedSecondInt = posInt
+ } else {
+ // Foreground: emit every observer tick (~5 Hz).
+ _ = stride
+ }
+ delegate?.engineDidEmitPosition(pos)
+ }
+
+ private func emitPositionImmediate() {
+ let pos = getPositionS()
+ guard pos.isFinite else { return }
+ lastEmittedSecondInt = Int(pos)
+ delegate?.engineDidEmitPosition(pos)
+ }
+
+ private func emitState() {
+ let snap = EngineStateSnapshot(
+ playing: player.rate > 0 || player.timeControlStatus == .playing,
+ processingState: processingState,
+ timeControlStatus: player.timeControlStatus.rawValue,
+ reasonForWaitingToPlay: player.reasonForWaitingToPlay?.rawValue
+ )
+ delegate?.engineDidChangeState(snap)
+ }
+
+ private func observeAppLifecycle() {
+ NotificationCenter.default.addObserver(
+ forName: UIApplication.didEnterBackgroundNotification,
+ object: nil, queue: .main
+ ) { [weak self] _ in self?.queue.async { self?.isBackgrounded = true } }
+ NotificationCenter.default.addObserver(
+ forName: UIApplication.willEnterForegroundNotification,
+ object: nil, queue: .main
+ ) { [weak self] _ in self?.queue.async { self?.isBackgrounded = false } }
+ }
+
+ // MARK: - Helpers
+
+ private func trackIndexFor(globalSeconds: Double) -> Int {
+ if globalSeconds <= 0 { return 0 }
+ let trackCount = max(1, trackOffsets.count - 1)
+ for i in 0..<trackCount {
+ let nextOffset = i + 1 < trackOffsets.count ? trackOffsets[i + 1] : .greatestFiniteMagnitude
+ if globalSeconds < nextOffset { return i }
+ }
+ return trackCount - 1
+ }
+
+ private static func normalizeOffsets(_ offsets: [Double],
+ trackCount: Int,
+ totalDurationS: Double) -> [Double] {
+ // Expect length = trackCount + 1, cumulative starting at 0. Fall back to
+ // single-track if the caller passed nothing usable.
+ if offsets.count == trackCount + 1, offsets.first == 0 {
+ return offsets
+ }
+ if trackCount <= 1 || totalDurationS <= 0 {
+ return [0, totalDurationS > 0 ? totalDurationS : .greatestFiniteMagnitude]
+ }
+ var out: [Double] = [0]
+ let perTrack = totalDurationS / Double(trackCount)
+ for i in 1...trackCount { out.append(perTrack * Double(i)) }
+ return out
+ }
+
+ private func emit(_ line: String) {
+ NSLog("%@", line)
+ Self.logSink?(line)
+ }
+}
diff --git a/ios/Runner/Audio/AbsorbAudioEngineEvents.swift b/ios/Runner/Audio/AbsorbAudioEngineEvents.swift
new file mode 100644
index 00000000..c4e49ed1
--- /dev/null
+++ b/ios/Runner/Audio/AbsorbAudioEngineEvents.swift
@@ -0,0 +1,27 @@
+import Foundation
+
+enum EngineProcessingState: Int {
+ case idle = 0
+ case loading = 1
+ case buffering = 2
+ case ready = 3
+ case completed = 4
+}
+
+struct EngineStateSnapshot {
+ let playing: Bool
+ let processingState: EngineProcessingState
+ let timeControlStatus: Int
+ let reasonForWaitingToPlay: String?
+}
+
+protocol AbsorbAudioEngineDelegate: AnyObject {
+ func engineDidEmitPosition(_ positionS: Double)
+ func engineDidChangeState(_ state: EngineStateSnapshot)
+ func engineDidLoadDuration(_ durationS: Double?)
+ func engineDidChangeTrack(trackIndex: Int, totalTracks: Int)
+ func engineDidCompleteBook()
+ func engineDidAutoAdvance()
+ func engineDidEmitBufferedPosition(_ bufferedPositionS: Double)
+ func engineDidError(message: String, code: String?)
+}
diff --git a/ios/Runner/Audio/AudioEQProcessor.h b/ios/Runner/Audio/AudioEQProcessor.h
new file mode 100644
index 00000000..a2d5b6d2
--- /dev/null
+++ b/ios/Runner/Audio/AudioEQProcessor.h
@@ -0,0 +1,48 @@
+#import <Foundation/Foundation.h>
+#import <AVFoundation/AVFoundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/// Singleton that owns EQ DSP state and attaches MTAudioProcessingTap
+/// to AVPlayerItems for real-time audio equalisation on iOS.
+@interface AbsorbAudioEQProcessor : NSObject
+
+@property (class, readonly) AbsorbAudioEQProcessor *shared;
+
+/// Attach a processing tap to the given player item. Asset tracks load
+/// asynchronously; `shouldStillAttach` is invoked just before the audio mix
+/// is assigned so the caller can bail out if the item has been replaced.
+- (void)attachTapToPlayerItem:(AVPlayerItem *)item
+ shouldStillAttach:(BOOL (^_Nullable)(void))shouldStillAttach;
+
+/// Attach the tap synchronously (asset tracks must already be loaded). Call
+/// before playback starts - a tap installed after is silently ignored.
+- (void)attachTapSyncToPlayerItem:(AVPlayerItem *)item;
+
+/// Detach the tap by clearing the player item's audioMix.
+- (void)detachFromPlayerItem:(AVPlayerItem *)item;
+
+/// Master EQ enable/disable.
+- (void)setEnabled:(BOOL)enabled;
+
+/// Set a single band level in millibels (e.g. -1500 to +1500 for +/-15 dB).
+/// @param band Band index 0-4.
+/// @param level Level in millibels.
+- (void)setBandLevel:(int)level forBand:(int)band;
+
+/// Set bass boost strength (0-1000).
+- (void)setBassBoostStrength:(int)strength;
+
+/// Set loudness gain in millibels (added on top of output).
+- (void)setLoudnessGain:(int)gainMb;
+
+/// Enable mono downmix.
+- (void)setMonoEnabled:(BOOL)enabled;
+
+/// Sets a callback that gets each `[EQDiag]` line emitted from
+/// tapPrepare so callers can route format info into their own logger.
++ (void)setFormatLogger:(nullable void (^)(NSString *line))logger;
+
+@end
+
+NS_ASSUME_NONNULL_END
diff --git a/ios/Runner/Audio/AudioEQProcessor.m b/ios/Runner/Audio/AudioEQProcessor.m
new file mode 100644
index 00000000..b3225b0b
--- /dev/null
+++ b/ios/Runner/Audio/AudioEQProcessor.m
@@ -0,0 +1,473 @@
+#import "AudioEQProcessor.h"
+#import <MediaToolbox/MediaToolbox.h>
+#import <Accelerate/Accelerate.h>
+#import <stdatomic.h>
+#import <math.h>
+
+#define EQ_NUM_BANDS 5
+#define MAX_CHANNELS 2
+
+static const float kBandFrequencies[EQ_NUM_BANDS] = {60.0f, 230.0f, 910.0f, 3600.0f, 14000.0f};
+static const float kDefaultQ = 1.4f;
+
+typedef struct {
+ float b0, b1, b2, a1, a2;
+} BiquadCoeffs;
+
+typedef struct {
+ float x1, x2;
+ float y1, y2;
+} BiquadDelay;
+
+typedef struct {
+ _Atomic(int) enabled;
+ _Atomic(int) mono;
+ _Atomic(int) loudnessGainMb;
+ _Atomic(int) bassBoostStrength;
+ _Atomic(int) bandLevels[EQ_NUM_BANDS];
+ _Atomic(int) coeffVersion;
+} EQParams;
+
+typedef struct {
+ BiquadDelay delays[EQ_NUM_BANDS][MAX_CHANNELS];
+ BiquadDelay bassDelay[MAX_CHANNELS];
+ BiquadCoeffs coeffs[EQ_NUM_BANDS];
+ BiquadCoeffs bassCoeffs;
+ float sampleRate;
+ int numChannels;
+ int lastCoeffVersion;
+} TapContext;
+
+static EQParams sParams;
+
+/// Peaking EQ filter coefficients (constant-Q).
+static BiquadCoeffs peakingEQ(float f0, float dBGain, float Q, float Fs) {
+ BiquadCoeffs c = {1, 0, 0, 0, 0};
+ if (Fs <= 0) return c;
+
+ float A = powf(10.0f, dBGain / 40.0f);
+ float w0 = 2.0f * M_PI * f0 / Fs;
+ float sinw = sinf(w0);
+ float cosw = cosf(w0);
+ float alpha = sinw / (2.0f * Q);
+
+ float a0 = 1.0f + alpha / A;
+ c.b0 = (1.0f + alpha * A) / a0;
+ c.b1 = (-2.0f * cosw) / a0;
+ c.b2 = (1.0f - alpha * A) / a0;
+ c.a1 = (-2.0f * cosw) / a0;
+ c.a2 = (1.0f - alpha / A) / a0;
+ return c;
+}
+
+/// Low-shelf filter coefficients for bass boost.
+static BiquadCoeffs lowShelf(float f0, float dBGain, float Fs) {
+ BiquadCoeffs c = {1, 0, 0, 0, 0};
+ if (Fs <= 0) return c;
+
+ float A = powf(10.0f, dBGain / 40.0f);
+ float w0 = 2.0f * M_PI * f0 / Fs;
+ float sinw = sinf(w0);
+ float cosw = cosf(w0);
+ float alpha = sinw / 2.0f * sqrtf((A + 1.0f / A) * (1.0f / 0.7071f - 1.0f) + 2.0f);
+ float sqrtA2alpha = 2.0f * sqrtf(A) * alpha;
+
+ float a0 = (A + 1.0f) + (A - 1.0f) * cosw + sqrtA2alpha;
+ c.b0 = (A * ((A + 1.0f) - (A - 1.0f) * cosw + sqrtA2alpha)) / a0;
+ c.b1 = (2.0f * A * ((A - 1.0f) - (A + 1.0f) * cosw)) / a0;
+ c.b2 = (A * ((A + 1.0f) - (A - 1.0f) * cosw - sqrtA2alpha)) / a0;
+ c.a1 = (-2.0f * ((A - 1.0f) + (A + 1.0f) * cosw)) / a0;
+ c.a2 = ((A + 1.0f) + (A - 1.0f) * cosw - sqrtA2alpha) / a0;
+ return c;
+}
+
+static inline float processBiquad(BiquadCoeffs *c, BiquadDelay *d, float x) {
+ float y = c->b0 * x + c->b1 * d->x1 + c->b2 * d->x2
+ - c->a1 * d->y1 - c->a2 * d->y2;
+ d->x2 = d->x1;
+ d->x1 = x;
+ d->y2 = d->y1;
+ d->y1 = y;
+ return y;
+}
+
+static void rebuildCoefficients(TapContext *ctx) {
+ float Fs = ctx->sampleRate;
+ // Clamp band frequencies below Nyquist with 5% headroom. A peaking
+ // biquad at f0 >= Fs/2 puts the filter poles outside the unit circle,
+ // the filter blows up, samples turn into NaN, and the output goes
+ // silent. Low-bitrate AAC m4b decodes to 22050Hz so the 14kHz band
+ // tripped this without the clamp.
+ float maxBandHz = (Fs * 0.5f) * 0.95f;
+ for (int i = 0; i < EQ_NUM_BANDS; i++) {
+ float dBGain = (float)atomic_load_explicit(&sParams.bandLevels[i], memory_order_relaxed) / 100.0f;
+ float bandHz = kBandFrequencies[i];
+ if (bandHz >= maxBandHz) {
+ BiquadCoeffs unity = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f};
+ ctx->coeffs[i] = unity;
+ } else {
+ ctx->coeffs[i] = peakingEQ(bandHz, dBGain, kDefaultQ, Fs);
+ }
+ }
+
+ int bassStrength = atomic_load_explicit(&sParams.bassBoostStrength, memory_order_relaxed);
+ float bassdB = (float)bassStrength / 1000.0f * 12.0f;
+ if (120.0f >= maxBandHz) {
+ BiquadCoeffs unity = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f};
+ ctx->bassCoeffs = unity;
+ } else {
+ ctx->bassCoeffs = lowShelf(120.0f, bassdB, Fs);
+ }
+
+ ctx->lastCoeffVersion = atomic_load_explicit(&sParams.coeffVersion, memory_order_relaxed);
+}
+
+static void tapInit(MTAudioProcessingTapRef tap, void *clientInfo, void **tapStorageOut) {
+ TapContext *ctx = (TapContext *)calloc(1, sizeof(TapContext));
+ *tapStorageOut = ctx;
+}
+
+static void tapFinalize(MTAudioProcessingTapRef tap) {
+ TapContext *ctx = (TapContext *)MTAudioProcessingTapGetStorage(tap);
+ if (ctx) free(ctx);
+}
+
+static void (^sFormatLogger)(NSString *) = NULL;
+
+static void tapPrepare(MTAudioProcessingTapRef tap,
+ CMItemCount maxFrames,
+ const AudioStreamBasicDescription *processingFormat) {
+ TapContext *ctx = (TapContext *)MTAudioProcessingTapGetStorage(tap);
+ if (!ctx) return;
+
+ ctx->sampleRate = (float)processingFormat->mSampleRate;
+ ctx->numChannels = (int)processingFormat->mChannelsPerFrame;
+ int truncated = 0;
+ if (ctx->numChannels > MAX_CHANNELS) {
+ truncated = ctx->numChannels;
+ ctx->numChannels = MAX_CHANNELS;
+ }
+
+ memset(ctx->delays, 0, sizeof(ctx->delays));
+ memset(ctx->bassDelay, 0, sizeof(ctx->bassDelay));
+
+ rebuildCoefficients(ctx);
+
+ // Dump the post-decode PCM format so "tap enabled produces silence"
+ // reports can be correlated to specific format fingerprints (e.g. low
+ // bitrate AAC at 22050Hz mono).
+ int enabled = atomic_load_explicit(&sParams.enabled, memory_order_relaxed);
+ UInt32 fmtID = processingFormat->mFormatID;
+ char fmtIDChars[5] = {
+ (char)((fmtID >> 24) & 0xff),
+ (char)((fmtID >> 16) & 0xff),
+ (char)((fmtID >> 8) & 0xff),
+ (char)(fmtID & 0xff),
+ 0
+ };
+ UInt32 flags = processingFormat->mFormatFlags;
+ NSString *line = [NSString stringWithFormat:
+ @"[EQDiag] tapPrepare enabled=%d sampleRate=%.1f channels=%u (truncated_from=%d) "
+ @"formatID='%s' flags=0x%x [%s%s%s%s%s%s] bitsPerChannel=%u "
+ @"bytesPerFrame=%u framesPerPacket=%u maxFrames=%lld",
+ enabled,
+ processingFormat->mSampleRate,
+ (unsigned)processingFormat->mChannelsPerFrame,
+ truncated,
+ fmtIDChars,
+ (unsigned)flags,
+ (flags & 0x1) ? "Float " : "",
+ (flags & 0x2) ? "BigEndian " : "",
+ (flags & 0x4) ? "SignedInt " : "",
+ (flags & 0x8) ? "Packed " : "",
+ (flags & 0x10) ? "AlignedHigh " : "",
+ (flags & 0x20) ? "NonInterleaved" : "Interleaved",
+ (unsigned)processingFormat->mBitsPerChannel,
+ (unsigned)processingFormat->mBytesPerFrame,
+ (unsigned)processingFormat->mFramesPerPacket,
+ (long long)maxFrames];
+ NSLog(@"%@", line);
+ if (sFormatLogger) sFormatLogger(line);
+}
+
+static void tapUnprepare(MTAudioProcessingTapRef tap) {
+}
+
+static void tapProcess(MTAudioProcessingTapRef tap,
+ CMItemCount numberFrames,
+ MTAudioProcessingTapFlags flags,
+ AudioBufferList *bufferListInOut,
+ CMItemCount *numberFramesOut,
+ MTAudioProcessingTapFlags *flagsOut) {
+ OSStatus status = MTAudioProcessingTapGetSourceAudio(tap, numberFrames, bufferListInOut,
+ flagsOut, NULL, numberFramesOut);
+ if (status != noErr) return;
+
+ int bandsOn = atomic_load_explicit(&sParams.enabled, memory_order_relaxed);
+ int mono = atomic_load_explicit(&sParams.mono, memory_order_relaxed);
+ int loudnessMb = atomic_load_explicit(&sParams.loudnessGainMb, memory_order_relaxed);
+ int hasBass = atomic_load_explicit(&sParams.bassBoostStrength, memory_order_relaxed) > 0;
+
+ // Bass / loudness / mono apply independently of the band-EQ master switch,
+ // so process whenever any of them is active - not only when bands are on.
+ if (!bandsOn && !mono && loudnessMb <= 0 && !hasBass) return;
+
+ TapContext *ctx = (TapContext *)MTAudioProcessingTapGetStorage(tap);
+ if (!ctx) return;
+
+ int currentVersion = atomic_load_explicit(&sParams.coeffVersion, memory_order_relaxed);
+ if (currentVersion != ctx->lastCoeffVersion) {
+ rebuildCoefficients(ctx);
+ }
+
+ float loudnessGain = (loudnessMb > 0) ? powf(10.0f, (float)loudnessMb / 2000.0f) : 1.0f;
+
+ UInt32 numBuffers = bufferListInOut->mNumberBuffers;
+ CMItemCount frames = *numberFramesOut;
+
+ BOOL nonInterleaved = (numBuffers > 1 && bufferListInOut->mBuffers[0].mNumberChannels == 1);
+
+ if (nonInterleaved) {
+ int totalChans = (int)numBuffers;
+ if (totalChans > MAX_CHANNELS) totalChans = MAX_CHANNELS;
+
+ for (int ch = 0; ch < totalChans; ch++) {
+ float *data = (float *)bufferListInOut->mBuffers[ch].mData;
+ if (!data) continue;
+
+ for (CMItemCount f = 0; f < frames; f++) {
+ float sample = data[f];
+
+ if (bandsOn) {
+ for (int band = 0; band < EQ_NUM_BANDS; band++) {
+ sample = processBiquad(&ctx->coeffs[band], &ctx->delays[band][ch], sample);
+ }
+ }
+
+ if (hasBass) {
+ sample = processBiquad(&ctx->bassCoeffs, &ctx->bassDelay[ch], sample);
+ }
+
+ if (loudnessMb > 0) {
+ sample *= loudnessGain;
+ }
+
+ data[f] = sample;
+ }
+ }
+
+ if (mono && totalChans >= 2) {
+ float *L = (float *)bufferListInOut->mBuffers[0].mData;
+ float *R = (float *)bufferListInOut->mBuffers[1].mData;
+ if (L && R) {
+ for (CMItemCount f = 0; f < frames; f++) {
+ float avg = (L[f] + R[f]) * 0.5f;
+ L[f] = avg;
+ R[f] = avg;
+ }
+ }
+ }
+ } else {
+ for (UInt32 buf = 0; buf < numBuffers; buf++) {
+ AudioBuffer *ab = &bufferListInOut->mBuffers[buf];
+ float *data = (float *)ab->mData;
+ if (!data) continue;
+
+ int chansInBuf = ab->mNumberChannels;
+
+ for (CMItemCount f = 0; f < frames; f++) {
+ for (int ch = 0; ch < chansInBuf && ch < MAX_CHANNELS; ch++) {
+ float sample = data[f * chansInBuf + ch];
+
+ if (bandsOn) {
+ for (int band = 0; band < EQ_NUM_BANDS; band++) {
+ sample = processBiquad(&ctx->coeffs[band], &ctx->delays[band][ch], sample);
+ }
+ }
+
+ if (hasBass) {
+ sample = processBiquad(&ctx->bassCoeffs, &ctx->bassDelay[ch], sample);
+ }
+
+ if (loudnessMb > 0) {
+ sample *= loudnessGain;
+ }
+
+ data[f * chansInBuf + ch] = sample;
+ }
+
+ if (mono && chansInBuf >= 2) {
+ float avg = (data[f * chansInBuf] + data[f * chansInBuf + 1]) * 0.5f;
+ data[f * chansInBuf] = avg;
+ data[f * chansInBuf + 1] = avg;
+ }
+ }
+ }
+ }
+}
+
+@implementation AbsorbAudioEQProcessor
+
++ (AbsorbAudioEQProcessor *)shared {
+ static AbsorbAudioEQProcessor *instance = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ instance = [[AbsorbAudioEQProcessor alloc] init];
+ });
+ return instance;
+}
+
++ (void)setFormatLogger:(void (^)(NSString *))logger {
+ sFormatLogger = [logger copy];
+}
+
+- (instancetype)init {
+ self = [super init];
+ if (self) {
+ atomic_store(&sParams.enabled, 0);
+ atomic_store(&sParams.mono, 0);
+ atomic_store(&sParams.loudnessGainMb, 0);
+ atomic_store(&sParams.bassBoostStrength, 0);
+ atomic_store(&sParams.coeffVersion, 0);
+ for (int i = 0; i < EQ_NUM_BANDS; i++) {
+ atomic_store(&sParams.bandLevels[i], 0);
+ }
+ }
+ return self;
+}
+
+- (void)attachTapToPlayerItem:(AVPlayerItem *)item
+ shouldStillAttach:(BOOL (^)(void))shouldStillAttach {
+ if (!item) return;
+
+ MTAudioProcessingTapCallbacks callbacks;
+ callbacks.version = kMTAudioProcessingTapCallbacksVersion_0;
+ callbacks.clientInfo = (__bridge void *)self;
+ callbacks.init = tapInit;
+ callbacks.finalize = tapFinalize;
+ callbacks.prepare = tapPrepare;
+ callbacks.unprepare = tapUnprepare;
+ callbacks.process = tapProcess;
+
+ MTAudioProcessingTapRef tap = NULL;
+ OSStatus status = MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks,
+ kMTAudioProcessingTapCreationFlag_PostEffects,
+ &tap);
+ if (status != noErr || !tap) {
+ NSLog(@"[AudioEQProcessor] Failed to create tap: %d", (int)status);
+ return;
+ }
+
+ AVAsset *asset = item.asset;
+ [asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:^{
+ NSError *error = nil;
+ AVKeyValueStatus trackStatus = [asset statusOfValueForKey:@"tracks" error:&error];
+ if (trackStatus != AVKeyValueStatusLoaded) {
+ NSLog(@"[AudioEQProcessor] Tracks not loaded: %@", error);
+ CFRelease(tap);
+ return;
+ }
+
+ NSArray<AVAssetTrack *> *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
+ if (audioTracks.count == 0) {
+ NSLog(@"[AudioEQProcessor] No audio tracks found");
+ CFRelease(tap);
+ return;
+ }
+
+ NSMutableArray<AVMutableAudioMixInputParameters *> *inputParams = [NSMutableArray array];
+ for (AVAssetTrack *track in audioTracks) {
+ AVMutableAudioMixInputParameters *params =
+ [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];
+ params.audioTapProcessor = tap;
+ [inputParams addObject:params];
+ }
+
+ AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
+ audioMix.inputParameters = inputParams;
+
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (shouldStillAttach && !shouldStillAttach()) {
+ NSLog(@"[AudioEQProcessor] Item replaced before tap attach, skipping");
+ CFRelease(tap);
+ return;
+ }
+ item.audioMix = audioMix;
+ CFRelease(tap);
+ });
+ }];
+}
+
+- (void)attachTapSyncToPlayerItem:(AVPlayerItem *)item {
+ if (!item) return;
+
+ AVAsset *asset = item.asset;
+ NSArray<AVAssetTrack *> *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
+ if (audioTracks.count == 0) {
+ NSLog(@"[AudioEQProcessor] sync attach: no audio tracks (asset not preloaded?)");
+ return;
+ }
+
+ MTAudioProcessingTapCallbacks callbacks;
+ callbacks.version = kMTAudioProcessingTapCallbacksVersion_0;
+ callbacks.clientInfo = (__bridge void *)self;
+ callbacks.init = tapInit;
+ callbacks.finalize = tapFinalize;
+ callbacks.prepare = tapPrepare;
+ callbacks.unprepare = tapUnprepare;
+ callbacks.process = tapProcess;
+
+ MTAudioProcessingTapRef tap = NULL;
+ OSStatus status = MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks,
+ kMTAudioProcessingTapCreationFlag_PostEffects,
+ &tap);
+ if (status != noErr || !tap) {
+ NSLog(@"[AudioEQProcessor] sync attach: failed to create tap: %d", (int)status);
+ return;
+ }
+
+ NSMutableArray<AVMutableAudioMixInputParameters *> *inputParams = [NSMutableArray array];
+ for (AVAssetTrack *track in audioTracks) {
+ AVMutableAudioMixInputParameters *params =
+ [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];
+ params.audioTapProcessor = tap;
+ [inputParams addObject:params];
+ }
+
+ AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
+ audioMix.inputParameters = inputParams;
+ item.audioMix = audioMix;
+ CFRelease(tap);
+}
+
+- (void)detachFromPlayerItem:(AVPlayerItem *)item {
+ if (!item) return;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ item.audioMix = nil;
+ });
+}
+
+- (void)setEnabled:(BOOL)enabled {
+ atomic_store_explicit(&sParams.enabled, enabled ? 1 : 0, memory_order_relaxed);
+}
+
+- (void)setBandLevel:(int)level forBand:(int)band {
+ if (band < 0 || band >= EQ_NUM_BANDS) return;
+ atomic_store_explicit(&sParams.bandLevels[band], level, memory_order_relaxed);
+ atomic_fetch_add_explicit(&sParams.coeffVersion, 1, memory_order_release);
+}
+
+- (void)setBassBoostStrength:(int)strength {
+ atomic_store_explicit(&sParams.bassBoostStrength, strength, memory_order_relaxed);
+ atomic_fetch_add_explicit(&sParams.coeffVersion, 1, memory_order_release);
+}
+
+- (void)setLoudnessGain:(int)gainMb {
+ atomic_store_explicit(&sParams.loudnessGainMb, gainMb, memory_order_relaxed);
+}
+
+- (void)setMonoEnabled:(BOOL)enabled {
+ atomic_store_explicit(&sParams.mono, enabled ? 1 : 0, memory_order_relaxed);
+}
+
+@end
diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h
index 308a2a56..5a52dba1 100644
--- a/ios/Runner/Runner-Bridging-Header.h
+++ b/ios/Runner/Runner-Bridging-Header.h
@@ -1 +1,2 @@
#import "GeneratedPluginRegistrant.h"
+#import "Audio/AudioEQProcessor.h"
diff --git a/lib/services/_audio_player.dart b/lib/services/_audio_player.dart
new file mode 100644
index 00000000..5088c0d7
--- /dev/null
+++ b/lib/services/_audio_player.dart
@@ -0,0 +1,146 @@
+import 'dart:async';
+import 'dart:io';
+import 'package:just_audio/just_audio.dart' as ja;
+import 'native_ios_audio_player.dart';
+
+// Re-export just_audio's data types so consumers don't need a second import.
+export 'package:just_audio/just_audio.dart'
+ show
+ AudioSource,
+ UriAudioSource,
+ ConcatenatingAudioSource,
+ ProgressiveAudioSource,
+ PlayerState,
+ PlaybackEvent,
+ ProcessingState,
+ AudioLoadConfiguration,
+ AndroidLoadControl,
+ DarwinLoadControl;
+
+/// Platform-aware audio player. Uses the native AVPlayer engine on iOS and
+/// just_audio everywhere else.
+class AudioPlayer {
+ AudioPlayer({
+ bool handleInterruptions = true,
+ bool useProxyForRequestHeaders = true,
+ ja.AudioLoadConfiguration? audioLoadConfiguration,
+ }) {
+ if (Platform.isIOS) {
+ _native = NativeIosAudioPlayer();
+ } else {
+ _ja = ja.AudioPlayer(
+ handleInterruptions: handleInterruptions,
+ useProxyForRequestHeaders: useProxyForRequestHeaders,
+ audioLoadConfiguration: audioLoadConfiguration,
+ );
+ }
+ }
+
+ ja.AudioPlayer? _ja;
+ NativeIosAudioPlayer? _native;
+
+ bool get _isNative => _native != null;
+
+ /// Expose the just_audio inner player for code paths that absolutely need
+ /// it (rare). Null when running on the native engine.
+ ja.AudioPlayer? get jaPlayer => _ja;
+
+ // ─── State getters ───
+
+ Duration get position => _isNative ? _native!.position : _ja!.position;
+ Duration? get duration => _isNative ? _native!.duration : _ja!.duration;
+ Duration get bufferedPosition =>
+ _isNative ? _native!.bufferedPosition : _ja!.bufferedPosition;
+ bool get playing => _isNative ? _native!.playing : _ja!.playing;
+ ja.ProcessingState get processingState =>
+ _isNative ? _native!.processingState : _ja!.processingState;
+ double get speed => _isNative ? _native!.speed : _ja!.speed;
+ double get volume => _isNative ? _native!.volume : _ja!.volume;
+ int? get currentIndex =>
+ _isNative ? _native!.currentIndex : _ja!.currentIndex;
+ int? get androidAudioSessionId =>
+ _isNative ? null : _ja!.androidAudioSessionId;
+ ja.PlaybackEvent get playbackEvent =>
+ _isNative ? _native!.playbackEvent : _ja!.playbackEvent;
+
+ // ─── Streams ───
+
+ Stream<Duration> get positionStream =>
+ _isNative ? _native!.positionStream : _ja!.positionStream;
+ Stream<Duration?> get durationStream =>
+ _isNative ? _native!.durationStream : _ja!.durationStream;
+ Stream<Duration> get bufferedPositionStream =>
+ _isNative ? _native!.bufferedPositionStream : _ja!.bufferedPositionStream;
+ Stream<ja.PlayerState> get playerStateStream =>
+ _isNative ? _native!.playerStateStream : _ja!.playerStateStream;
+ Stream<ja.ProcessingState> get processingStateStream =>
+ _isNative ? _native!.processingStateStream : _ja!.processingStateStream;
+ Stream<ja.PlaybackEvent> get playbackEventStream =>
+ _isNative ? _native!.playbackEventStream : _ja!.playbackEventStream;
+ Stream<int?> get currentIndexStream =>
+ _isNative ? _native!.currentIndexStream : _ja!.currentIndexStream;
+
+ /// Native-only signal that the engine swapped to a pre-buffered next book
+ /// mid-flight. Empty stream on Android - pre-buffer there still uses
+ /// ConcatenatingAudioSource.add and is detected via position-jump.
+ Stream<void> get bookAutoAdvancedStream =>
+ _isNative ? _native!.bookAutoAdvancedStream : const Stream.empty();
+
+ // ─── Source loading ───
+
+ Future<Duration?> setAudioSource(ja.AudioSource source, {
+ Duration? initialPosition,
+ int? initialIndex,
+ bool preload = true,
+ }) async {
+ if (_isNative) {
+ return _native!.setAudioSource(source, initialPosition: initialPosition, initialIndex: initialIndex, preload: preload);
+ }
+ return _ja!.setAudioSource(source, initialPosition: initialPosition, initialIndex: initialIndex, preload: preload);
+ }
+
+ /// Pre-buffer the next book so cross-book transitions are gapless.
+ /// 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 {
+ if (_isNative) {
+ return _native!.setNextSource(source, startPositionS: startPositionS, totalDurationS: totalDurationS);
+ }
+ return false;
+ }
+
+ Future<void> attachEqualizerTap() async {
+ if (_isNative) await _native!.attachEqualizerTap();
+ }
+
+ Future<void> detachEqualizerTap() async {
+ if (_isNative) await _native!.detachEqualizerTap();
+ }
+
+ // ─── Control ───
+
+ Future<void> play() => _isNative ? _native!.play() : _ja!.play();
+ Future<void> pause() => _isNative ? _native!.pause() : _ja!.pause();
+ Future<void> stop() => _isNative ? _native!.stop() : _ja!.stop();
+ Future<void> seek(Duration? position, {int? index}) =>
+ _isNative ? _native!.seek(position, index: index) : _ja!.seek(position, index: index);
+ Future<void> setSpeed(double speed) =>
+ _isNative ? _native!.setSpeed(speed) : _ja!.setSpeed(speed);
+ Future<void> setVolume(double volume) =>
+ _isNative ? _native!.setVolume(volume) : _ja!.setVolume(volume);
+ Future<void> setSkipSilenceEnabled(bool enabled) =>
+ _isNative ? _native!.setSkipSilenceEnabled(enabled) : _ja!.setSkipSilenceEnabled(enabled);
+ Future<Duration?> setAsset(String asset) =>
+ _isNative ? _native!.setAsset(asset) : _ja!.setAsset(asset);
+ Future<void> dispose() =>
+ _isNative ? _native!.dispose() : _ja!.dispose();
+
+ // ─── just_audio-specific configuration (Android path) ───
+
+ static Future<void> configureStreamingCache(int sizeInMB) async {
+ // Forward to just_audio's static. Native iOS engine ignores this and
+ // uses default AVPlayer caching; acceptable for the experimental flag.
+ await ja.AudioPlayer.configureStreamingCache(sizeInMB);
+ }
+}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index d1980c94..b66ea612 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -3,7 +3,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:just_audio/just_audio.dart';
+import '_audio_player.dart';
import 'package:audio_service/audio_service.dart';
import 'package:audio_session/audio_session.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -1000,6 +1000,7 @@ class AudioPlayerService extends ChangeNotifier {
SharedPreferences? _prefs;
StreamSubscription? _syncSub;
StreamSubscription? _completionSub;
+ StreamSubscription? _nativeAutoAdvanceSub;
// ── Pre-buffer next book in queue (iOS background auto-advance fix) ──
// iOS denies background audio output to freshly-loaded AVPlayerItems.
@@ -1050,6 +1051,9 @@ class AudioPlayerService extends ChangeNotifier {
int _iosLastTrackRecoveryAttempts = 0;
static const _maxIosLastTrackRecoveries = 2;
+ // Force one lock-screen state push after an intra-book track advance.
+ bool _pendingTrackAdvanceRefresh = false;
+
// ── Notification chapter progress mode ──
bool _notifChapterMode = false;
double _currentChapterStart = 0;
@@ -1247,6 +1251,25 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
+ if (Platform.isIOS) {
+ // Native engine owns the cross-book swap. Skip concat.add entirely.
+ final source = nextTrackSources.length == 1
+ ? nextTrackSources.first
+ : ConcatenatingAudioSource(children: nextTrackSources);
+ final ok = await _player!.setNextSource(
+ source,
+ startPositionS: startS,
+ totalDurationS: (next['duration'] as num?)?.toDouble() ?? 0,
+ );
+ if (!ok) {
+ debugPrint('[PreBuffer] Native setNextSource failed');
+ return;
+ }
+ _preloadedNextBook = next;
+ debugPrint('[PreBuffer] Pre-loaded native: ${next['title']} ($nextItemId) start=${startS.toStringAsFixed(1)}s');
+ return;
+ }
+
final concat = _activeConcatSource;
if (concat == null) {
debugPrint('[PreBuffer] Concat source went away mid-preload');
@@ -1259,8 +1282,7 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[PreBuffer] Pre-loaded next item: ${next['title']} ($nextItemId)');
if (Platform.isIOS) {
- // Also prime the native handover so the background path can take over
- // without going through just_audio's heavy reload.
+ // Legacy native queue advancer kick (flag-off path).
unawaited(_primeNativeQueueAdvancer(next, localPaths, audioTracks, audioHeaders));
}
} catch (e, st) {
@@ -1621,6 +1643,7 @@ class AudioPlayerService extends ChangeNotifier {
final clamped = index.clamp(0, _trackStartOffsets.length - 2);
if (clamped != _currentTrackIndex) {
_lastIndexAdvanceTime = DateTime.now();
+ _pendingTrackAdvanceRefresh = true;
debugPrint('[Player] Track index advance: $_currentTrackIndex -> $clamped');
}
_currentTrackIndex = clamped;
@@ -1704,6 +1727,21 @@ class AudioPlayerService extends ChangeNotifier {
}
});
}
+ // iOS native engine: keep the processing tap attached whenever any
+ // EQ/effect is active so effects work with the band EQ off.
+ if (Platform.isIOS) {
+ EqualizerService().setTapApplier((active) {
+ try {
+ if (active) {
+ _handler?.player.attachEqualizerTap();
+ } else {
+ _handler?.player.detachEqualizerTap();
+ }
+ } catch (e) {
+ debugPrint('[Player] tap applier failed: $e');
+ }
+ });
+ }
// Initialize cached skip amounts so notification icons show the correct values
_handler!._cachedForwardSkip = fwdSkip;
_handler!._cachedBackSkip = backSkip;
@@ -2076,6 +2114,8 @@ class AudioPlayerService extends ChangeNotifier {
_syncSub = null;
_completionSub?.cancel();
_completionSub = null;
+ _nativeAutoAdvanceSub?.cancel();
+ _nativeAutoAdvanceSub = null;
_indexSub?.cancel();
_indexSub = null;
_lastKnownPositionSec = 0;
@@ -3135,6 +3175,8 @@ class AudioPlayerService extends ChangeNotifier {
_syncSub = null;
_completionSub?.cancel();
_completionSub = null;
+ _nativeAutoAdvanceSub?.cancel();
+ _nativeAutoAdvanceSub = null;
_lastKnownPositionSec = 0;
_bgSaveTimer?.cancel();
@@ -3253,6 +3295,7 @@ class AudioPlayerService extends ChangeNotifier {
void _setupSync() {
_syncSub?.cancel();
_completionSub?.cancel();
+ _nativeAutoAdvanceSub?.cancel();
_bgSaveTimer?.cancel();
_lastSyncSecond = -1;
_lastBgProcessedSec = -1;
@@ -3281,6 +3324,17 @@ class AudioPlayerService extends ChangeNotifier {
// Attach equalizer to current audio session
_attachEqualizer();
+ // Native iOS engine fires bookAutoAdvancedStream when it has swapped to
+ // the pre-buffered next book. Empty stream on Android / iOS-flag-off, so
+ // this is a no-op everywhere else.
+ _nativeAutoAdvanceSub?.cancel();
+ _nativeAutoAdvanceSub = _player?.bookAutoAdvancedStream.listen((_) {
+ if (_preloadedNextBook != null) {
+ debugPrint('[NativeEngine] bookAutoAdvanced received — firing auto-queue advance');
+ _onAutoQueueAdvanced();
+ }
+ });
+
// ─── Primary completion detection via processingState ───
// This fires reliably when ExoPlayer reaches STATE_ENDED, before any
// position-reset can confuse the position-based detection.
@@ -3311,6 +3365,13 @@ class AudioPlayerService extends ChangeNotifier {
final sec = absolutePos.inSeconds;
final posSec = absolutePos.inMilliseconds / 1000.0;
+ // After a track advance, push once now that the new position has landed
+ // so the background lock screen isn't left stale until foreground.
+ if (_pendingTrackAdvanceRefresh) {
+ _pendingTrackAdvanceRefresh = false;
+ _handler?.refreshPlaybackState();
+ }
+
// ─── Position-reset guard ────────────────────────────
// ExoPlayer can seek to 0 on STATE_ENDED. If we were near the end
// and suddenly jump to near 0 without a user seek, treat it as
@@ -3417,6 +3478,11 @@ class AudioPlayerService extends ChangeNotifier {
// ─── Completion detection (fallback) ───────────────────
// processingStateStream is the primary signal; this is a safety net.
if (_totalDuration > 0 && posSec >= _totalDuration - 1.0) {
+ if (_preloadedNextBook != null && _isBackgrounded && Platform.isIOS) {
+ debugPrint('[PreBuffer] Position-fallback near end with pre-buffer loaded — firing auto-queue advance');
+ _onAutoQueueAdvanced();
+ return;
+ }
_onPlaybackComplete();
return;
}
@@ -3698,6 +3764,8 @@ class AudioPlayerService extends ChangeNotifier {
_syncSub = null;
_completionSub?.cancel();
_completionSub = null;
+ _nativeAutoAdvanceSub?.cancel();
+ _nativeAutoAdvanceSub = null;
_bgSaveTimer?.cancel();
_bgSaveTimer = null;
// Android: stop() prevents ExoPlayer's phantom seek-to-0 on completion,
diff --git a/lib/services/download_notification_service.dart b/lib/services/download_notification_service.dart
index 61e2a023..4ecf9f19 100644
--- a/lib/services/download_notification_service.dart
+++ b/lib/services/download_notification_service.dart
@@ -46,6 +46,11 @@ class DownloadNotificationService {
int _activeCount = 0;
+ // Track last shown percent per slot so we can throttle progress updates. iOS
+ // re-banners each notification update (even with the same ID), so even with
+ // passive interruption we want to keep the update rate low.
+ final Map<int, int> _lastShownPercent = {};
+
Future<void> init() async {
if (_initialized) return;
@@ -62,7 +67,7 @@ class DownloadNotificationService {
final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
if (androidPlugin != null) {
- // Progress channel — default importance so the foreground service
+ // Progress channel; default importance so the foreground service
// notification stays visible in the shade without making noise.
await androidPlugin.createNotificationChannel(
AndroidNotificationChannel(
@@ -101,6 +106,7 @@ class DownloadNotificationService {
}) async {
if (!_initialized) await init();
_activeCount++;
+ _lastShownPercent.remove(slot);
// Start foreground service if this is the first download
if (_activeCount == 1) {
@@ -128,6 +134,12 @@ class DownloadNotificationService {
}) async {
if (!_initialized) await init();
final percent = (progress * 100).round().clamp(0, 100);
+
+ // Throttle to 10% increments (plus always emit the 100% completion).
+ final last = _lastShownPercent[slot];
+ if (last != null && percent < 100 && (percent - last) < 10) return;
+ _lastShownPercent[slot] = percent;
+
await _showSlotProgress(
slot: slot,
title: title,
@@ -155,6 +167,7 @@ class DownloadNotificationService {
}
_activeCount = (_activeCount - 1).clamp(0, 99);
+ _lastShownPercent.remove(slot);
if (_activeCount == 0) {
await _stopForeground();
@@ -186,6 +199,7 @@ class DownloadNotificationService {
}
_activeCount = (_activeCount - 1).clamp(0, 99);
+ _lastShownPercent.remove(slot);
if (_activeCount == 0) {
await _stopForeground();
@@ -198,6 +212,7 @@ class DownloadNotificationService {
Future<void> dismiss() async {
await _stopForeground();
_activeCount = 0;
+ _lastShownPercent.clear();
// Cancel all possible slot notifications
for (int i = 0; i < 5; i++) {
try {
@@ -335,7 +350,14 @@ class DownloadNotificationService {
subtitle,
NotificationDetails(
android: androidDetails,
- iOS: const DarwinNotificationDetails(),
+ // Passive interruption: iOS updates the notification without showing
+ // a banner or playing sound on each progress tick.
+ iOS: const DarwinNotificationDetails(
+ presentAlert: false,
+ presentBanner: false,
+ presentSound: false,
+ interruptionLevel: InterruptionLevel.passive,
+ ),
),
);
}
diff --git a/lib/services/equalizer_service.dart b/lib/services/equalizer_service.dart
index 5771d6a0..49921294 100644
--- a/lib/services/equalizer_service.dart
+++ b/lib/services/equalizer_service.dart
@@ -34,6 +34,10 @@ class EqualizerService extends ChangeNotifier {
/// just_audio.
void Function(bool enabled)? _skipSilenceApplier;
+ /// Invoked when [anyProcessingActive] may have changed so the iOS engine can
+ /// attach/detach its processing tap. Registered by AudioPlayerService.
+ void Function(bool active)? _tapApplier;
+
// Built-in presets (EQ curve shapes)
static const Map<String, List<double>> presets = {
'flat': [0, 0, 0, 0, 0],
@@ -62,6 +66,12 @@ class EqualizerService extends ChangeNotifier {
bool get perItem => _perItem;
String? get currentItemId => _currentItemId;
+ /// True when any audio processing (band EQ, bass, loudness, or mono) is
+ /// active. iOS uses this to decide whether the processing tap must be live;
+ /// effects work even with the band-EQ master switch off.
+ bool get anyProcessingActive =>
+ _enabled || _bassBoost > 0 || _loudnessGain > 0 || _mono;
+
/// Initialize — try to connect to platform EQ, fall back to software presets.
Future<void> init() async {
await _loadSettings();
@@ -91,6 +101,7 @@ class EqualizerService extends ChangeNotifier {
_setupSoftwareFallback();
}
_skipSilenceApplier?.call(_skipSilence);
+ _tapApplier?.call(anyProcessingActive);
notifyListeners();
}
@@ -112,6 +123,7 @@ class EqualizerService extends ChangeNotifier {
} else {
_resetPlatform();
}
+ _tapApplier?.call(anyProcessingActive);
await _saveSettings();
notifyListeners();
}
@@ -148,11 +160,11 @@ class EqualizerService extends ChangeNotifier {
/// Set bass boost (0.0–1.0).
Future<void> setBassBoost(double value) async {
_bassBoost = value.clamp(0.0, 1.0);
- if (_enabled) {
- try {
- await _channel.invokeMethod('setBassBoost', {'strength': (_bassBoost * 1000).round()});
- } catch (_) {}
- }
+ // Effects apply independently of the band-EQ master switch on both platforms.
+ try {
+ await _channel.invokeMethod('setBassBoost', {'strength': (_bassBoost * 1000).round()});
+ } catch (_) {}
+ _tapApplier?.call(anyProcessingActive);
await _saveSettings();
notifyListeners();
}
@@ -175,6 +187,7 @@ class EqualizerService extends ChangeNotifier {
try {
await _channel.invokeMethod('setMono', {'enabled': _mono});
} catch (_) {}
+ _tapApplier?.call(anyProcessingActive);
await _saveSettings();
notifyListeners();
}
@@ -196,14 +209,20 @@ class EqualizerService extends ChangeNotifier {
fn(_skipSilence);
}
+ /// Register the iOS processing-tap applier. Called once immediately so the
+ /// engine reflects the current state.
+ void setTapApplier(void Function(bool active) fn) {
+ _tapApplier = fn;
+ fn(anyProcessingActive);
+ }
+
/// Set loudness enhancer gain (0.0–1.0).
Future<void> setLoudnessGain(double value) async {
_loudnessGain = value.clamp(0.0, 1.0);
- if (_enabled) {
- try {
- await _channel.invokeMethod('setLoudness', {'gain': (_loudnessGain * 1500).round()});
- } catch (_) {}
- }
+ try {
+ await _channel.invokeMethod('setLoudness', {'gain': (_loudnessGain * 1500).round()});
+ } catch (_) {}
+ _tapApplier?.call(anyProcessingActive);
await _saveSettings();
notifyListeners();
}
@@ -220,7 +239,10 @@ class EqualizerService extends ChangeNotifier {
_skipSilenceApplier?.call(_skipSilence);
if (_enabled) {
_applyCurrentSettings();
+ } else {
+ _resetPlatform();
}
+ _tapApplier?.call(anyProcessingActive);
await _saveSettings();
notifyListeners();
}
@@ -235,8 +257,9 @@ class EqualizerService extends ChangeNotifier {
if (_enabled) {
_applyCurrentSettings();
} else {
- // Ensure effects stay disabled even though the native side creates them disabled by default
- _channel.invokeMethod('setEnabled', {'enabled': false});
+ // Bands off, but still push bass/loudness/mono so independent effects
+ // apply on a freshly-attached session.
+ _resetPlatform();
}
} catch (e) {
debugPrint('[EQ] attachSession failed: $e');
@@ -269,8 +292,12 @@ class EqualizerService extends ChangeNotifier {
Future<void> _resetPlatform() async {
try {
+ // Master switch only gates the band EQ; effects stay applied so bass /
+ // loudness / mono keep working with the equalizer off.
await _channel.invokeMethod('setEnabled', {'enabled': false});
await _channel.invokeMethod('setMono', {'enabled': _mono});
+ await _channel.invokeMethod('setBassBoost', {'strength': (_bassBoost * 1000).round()});
+ await _channel.invokeMethod('setLoudness', {'gain': (_loudnessGain * 1500).round()});
} catch (_) {}
}
@@ -286,6 +313,7 @@ class EqualizerService extends ChangeNotifier {
Future<void> switchItem(String itemId) async {
if (!_perItem) {
_currentItemId = itemId;
+ _tapApplier?.call(anyProcessingActive);
return;
}
if (_currentItemId != null && _currentItemId != itemId) {
@@ -299,6 +327,7 @@ class EqualizerService extends ChangeNotifier {
} else {
_resetPlatform();
}
+ _tapApplier?.call(anyProcessingActive);
notifyListeners();
}
@@ -423,6 +452,7 @@ class EqualizerService extends ChangeNotifier {
} else {
await _resetPlatform();
}
+ _tapApplier?.call(anyProcessingActive);
notifyListeners();
}
diff --git a/lib/services/native_ios_audio_player.dart b/lib/services/native_ios_audio_player.dart
new file mode 100644
index 00000000..01d06981
--- /dev/null
+++ b/lib/services/native_ios_audio_player.dart
@@ -0,0 +1,344 @@
+import 'dart:async';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:just_audio/just_audio.dart' as ja;
+import 'scoped_prefs.dart';
+
+/// Native iOS audio engine wrapper. Mimics enough of just_audio's
+/// `AudioPlayer` surface that AudioPlayerHandler treats it as a drop-in.
+/// Talks to AbsorbAudioEngine via `com.absorb.audio_engine` method channel
+/// and `com.absorb.audio_engine.events` event channel.
+class NativeIosAudioPlayer {
+ static const _methodChannel = MethodChannel('com.absorb.audio_engine');
+ static const _eventChannel = EventChannel('com.absorb.audio_engine.events');
+
+ NativeIosAudioPlayer() {
+ _eventSub = _eventChannel.receiveBroadcastStream().listen(
+ _onEvent,
+ onError: (Object e) {
+ debugPrint('[NativeIosAudioPlayer] event stream error: $e');
+ },
+ );
+ }
+
+ StreamSubscription? _eventSub;
+
+ // Cached state mirrors the native engine.
+ Duration _position = Duration.zero;
+ Duration? _duration;
+ Duration _bufferedPosition = Duration.zero;
+ bool _playing = false;
+ ja.ProcessingState _processingState = ja.ProcessingState.idle;
+ double _speed = 1.0;
+ double _volume = 1.0;
+ int? _currentIndex;
+ DateTime _updateTime = DateTime.now();
+
+ // Stream controllers; broadcast so multiple listeners are allowed.
+ final _positionController = StreamController<Duration>.broadcast();
+ final _durationController = StreamController<Duration?>.broadcast();
+ final _bufferedPositionController = StreamController<Duration>.broadcast();
+ final _playerStateController = StreamController<ja.PlayerState>.broadcast();
+ final _processingStateController = StreamController<ja.ProcessingState>.broadcast();
+ final _playbackEventController = StreamController<ja.PlaybackEvent>.broadcast();
+ final _currentIndexController = StreamController<int?>.broadcast();
+
+ // Notified by AudioPlayerHandler-style consumers when the engine auto-advances
+ // mid-book to the pre-buffered next book.
+ final _bookAutoAdvancedController = StreamController<void>.broadcast();
+
+ Stream<Duration> get positionStream => _positionController.stream;
+ Stream<Duration?> get durationStream => _durationController.stream;
+ Stream<Duration> get bufferedPositionStream => _bufferedPositionController.stream;
+ Stream<ja.PlayerState> get playerStateStream => _playerStateController.stream;
+ Stream<ja.ProcessingState> get processingStateStream => _processingStateController.stream;
+ Stream<ja.PlaybackEvent> get playbackEventStream => _playbackEventController.stream;
+ Stream<int?> get currentIndexStream => _currentIndexController.stream;
+
+ /// Fired when the engine has swapped to a pre-buffered next book mid-flight.
+ /// AudioPlayerService listens to this instead of inferring from position
+ /// jumps + completion races.
+ Stream<void> get bookAutoAdvancedStream => _bookAutoAdvancedController.stream;
+
+ Duration get position => _position;
+ Duration? get duration => _duration;
+ Duration get bufferedPosition => _bufferedPosition;
+ bool get playing => _playing;
+ ja.ProcessingState get processingState => _processingState;
+ double get speed => _speed;
+ double get volume => _volume;
+ int? get currentIndex => _currentIndex;
+
+ /// Android-only; always null on iOS, matches just_audio's iOS behavior.
+ int? get androidAudioSessionId => null;
+
+ /// Current playback event snapshot. AudioPlayerHandler reads this in
+ /// `refreshPlaybackState`; mirror the just_audio shape.
+ ja.PlaybackEvent get playbackEvent => _buildPlaybackEvent();
+
+ // ─── Source loading ───
+
+ Future<Duration?> setAudioSource(ja.AudioSource source, {
+ Duration? initialPosition,
+ int? initialIndex,
+ bool preload = true,
+ }) async {
+ final tracks = _flattenSource(source);
+ if (tracks.isEmpty) return null;
+
+ final startS = (initialPosition?.inMilliseconds ?? 0) / 1000.0;
+ final eqEnabled = await ScopedPrefs.getBool('eq_enabled') ?? false;
+ final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>('load', {
+ 'tracks': tracks.map(_trackToMap).toList(),
+ 'trackOffsets': _buildTrackOffsets(tracks),
+ 'startPositionS': startS,
+ 'totalDurationS': _totalDurationHint,
+ 'speed': _speed,
+ 'volume': _volume,
+ 'eqEnabled': eqEnabled,
+ });
+ final durS = result?['durationS'] as double?;
+ if (durS != null) {
+ _duration = Duration(milliseconds: (durS * 1000).round());
+ _durationController.add(_duration);
+ }
+ return _duration;
+ }
+
+ /// 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 {
+ if (source == null) {
+ await _methodChannel.invokeMethod('clearNextSource');
+ return true;
+ }
+ final tracks = _flattenSource(source);
+ if (tracks.isEmpty) return false;
+ final result = await _methodChannel.invokeMethod<bool>('setNextSource', {
+ 'tracks': tracks.map(_trackToMap).toList(),
+ 'trackOffsets': _buildTrackOffsets(tracks),
+ 'startPositionS': startPositionS,
+ 'totalDurationS': totalDurationS,
+ });
+ return result ?? false;
+ }
+
+ // ─── Control ───
+
+ Future<void> play() async {
+ await _methodChannel.invokeMethod('play');
+ _playing = true;
+ _emitPlayerState();
+ }
+
+ Future<void> pause() async {
+ await _methodChannel.invokeMethod('pause');
+ _playing = false;
+ _emitPlayerState();
+ }
+
+ Future<void> stop() async {
+ await _methodChannel.invokeMethod('stop');
+ _playing = false;
+ _processingState = ja.ProcessingState.idle;
+ _emitPlayerState();
+ }
+
+ Future<void> seek(Duration? position, {int? index}) async {
+ final s = (position?.inMilliseconds ?? 0) / 1000.0;
+ // `index` is the track within a multi-file book. The engine seeks to the
+ // track-local position `s` inside that track; AudioPlayerService has
+ // already converted the absolute book position into (index, local offset).
+ await _methodChannel.invokeMethod<bool>('seek', {
+ 'positionS': s,
+ if (index != null) 'index': index,
+ });
+ _position = position ?? Duration.zero;
+ if (index != null) _currentIndex = index;
+ _updateTime = DateTime.now();
+ _positionController.add(_position);
+ _playbackEventController.add(_buildPlaybackEvent());
+ }
+
+ Future<void> setSpeed(double speed) async {
+ _speed = speed;
+ await _methodChannel.invokeMethod('setSpeed', {'speed': speed});
+ _playbackEventController.add(_buildPlaybackEvent());
+ }
+
+ Future<void> setVolume(double volume) async {
+ _volume = volume;
+ await _methodChannel.invokeMethod('setVolume', {'volume': volume});
+ }
+
+ /// No-op on iOS; just_audio's iOS plugin doesn't support skip-silence either.
+ Future<void> setSkipSilenceEnabled(bool enabled) async {}
+
+ /// Sleep timer chime uses ja.AudioPlayer.setAsset directly; this wrapper
+ /// should never be the chime player. Throw to surface misuse early.
+ Future<Duration?> setAsset(String asset) async {
+ throw UnsupportedError('NativeIosAudioPlayer.setAsset is not implemented; use ja.AudioPlayer for the chime.');
+ }
+
+ Future<void> attachEqualizerTap() async {
+ await _methodChannel.invokeMethod('attachEqualizerTap');
+ }
+
+ Future<void> detachEqualizerTap() async {
+ await _methodChannel.invokeMethod('detachEqualizerTap');
+ }
+
+ Future<void> dispose() async {
+ await _eventSub?.cancel();
+ _eventSub = null;
+ try {
+ await _methodChannel.invokeMethod('dispose');
+ } catch (_) {}
+ await _positionController.close();
+ await _durationController.close();
+ await _bufferedPositionController.close();
+ await _playerStateController.close();
+ await _processingStateController.close();
+ await _playbackEventController.close();
+ await _currentIndexController.close();
+ await _bookAutoAdvancedController.close();
+ }
+
+ // ─── Event channel handler ───
+
+ void _onEvent(dynamic raw) {
+ if (raw is! Map) return;
+ final type = raw['type'] as String?;
+ switch (type) {
+ case 'position':
+ final s = (raw['positionS'] as num?)?.toDouble() ?? 0;
+ _position = Duration(milliseconds: (s * 1000).round());
+ _updateTime = DateTime.now();
+ _positionController.add(_position);
+ _playbackEventController.add(_buildPlaybackEvent());
+ break;
+ case 'state':
+ _playing = (raw['playing'] as bool?) ?? false;
+ final psRaw = (raw['processingState'] as int?) ?? 0;
+ _processingState = _mapProcessingState(psRaw);
+ _processingStateController.add(_processingState);
+ _emitPlayerState();
+ _playbackEventController.add(_buildPlaybackEvent());
+ break;
+ case 'duration':
+ final s = (raw['durationS'] as num?)?.toDouble();
+ _duration = s != null && s > 0 ? Duration(milliseconds: (s * 1000).round()) : null;
+ _durationController.add(_duration);
+ _playbackEventController.add(_buildPlaybackEvent());
+ break;
+ case 'trackChanged':
+ final idx = (raw['trackIndex'] as int?);
+ _currentIndex = idx;
+ _currentIndexController.add(idx);
+ _playbackEventController.add(_buildPlaybackEvent());
+ break;
+ case 'bookCompleted':
+ _processingState = ja.ProcessingState.completed;
+ _processingStateController.add(_processingState);
+ _emitPlayerState();
+ _playbackEventController.add(_buildPlaybackEvent());
+ break;
+ case 'bookAutoAdvanced':
+ _bookAutoAdvancedController.add(null);
+ break;
+ case 'bufferedPosition':
+ final s = (raw['bufferedPositionS'] as num?)?.toDouble() ?? 0;
+ _bufferedPosition = Duration(milliseconds: (s * 1000).round());
+ _bufferedPositionController.add(_bufferedPosition);
+ _playbackEventController.add(_buildPlaybackEvent());
+ break;
+ case 'error':
+ final msg = raw['message'] as String? ?? 'engine error';
+ debugPrint('[NativeIosAudioPlayer] engine error: $msg');
+ break;
+ }
+ }
+
+ ja.ProcessingState _mapProcessingState(int raw) {
+ switch (raw) {
+ case 0: return ja.ProcessingState.idle;
+ case 1: return ja.ProcessingState.loading;
+ case 2: return ja.ProcessingState.buffering;
+ case 3: return ja.ProcessingState.ready;
+ case 4: return ja.ProcessingState.completed;
+ default: return ja.ProcessingState.idle;
+ }
+ }
+
+ void _emitPlayerState() {
+ _playerStateController.add(ja.PlayerState(_playing, _processingState));
+ }
+
+ ja.PlaybackEvent _buildPlaybackEvent() {
+ return ja.PlaybackEvent(
+ processingState: _processingState,
+ updateTime: _updateTime,
+ updatePosition: _position,
+ bufferedPosition: _bufferedPosition,
+ duration: _duration,
+ currentIndex: _currentIndex,
+ );
+ }
+
+ // ─── AudioSource translation ───
+
+ // Used as a hint to the native engine when load lacks an explicit duration.
+ // setAudioSource doesn't receive a duration directly, so we leave it at 0
+ // and let the engine read it from the asset after load.
+ double get _totalDurationHint => 0;
+
+ List<_NativeTrack> _flattenSource(ja.AudioSource source) {
+ final out = <_NativeTrack>[];
+ _collect(source, out);
+ return out;
+ }
+
+ void _collect(ja.AudioSource source, List<_NativeTrack> out) {
+ if (source is ja.ConcatenatingAudioSource) {
+ for (final child in source.children) {
+ _collect(child, out);
+ }
+ return;
+ }
+ if (source is ja.UriAudioSource) {
+ final uri = source.uri;
+ final headers = source.headers ?? const <String, String>{};
+ final isLocal = uri.scheme == 'file' || uri.scheme.isEmpty;
+ out.add(_NativeTrack(
+ url: isLocal ? uri.toFilePath() : uri.toString(),
+ isLocal: isLocal,
+ headers: headers,
+ ));
+ return;
+ }
+ debugPrint('[NativeIosAudioPlayer] Unsupported AudioSource: ${source.runtimeType}');
+ }
+
+ Map<String, dynamic> _trackToMap(_NativeTrack t) => {
+ 'url': t.url,
+ 'isLocal': t.isLocal,
+ 'headers': t.headers,
+ };
+
+ /// Without per-track durations available here, hand the engine an empty
+ /// offsets list and let it fall back to single-track behavior. The
+ /// AudioPlayerService already maintains its own `_trackStartOffsets` from
+ /// the cached audioTracks and applies the global-position math on the Dart
+ /// side, so the engine's offsets are only used internally for seek routing.
+ List<double> _buildTrackOffsets(List<_NativeTrack> tracks) {
+ if (tracks.length <= 1) return const [];
+ return const [];
+ }
+}
+
+class _NativeTrack {
+ _NativeTrack({required this.url, required this.isLocal, required this.headers});
+ final String url;
+ final bool isLocal;
+ final Map<String, String> headers;
+}
diff --git a/lib/widgets/equalizer_sheet.dart b/lib/widgets/equalizer_sheet.dart
index b0a0934e..b02a2edc 100644
--- a/lib/widgets/equalizer_sheet.dart
+++ b/lib/widgets/equalizer_sheet.dart
@@ -413,8 +413,14 @@ class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
);
}).toList(),
),
- if (_vPreset == 'custom')
- Padding(
+ // Reserve the chip's space always, so it appearing when a band
+ // is first touched doesn't shift the sliders down under the finger.
+ Visibility(
+ visible: _vPreset == 'custom',
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: Padding(
padding: const EdgeInsets.only(top: 8),
child: GestureDetector(
onTap: _vEnabled ? () => _applyPreset('flat') : null,
@@ -430,6 +436,7 @@ class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
),
),
),
+ ),
const SizedBox(height: 20),
// ── EQ Bands ──
@@ -468,7 +475,7 @@ class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
label: l.bassBoost,
value: _vBass,
accent: accent,
- enabled: _vEnabled,
+ enabled: true,
onChanged: (v) => _setBass(v),
),
const SizedBox(height: 8),
@@ -480,7 +487,7 @@ class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
label: l.surround,
value: _vVirt,
accent: accent,
- enabled: _vEnabled,
+ enabled: true,
onChanged: (v) => _setVirt(v),
),
const SizedBox(height: 8),
@@ -492,7 +499,7 @@ class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
label: l.loudness,
value: _vLoud,
accent: accent,
- enabled: _vEnabled,
+ enabled: true,
onChanged: (v) => _setLoud(v),
),
const SizedBox(height: 8),
@@ -564,12 +571,10 @@ class _EqualizerSheetContentState extends State<_EqualizerSheetContent> {
// Reset button
Center(
child: TextButton.icon(
- onPressed: _vEnabled ? () => _resetAll() : null,
- icon: Icon(Icons.refresh_rounded, size: 18,
- color: _vEnabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.12)),
+ onPressed: () => _resetAll(),
+ icon: Icon(Icons.refresh_rounded, size: 18, color: cs.onSurfaceVariant),
label: Text(l.resetAll, style: TextStyle(
- color: _vEnabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.12),
- fontSize: 13)),
+ color: cs.onSurfaceVariant, fontSize: 13)),
),
),
const SizedBox(height: 24),
diff --git a/pubspec.yaml b/pubspec.yaml
index 8b611e96..a2d95651 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.91+150
+version: 1.8.91+156
environment:
sdk: '>=3.1.0 <4.0.0'