Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add AA cold-start book-finished buffer and alpha diagnostics for #172/#179/#186

Barnabas33434c8efadb
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 81f09295..3953e0f9 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -174,7 +174,8 @@ class MainActivity : AudioServiceActivity() {
Log.w(TAG, "LoudnessEnhancer not supported: ${e.message}"); null
}
- Log.d(TAG, "Effects attached to session $sessionId")
+ // Alpha: capture LoudnessEnhancer/eq state on attach for GH #179 (volume falls off).
+ Log.d(TAG, "Effects attached to session $sessionId: eqEnabled=$eqEnabled loudnessGainMb=$eqLoudnessGainMb loudnessEffectOk=${loudnessEnhancer != null}")
result.success(true)
} catch (e: Exception) {
Log.e(TAG, "attachSession failed: ${e.message}")
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dart
index 6f0be154..d4e8df1c 100644
--- a/lib/providers/_lp_absorbing.dart
+++ b/lib/providers/_lp_absorbing.dart
@@ -779,13 +779,27 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
void _autoAdvanceOfflineBook(String finishedBookId) {
PlayerSettings.getBookQueueMode().then((mode) {
- if (mode != 'auto_next') return;
- if (AudioPlayerService.wasNoisyPause) return;
+ // Alpha: bail-reason logs for GH #186 (book restart). Each silent return
+ // here was a suspect in the advance-didn't-fire hypothesis.
+ if (mode != 'auto_next') {
+ debugPrint('[AutoAdvance] Offline book bail: mode=$mode (not auto_next) finished=$finishedBookId');
+ return;
+ }
+ if (AudioPlayerService.wasNoisyPause) {
+ debugPrint('[AutoAdvance] Offline book bail: wasNoisyPause=true finished=$finishedBookId');
+ return;
+ }
final finished = _itemDataWithSeries(finishedBookId);
- if (finished == null) return;
+ if (finished == null) {
+ debugPrint('[AutoAdvance] Offline book bail: no series data for finished=$finishedBookId');
+ return;
+ }
final (seriesId, currentSeq) = _StateMixin._extractSeries(finished);
- if (seriesId == null || currentSeq == null) return;
+ if (seriesId == null || currentSeq == null) {
+ debugPrint('[AutoAdvance] Offline book bail: seriesId=$seriesId currentSeq=$currentSeq finished=$finishedBookId');
+ return;
+ }
final dl = DownloadService();
final candidates = <double, MapEntry<String, Map<String, dynamic>>>{};
@@ -801,7 +815,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
if (sid != seriesId || seq == null || seq <= currentSeq) continue;
candidates[seq] = MapEntry(id, data);
}
- if (candidates.isEmpty) return;
+ if (candidates.isEmpty) {
+ debugPrint('[AutoAdvance] Offline book bail: no downloaded next book in series=$seriesId after seq=$currentSeq');
+ return;
+ }
final nextSeq = candidates.keys.toList()..sort();
final next = candidates[nextSeq.first]!;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 1dabae3d..3c678823 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -24,6 +24,38 @@ part '_lp_absorbing.dart';
class LibraryProvider extends ChangeNotifier
with _StateMixin, _CoreMixin, _AbsorbingMixin {
+ LibraryProvider() {
+ // Registered once at provider construction so the audio service can
+ // notify this provider on completion/playback events even when the
+ // Flutter UI wasn't foregrounded yet (e.g. Android Auto cold-start,
+ // where updateAuth may not run until much later).
+ AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
+ AudioPlayerService.setOnPlayStartedCallback((key) {
+ Future.delayed(const Duration(seconds: 30), () {
+ final stillPlaying = AudioPlayerService().isPlaying;
+ if (!stillPlaying) return;
+ _checkRollingDownloads(key);
+ _checkQueueAutoDownloads(key);
+ _checkAutoDownloadOnStream(key);
+ });
+ });
+ AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {
+ if (playing) {
+ onPlaybackStarted();
+ } else {
+ onPlaybackStopped();
+ }
+ });
+ ChromecastService.setOnBookFinishedCallback(markFinishedLocally);
+ ChromecastService.setOnPlaybackStateChangedCallback((playing) {
+ if (playing) {
+ onPlaybackStarted();
+ } else {
+ onPlaybackStopped();
+ }
+ });
+ }
+
void updateAuth(AuthProvider auth) {
if (!_listeningToDownloads) {
_listeningToDownloads = true;
@@ -73,33 +105,6 @@ class LibraryProvider extends ChangeNotifier
notifyListeners();
}
- AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
- AudioPlayerService.setOnPlayStartedCallback((key) {
- // Defer download checks to avoid a network burst at playback start.
- Future.delayed(const Duration(seconds: 30), () {
- final stillPlaying = AudioPlayerService().isPlaying;
- if (!stillPlaying) return;
- _checkRollingDownloads(key);
- _checkQueueAutoDownloads(key);
- _checkAutoDownloadOnStream(key);
- });
- });
- AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {
- if (playing) {
- onPlaybackStarted();
- } else {
- onPlaybackStopped();
- }
- });
- ChromecastService.setOnBookFinishedCallback(markFinishedLocally);
- ChromecastService.setOnPlaybackStateChangedCallback((playing) {
- if (playing) {
- onPlaybackStarted();
- } else {
- onPlaybackStopped();
- }
- });
-
restoreOfflineMode().then((_) async {
debugPrint(
'[Library] restoreOfflineMode done, serverReachable=${auth.serverReachable} api=${_api != null} offline=$isOffline');
@@ -110,6 +115,10 @@ class LibraryProvider extends ChangeNotifier
await _loadKnownEpisodeIds();
Future.microtask(() => checkSubscribedPodcasts());
+ // Replay any book-finished event that fired before the absorbing
+ // cache was loaded (Android Auto cold-start case).
+ AudioPlayerService.drainPendingBookFinished();
+
_buildProgressMap(auth);
if (!auth.serverReachable) {
@@ -150,10 +159,6 @@ class LibraryProvider extends ChangeNotifier
});
} else {
_lastAuthKey = null;
- AudioPlayerService.setOnBookFinishedCallback(null);
- AudioPlayerService.setOnPlayStartedCallback(null);
- AudioPlayerService.setOnPlaybackStateChangedCallback(null);
- ChromecastService.setOnBookFinishedCallback(null);
_idleDisconnectTimer?.cancel();
_idleDisconnectTimer = null;
_libraries = [];
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 9fe6acaa..63f66dbf 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -696,10 +696,24 @@ class AudioPlayerService extends ChangeNotifier {
/// Register via [setOnBookFinishedCallback]. Used by LibraryProvider to
/// update local finished state immediately without waiting for a server refresh.
static void Function(String itemId)? _onBookFinishedCallback;
+ // Buffers the most recent completion key when the callback fires before
+ // LibraryProvider is ready to handle it (e.g. Android Auto cold-start).
+ // LibraryProvider calls [drainPendingBookFinished] once its absorbing cache
+ // is loaded so auto-advance has the state it needs.
+ static String? _pendingBookFinishedKey;
static void setOnBookFinishedCallback(void Function(String itemId)? cb) {
_onBookFinishedCallback = cb;
}
+ static void drainPendingBookFinished() {
+ final cb = _onBookFinishedCallback;
+ final pending = _pendingBookFinishedKey;
+ if (cb == null || pending == null) return;
+ _pendingBookFinishedKey = null;
+ debugPrint('[Player] Draining buffered book-finished key=$pending');
+ cb(pending);
+ }
+
/// Called when a new item starts playing. Used by LibraryProvider to trigger
/// rolling downloads for the next items in a series/podcast.
static void Function(String key)? _onPlayStartedCallback;
@@ -2250,6 +2264,11 @@ class AudioPlayerService extends ChangeNotifier {
final displayDuration = speed > 0 && speed != 1.0
? rawDuration / speed
: rawDuration;
+ // Alpha: confirms MediaItem metadata flowing to MediaSession for GH #172
+ // (BT car display stuck on prior chapter). If this fires with fresh
+ // artist/chapter text but the car still shows old, the issue is downstream
+ // of audio_service's MediaSession push.
+ debugPrint('[Handler] mediaItem.add: item=$itemId artist="$displayArtist" dur=${displayDuration.round()}s chapter=$chapter hasHandler=${_handler != null}');
_handler!.mediaItem.add(MediaItem(
id: itemId,
title: title,
@@ -2701,6 +2720,11 @@ class AudioPlayerService extends ChangeNotifier {
bool _isCompletingBook = false;
Future<void> _onPlaybackComplete() async {
+ // Alpha: captures completion path choice for GH #186 (book restart bug).
+ // Re-entry attempts are logged too so we can see if completion fires
+ // multiple times from different signals (processingState, position-jump,
+ // fallback) and races with auto-advance.
+ debugPrint('[Complete] entry: pos=${_lastKnownPositionSec.toStringAsFixed(1)}s totalDur=${_totalDuration.toStringAsFixed(1)}s item=$_currentItemId ep=$_currentEpisodeId reentry=$_isCompletingBook');
if (_isCompletingBook) return; // prevent re-entry
_isCompletingBook = true;
@@ -2793,7 +2817,12 @@ class AudioPlayerService extends ChangeNotifier {
// Notify LibraryProvider before clearing state so it can update isFinished locally.
if (itemId != null) {
final key = episodeId != null ? '$itemId-$episodeId' : itemId;
- _onBookFinishedCallback?.call(key);
+ if (_onBookFinishedCallback != null) {
+ _onBookFinishedCallback!(key);
+ } else {
+ _pendingBookFinishedKey = key;
+ debugPrint('[Player] Book-finished callback not registered, buffering key=$key');
+ }
}
// Clear state (player already stopped at top of method)
@@ -2831,7 +2860,11 @@ class AudioPlayerService extends ChangeNotifier {
final now = DateTime.now();
final elapsed = now.difference(_lastServerSync).inSeconds.clamp(0, 300);
_lastServerSync = now;
- debugPrint('[Player] Sync session ${_playbackSessionId!.substring(0, 8)}... | currentTime=${ct.toStringAsFixed(1)}s, timeListened=${elapsed}s');
+ // Alpha: volume/sessionId piggybacked for GH #179 (volume falls off).
+ // We sample these on each sync tick so drift over time is visible.
+ final vol = _player?.volume;
+ final eqSid = _player?.androidAudioSessionId;
+ debugPrint('[Player] Sync session ${_playbackSessionId!.substring(0, 8)}... | currentTime=${ct.toStringAsFixed(1)}s, timeListened=${elapsed}s, volume=$vol, eqSession=$eqSid');
final ok = await _api!.syncPlaybackSession(
_playbackSessionId!,
currentTime: ct,
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index d98f8cbc..c72881d6 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -46,6 +46,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
bool _speedAdjustedTime = true;
double _savedSpeed = 1.0; // per-book or default speed for inactive display
final ValueNotifier<bool> _edgeBarExpanded = ValueNotifier(false);
+ String? _lastRenderLogSig;
@override
bool get wantKeepAlive => true;
@@ -422,6 +423,18 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
bookProgress = progress;
}
+ // Alpha diagnostic: fires only when a state-shape transition happens
+ // (not on every position tick), to confirm why a card's progress bar
+ // would render empty after an AA cold-start.
+ final durBucket = widget.player.totalDuration > 0 ? 'pos' : 'zero';
+ final progBucket = progress <= 0.001 ? '0' : (progress >= 0.999 ? '1' : 'mid');
+ final bookBucket = bookProgress <= 0.001 ? '0' : (bookProgress >= 0.999 ? '1' : 'mid');
+ final sig = 'item=$_itemId ep=$_episodeId active=$_isActive hasBook=${widget.player.hasBook} dur=$durBucket prog=$progBucket bar=$bookBucket playerItem=${widget.player.currentItemId} playerEp=${widget.player.currentEpisodeId}';
+ if (sig != _lastRenderLogSig) {
+ _lastRenderLogSig = sig;
+ debugPrint('[Card] $sig');
+ }
+
// Invalidate blurred background when cover URL changes (e.g. after server update)
if (_blurredCover != null && _blurredCoverUrl != _coverUrl) {
_blurredCover?.dispose();