Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Load the last played book paused at launch so a headset press always has a target

Barnabasdf4dc6e3a270
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index d649697d..6eee5a0c 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1333,6 +1333,17 @@ class AudioPlayerService extends ChangeNotifier {
/// instead of a live `/play` session. Position still syncs via /me/progress.
bool _localSessionMode = false;
+ // Set when a loadOnly playItem skipped starting the local session; the
+ // first real play() begins it, so listening time still gets recorded.
+ ({
+ String progressKey,
+ String itemId,
+ String? episodeId,
+ double duration,
+ String title,
+ String author,
+ })? _pendingLoadOnlySession;
+
/// Externally-pushed signal that the server is currently unreachable.
/// AuthProvider mirrors `serverReachable` here on each ping result so we
/// can short-circuit pre-play server calls (e.g. session creation) for
@@ -2196,16 +2207,24 @@ class AudioPlayerService extends ChangeNotifier {
if (player == null) return;
try {
final state = await player.engineState();
- if (state == null || !state.isLoaded || !state.isPlaying) return;
- debugPrint(
- '[Player] boot: native engine already playing at '
- '${state.globalPositionS.toStringAsFixed(1)}s with no book loaded - adopting',
- );
- if (state.globalPositionS > 0) {
- await HomeWidgetService().stashLivePosition(state.globalPositionS);
+ if (state != null && state.isLoaded && state.isPlaying) {
+ debugPrint(
+ '[Player] boot: native engine already playing at '
+ '${state.globalPositionS.toStringAsFixed(1)}s with no book loaded - adopting',
+ );
+ if (state.globalPositionS > 0) {
+ await HomeWidgetService().stashLivePosition(state.globalPositionS);
+ }
+ final restore = AudioPlayerService.onColdStartPlayRequested;
+ if (restore != null) await restore();
+ return;
}
- final restore = AudioPlayerService.onColdStartPlayRequested;
- if (restore != null) await restore();
+ // Idle engine: load the last played item paused instead, so a headset
+ // press in the first seconds of a cold start has a live target - the
+ // native core defers presses to Flutter the moment its heartbeat
+ // exists, and with nothing loaded that press used to land on neither
+ // layer.
+ await HomeWidgetService().loadLastPlayedPaused();
} catch (e) {
debugPrint('[Player] boot engine adopt failed: $e');
}
@@ -3116,6 +3135,11 @@ class AudioPlayerService extends ChangeNotifier {
// Auto, the widget, headphones or a cold-start restore begin at the
// phone's own position immediately. See play().
bool fromUi = false,
+ // Load the item into the player at its resume position but leave it
+ // paused, with no playback session: a headset press then always has a
+ // live target, without deciding for the user that audio starts now.
+ // Downloaded items only - a streamed item plays normally.
+ bool loadOnly = false,
}) async {
_pauseRequested = false;
_playFromUi = fromUi;
@@ -3179,6 +3203,7 @@ class AudioPlayerService extends ChangeNotifier {
// for downloaded items. Without this it leaks from a prior downloaded play
// into a following streaming play and misroutes the listening time.
_localSessionMode = false;
+ _pendingLoadOnlySession = null;
_currentEpisodeTitle = episodeTitle;
_currentTitle = title;
_currentAuthor = author;
@@ -3274,6 +3299,7 @@ class AudioPlayerService extends ChangeNotifier {
chapters,
startTime,
forceStartTime,
+ loadOnly,
);
} else {
// Check manual offline — don't stream from server
@@ -3610,6 +3636,7 @@ class AudioPlayerService extends ChangeNotifier {
List<dynamic> chapters,
double startTime, [
bool forceStartTime = false,
+ bool loadOnly = false,
]) async {
debugPrint('[Player] Playing from local files: $title');
// Alpha [PodDur]: trace podcast-episode duration loading. Symptom:
@@ -3850,6 +3877,25 @@ class AudioPlayerService extends ChangeNotifier {
chapter: initChapter,
);
await EqualizerService().switchItem(speedKey);
+ if (loadOnly) {
+ // Loaded and idle at the resume position: the lock screen shows the
+ // book paused and a headset press has a live target, but nothing
+ // plays and no session exists until the user presses play - the
+ // normal play() path creates the session then.
+ debugPrint('[Player] Loaded paused (no session) at '
+ '${startTime.toStringAsFixed(0)}s');
+ _pendingLoadOnlySession = (
+ progressKey: pKey,
+ itemId: _currentItemId!,
+ episodeId: _currentEpisodeId,
+ duration: totalDuration,
+ title: title,
+ author: author,
+ );
+ _handler?.refreshPlaybackState();
+ notifyListeners();
+ return null;
+ }
debugPrint('[Player] Starting local playback at ${speed}x');
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
@@ -6105,6 +6151,24 @@ class AudioPlayerService extends ChangeNotifier {
_noisyPause =
false; // User explicitly resumed — allow interrupt-resume again
_handler?._noisyPauseAt = null; // Clear noisy suppression window
+ // A loadOnly playItem left the item paused with no session; this first
+ // real play is where listening actually starts, so the session does too.
+ final pendingSession = _pendingLoadOnlySession;
+ if (pendingSession != null) {
+ _pendingLoadOnlySession = null;
+ if (_currentItemId == pendingSession.itemId) {
+ await LocalSessionService().beginSession(
+ progressKey: pendingSession.progressKey,
+ libraryItemId: pendingSession.itemId,
+ episodeId: pendingSession.episodeId,
+ mediaType: pendingSession.episodeId != null ? 'podcast' : 'book',
+ duration: pendingSession.duration,
+ startTime: position.inMilliseconds / 1000.0,
+ displayTitle: pendingSession.title,
+ displayAuthor: pendingSession.author,
+ );
+ }
+ }
// A seek while paused (user, or the socket adopting another device's
// position) is the position the user expects to hear next - don't let
// the server check below override it.
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 9d52245f..b7bdae06 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -428,41 +428,11 @@ class HomeWidgetService {
debugPrint('[HomeWidget] play_pause: cold resume, itemId=$itemId');
if (itemId == null) return;
- final serverUrl = prefs.getString('server_url');
- final token = prefs.getString('token');
- final refreshToken = prefs.getString('refresh_token');
- final username = prefs.getString('username');
+ final api = _apiFromPrefs(prefs);
debugPrint(
- '[HomeWidget] play_pause: server=${serverUrl != null}, token=${token != null}',
- );
- if (serverUrl == null || token == null) return;
-
- Map<String, String>? customHeaders;
- final headersJson = prefs.getString('custom_headers');
- if (headersJson != null) {
- try {
- customHeaders = Map<String, String>.from(
- jsonDecode(headersJson) as Map,
- );
- } catch (_) {}
- }
-
- final api = ApiService(
- baseUrl: serverUrl,
- token: token,
- refreshToken: refreshToken,
- isLegacyToken: refreshToken == null,
- customHeaders: customHeaders ?? const {},
- loadPersistedTokens: () =>
- UserAccountService().loadPersistedTokens(serverUrl, username),
- onTokensRefreshed: (access, refresh) =>
- UserAccountService().persistRefreshedTokens(
- access,
- refresh,
- serverUrl: serverUrl,
- username: username,
- ),
+ '[HomeWidget] play_pause: api=${api != null}',
);
+ if (api == null) return;
final episodeId = prefs.getString('widget_episode_id');
@@ -535,12 +505,80 @@ class HomeWidgetService {
/// Cold-resume a downloaded item straight from its download record. Returns
/// false when the item isn't downloaded (or the record is unusable) so the
/// caller falls back to fetching it from the server.
+ /// A saved session rebuilt from prefs, for paths that run before (or
+ /// without) the providers - the widget cold resume and the launch-time
+ /// load-paused. Null when no server credentials are saved.
+ ApiService? _apiFromPrefs(SharedPreferences prefs) {
+ final serverUrl = prefs.getString('server_url');
+ final token = prefs.getString('token');
+ if (serverUrl == null || token == null) return null;
+ final refreshToken = prefs.getString('refresh_token');
+ final username = prefs.getString('username');
+ Map<String, String>? customHeaders;
+ final headersJson = prefs.getString('custom_headers');
+ if (headersJson != null) {
+ try {
+ customHeaders = Map<String, String>.from(
+ jsonDecode(headersJson) as Map,
+ );
+ } catch (_) {}
+ }
+ return ApiService(
+ baseUrl: serverUrl,
+ token: token,
+ refreshToken: refreshToken,
+ isLegacyToken: refreshToken == null,
+ customHeaders: customHeaders ?? const {},
+ loadPersistedTokens: () =>
+ UserAccountService().loadPersistedTokens(serverUrl, username),
+ onTokensRefreshed: (access, refresh) =>
+ UserAccountService().persistRefreshedTokens(
+ access,
+ refresh,
+ serverUrl: serverUrl,
+ username: username,
+ ),
+ );
+ }
+
+ /// iOS cold start: load the last played item into the player paused, so a
+ /// headset press always has a live target. Without this, a press arriving
+ /// after Dart boots gets deferred by the native core to an audio_service
+ /// with nothing loaded, and lands on neither layer. Downloaded items only
+ /// (a stream would need a server session just to sit paused); no session
+ /// starts until a real play.
+ Future<void> loadLastPlayedPaused() async {
+ final player = AudioPlayerService();
+ if (player.hasBook) return;
+ final prefs = await SharedPreferences.getInstance();
+ final itemId = prefs.getString('widget_item_id');
+ if (itemId == null) return;
+ final api = _apiFromPrefs(prefs);
+ if (api == null) return;
+ final episodeId = prefs.getString('widget_episode_id');
+ try {
+ final ok = await _resumeFromDownloadRecord(
+ player,
+ api,
+ itemId,
+ episodeId,
+ loadOnly: true,
+ );
+ debugPrint(
+ '[HomeWidget] launch load-paused: ${ok ? "loaded $itemId" : "last played not downloaded - skipped"}',
+ );
+ } catch (e) {
+ debugPrint('[HomeWidget] launch load-paused failed: $e');
+ }
+ }
+
Future<bool> _resumeFromDownloadRecord(
AudioPlayerService player,
ApiService api,
String itemId,
- String? episodeId,
- ) async {
+ String? episodeId, {
+ bool loadOnly = false,
+ }) async {
final downloads = DownloadService();
final dlKey = episodeId != null ? '$itemId-$episodeId' : itemId;
if (!downloads.isDownloaded(dlKey)) return false;
@@ -573,6 +611,7 @@ class HomeWidgetService {
episodeId: episodeId,
episodeTitle: episodeId != null ? title : null,
libraryId: info.libraryId,
+ loadOnly: loadOnly,
);
return true;
}