Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Extra logging plus fix queue picking wrong type

Barnabas4072a7f6b238
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index 75043937..9d520a2a 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -80,9 +80,95 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
AbsorbPlayerCore.logSink?("[NativeCore] Registered as AppIntent dependency")
}
+ registerAudioSessionObservers()
+
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
+ private func registerAudioSessionObservers() {
+ let nc = NotificationCenter.default
+ nc.addObserver(
+ forName: AVAudioSession.routeChangeNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] note in
+ let reasonRaw = note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt ?? 0
+ let reason = AVAudioSession.RouteChangeReason(rawValue: reasonRaw)
+ let reasonName: String
+ switch reason {
+ case .unknown: reasonName = "unknown"
+ case .newDeviceAvailable: reasonName = "newDeviceAvailable"
+ case .oldDeviceUnavailable: reasonName = "oldDeviceUnavailable"
+ case .categoryChange: reasonName = "categoryChange"
+ case .override: reasonName = "override"
+ case .wakeFromSleep: reasonName = "wakeFromSleep"
+ case .noSuitableRouteForCategory: reasonName = "noSuitableRouteForCategory"
+ case .routeConfigurationChange: reasonName = "routeConfigurationChange"
+ default: reasonName = "raw=\(reasonRaw)"
+ }
+ let outputs = AVAudioSession.sharedInstance().currentRoute.outputs
+ .map { "\($0.portType.rawValue):\($0.portName)" }
+ .joined(separator: ",")
+ self?.logToFlutter("[AudioSession] routeChange reason=\(reasonName) outputs=[\(outputs)]")
+ }
+
+ nc.addObserver(
+ forName: AVAudioSession.interruptionNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] note in
+ let typeRaw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt ?? 99
+ let type = AVAudioSession.InterruptionType(rawValue: typeRaw)
+ let typeName: String
+ switch type {
+ case .began: typeName = "began"
+ case .ended: typeName = "ended"
+ default: typeName = "raw=\(typeRaw)"
+ }
+ var details: [String] = ["type=\(typeName)"]
+ if let optionsRaw = note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt {
+ let opts = AVAudioSession.InterruptionOptions(rawValue: optionsRaw)
+ details.append("shouldResume=\(opts.contains(.shouldResume))")
+ }
+ if #available(iOS 14.5, *) {
+ if let reasonRaw = note.userInfo?[AVAudioSessionInterruptionReasonKey] as? UInt {
+ details.append("reasonRaw=\(reasonRaw)")
+ }
+ }
+ self?.logToFlutter("[AudioSession] interruption \(details.joined(separator: " "))")
+ }
+
+ nc.addObserver(
+ forName: AVAudioSession.mediaServicesWereResetNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ self?.logToFlutter("[AudioSession] mediaServicesWereReset")
+ }
+
+ nc.addObserver(
+ forName: AVAudioSession.silenceSecondaryAudioHintNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] note in
+ let typeRaw = note.userInfo?[AVAudioSessionSilenceSecondaryAudioHintTypeKey] as? UInt ?? 99
+ self?.logToFlutter("[AudioSession] silenceSecondaryAudioHint type=\(typeRaw)")
+ }
+
+ // The patched just_audio fork posts JustAudioDiag notifications with
+ // AVPlayer state snapshots (timeControlStatus, rate, reasonForWaitingToPlay,
+ // error) right after each play() call. Forward them to the in-app log.
+ nc.addObserver(
+ forName: Notification.Name("JustAudioDiag"),
+ object: nil,
+ queue: .main
+ ) { [weak self] note in
+ if let msg = note.userInfo?["message"] as? String {
+ self?.logToFlutter(msg)
+ }
+ }
+ }
+
/// Forwards a log line to the Dart LogService via the widget channel so it
/// appears in the in-app log viewer (NSLog alone only shows in Xcode /
/// Console.app on a Mac).
@@ -239,6 +325,10 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
"type": port.portType.rawValue,
]
}
+ let npInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo
+ let npTitle = npInfo?[MPMediaItemPropertyTitle] as? String
+ let npRate = npInfo?[MPNowPlayingInfoPropertyPlaybackRate] as? Double
+ let npElapsed = npInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] as? Double
let info: [String: Any] = [
"category": session.category.rawValue,
"mode": session.mode.rawValue,
@@ -251,6 +341,10 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
"inputs": inputs,
"sampleRate": session.sampleRate,
"ioBufferDuration": session.ioBufferDuration,
+ "nowPlayingHasInfo": npInfo != nil,
+ "nowPlayingTitle": npTitle ?? "",
+ "nowPlayingRate": npRate ?? -1,
+ "nowPlayingElapsed": npElapsed ?? -1,
]
result(info)
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dart
index 12e4315f..d8ebecc0 100644
--- a/lib/providers/_lp_absorbing.dart
+++ b/lib/providers/_lp_absorbing.dart
@@ -603,32 +603,56 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
}
final merged = await PlayerSettings.getMergeAbsorbingLibraries();
+ final bookMode = await PlayerSettings.getBookQueueMode();
+ final podMode = await PlayerSettings.getPodcastQueueMode();
final finishedCached = _absorbingItemCache[finishedKey];
final finishedLibId = finishedCached?['libraryId'] as String?;
- // GH #241: queue mode is per-media-type (podcastQueueMode vs bookQueueMode),
- // so a podcast finishing must only advance to another podcast — never a book
- // (whose own queue mode might be "off").
final finishedIsPodcast = finishedKey.length > 36;
final finishedIdx = _absorbingBookIds.indexOf(finishedKey);
final startIdx = finishedIdx >= 0 ? finishedIdx + 1 : 0;
+ debugPrint('[Queue] _manualQueueAdvance: finished=$finishedKey '
+ '(${finishedIsPodcast ? "podcast" : "book"}, lib=$finishedLibId) '
+ 'merged=$merged bookMode=$bookMode podMode=$podMode '
+ 'queueLen=${_absorbingBookIds.length} startIdx=$startIdx');
+
for (int i = startIdx; i < _absorbingBookIds.length; i++) {
final key = _absorbingBookIds[i];
- if ((this as LibraryProvider).isItemFinishedByKey(key)) continue;
+ if ((this as LibraryProvider).isItemFinishedByKey(key)) {
+ debugPrint('[Queue] [$i] $key SKIP - already finished');
+ continue;
+ }
final candidateIsPodcast = key.length > 36;
- if (candidateIsPodcast != finishedIsPodcast) continue;
+ final candidateMode = candidateIsPodcast ? podMode : bookMode;
+ if (candidateMode == 'off') {
+ debugPrint('[Queue] [$i] $key SKIP - ${candidateIsPodcast ? "podcast" : "book"} mode is off');
+ continue;
+ }
+
+ if (!merged && candidateIsPodcast != finishedIsPodcast) {
+ debugPrint('[Queue] [$i] $key SKIP - cross-type (unified off, finished=${finishedIsPodcast ? "podcast" : "book"} candidate=${candidateIsPodcast ? "podcast" : "book"})');
+ continue;
+ }
final cached = _absorbingItemCache[key];
- if (cached == null) continue;
+ if (cached == null) {
+ debugPrint('[Queue] [$i] $key SKIP - no cache entry');
+ continue;
+ }
if (!merged && finishedLibId != null) {
final candidateLibId = cached['libraryId'] as String?;
- if (candidateLibId != null && candidateLibId != finishedLibId) continue;
+ if (candidateLibId != null && candidateLibId != finishedLibId) {
+ debugPrint('[Queue] [$i] $key SKIP - cross-library (finished=$finishedLibId candidate=$candidateLibId)');
+ continue;
+ }
}
+ debugPrint('[Queue] [$i] $key PICK - ${candidateIsPodcast ? "podcast" : "book"} (lib=${cached['libraryId']})');
+
final media = cached['media'] as Map<String, dynamic>? ?? {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
final title = metadata['title'] as String? ?? '';
@@ -1183,17 +1207,49 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
}
if (mode == 'manual') {
+ final bookMode = await PlayerSettings.getBookQueueMode();
+ final podMode = await PlayerSettings.getPodcastQueueMode();
+ final merged = await PlayerSettings.getMergeAbsorbingLibraries();
+ final currentLibId =
+ _absorbingItemCache[currentItemId]?['libraryId'] as String?;
final idx = _absorbingBookIds.indexOf(currentItemId);
final start = idx >= 0 ? idx + 1 : 0;
+ debugPrint('[Queue] peekUpNext: current=$currentItemId '
+ '(${isPodCurrent ? "podcast" : "book"}, lib=$currentLibId) '
+ 'merged=$merged bookMode=$bookMode podMode=$podMode '
+ 'queueLen=${_absorbingBookIds.length} startIdx=$start');
for (var i = start; i < _absorbingBookIds.length; i++) {
final key = _absorbingBookIds[i];
- if (self.isItemFinishedByKey(key)) continue;
- // Match _manualQueueAdvance: only same-type items are eligible.
- if ((key.length > 36) != isPodCurrent) continue;
+ if (self.isItemFinishedByKey(key)) {
+ debugPrint('[Queue] peek [$i] $key SKIP - already finished');
+ continue;
+ }
+ final candidateIsPodcast = key.length > 36;
+ final candidateMode = candidateIsPodcast ? podMode : bookMode;
+ if (candidateMode == 'off') {
+ debugPrint('[Queue] peek [$i] $key SKIP - ${candidateIsPodcast ? "podcast" : "book"} mode is off');
+ continue;
+ }
+ if (!merged && candidateIsPodcast != isPodCurrent) {
+ debugPrint('[Queue] peek [$i] $key SKIP - cross-type (unified off)');
+ continue;
+ }
final cached = _absorbingItemCache[key];
- if (cached == null) continue;
+ if (cached == null) {
+ debugPrint('[Queue] peek [$i] $key SKIP - no cache entry');
+ continue;
+ }
+ if (!merged && currentLibId != null) {
+ final candidateLibId = cached['libraryId'] as String?;
+ if (candidateLibId != null && candidateLibId != currentLibId) {
+ debugPrint('[Queue] peek [$i] $key SKIP - cross-library (current=$currentLibId candidate=$candidateLibId)');
+ continue;
+ }
+ }
+ debugPrint('[Queue] peek [$i] $key PICK - ${candidateIsPodcast ? "podcast" : "book"} (lib=${cached['libraryId']})');
return _entryTitle(cached);
}
+ debugPrint('[Queue] peek: no eligible item found');
return null;
}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 457a232f..193634b2 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1094,6 +1094,10 @@ class AudioPlayerService extends ChangeNotifier {
'ios.silenceHint=${info["secondaryAudioShouldBeSilencedHint"]}',
'ios.route=[$outputs]',
'ios.sampleRate=${info["sampleRate"]}',
+ 'ios.npHasInfo=${info["nowPlayingHasInfo"]}',
+ 'ios.npTitle="${info["nowPlayingTitle"]}"',
+ 'ios.npRate=${info["nowPlayingRate"]}',
+ 'ios.npElapsed=${info["nowPlayingElapsed"]}',
]);
}
} catch (e) {
diff --git a/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m b/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m
index f359ea67..13d61a27 100644
--- a/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m
+++ b/packages/just_audio/darwin/just_audio/Sources/just_audio/AudioPlayer.m
@@ -1033,6 +1033,33 @@
_playing = YES;
_player.rate = _speed;
[self updatePosition];
+ if (@available(macOS 10.12, iOS 10.0, *)) {
+ NSString *tcsName;
+ switch (_player.timeControlStatus) {
+ case AVPlayerTimeControlStatusPaused: tcsName = @"paused"; break;
+ case AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate: tcsName = @"waiting"; break;
+ case AVPlayerTimeControlStatusPlaying: tcsName = @"playing"; break;
+ default: tcsName = @"unknown"; break;
+ }
+ NSString *reasonName = @"none";
+ AVPlayerWaitingReason reason = _player.reasonForWaitingToPlay;
+ if (reason == AVPlayerWaitingToMinimizeStallsReason) reasonName = @"minimizeStalls";
+ else if (reason == AVPlayerWaitingWhileEvaluatingBufferingRateReason) reasonName = @"evaluatingBuffer";
+ else if (reason == AVPlayerWaitingWithNoItemToPlayReason) reasonName = @"noItem";
+ else if (reason != nil) reasonName = (NSString *)reason;
+ NSString *errDesc = _player.error ? _player.error.localizedDescription : @"none";
+ NSString *itemErrDesc = _player.currentItem.error ? _player.currentItem.error.localizedDescription : @"none";
+ NSString *itemStatus;
+ switch (_player.currentItem.status) {
+ case AVPlayerItemStatusReadyToPlay: itemStatus = @"readyToPlay"; break;
+ case AVPlayerItemStatusFailed: itemStatus = @"failed"; break;
+ case AVPlayerItemStatusUnknown: itemStatus = @"unknown"; break;
+ default: itemStatus = @"other"; break;
+ }
+ NSString *line = [NSString stringWithFormat:@"[JustAudio] play() post-rate: tcs=%@ rate=%.2f waitReason=%@ itemStatus=%@ err=%@ itemErr=%@", tcsName, _player.rate, reasonName, itemStatus, errDesc, itemErrDesc];
+ NSLog(@"%@", line);
+ [[NSNotificationCenter defaultCenter] postNotificationName:@"JustAudioDiag" object:nil userInfo:@{@"message": line}];
+ }
if (@available(macOS 10.12, iOS 10.0, *)) {}
else {
if (_bufferUnconfirmed && !_player.currentItem.playbackBufferFull) {