A cross platform Audiobookshelf client for Android and iOS
Dart
Keep the lock screen on the right chapter after the app was asleep, keep the cover when playback starts, drop cached covers in the background on iOS, and stop the library loading page after page while you sit at the top
Barnabas85094fc319fc
diff --git a/ios/Runner/AbsorbPlayerCore.swift b/ios/Runner/AbsorbPlayerCore.swiftindex 16be483f..81151aac 100644--- a/ios/Runner/AbsorbPlayerCore.swift+++ b/ios/Runner/AbsorbPlayerCore.swift@@ -308,7 +308,18 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Senvolume: 1.0,eqEnabled: eqEnabled,itemId: itemId- ) { _ in }+ ) { [weak self] _ in+ // The stamp below goes out before the engine has the track, so it+ // carries no position and, when the stash has no length, no duration -+ // the lock screen showed no timestamps. Stamp again once the engine is+ // loaded, unless Flutter has come up and owns the tile by now.+ self?.queue.async {+ guard let self = self, self._currentItemId != nil, !self.flutterIsAlive() else { return }+ let rate = AbsorbAudioEngine.shared.isPlaying ? Double(self.currentSpeed()) : 0+ self.updateNowPlayingInfo(rate: rate)+ self.emit("[NativeCore] engine loaded - re-stamped Now Playing at \(self.globalPosition())s")+ }+ }configureRemoteCommandsIfNeeded()updateNowPlayingInfo(rate: 0)diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex 2f066dfa..adf6b6c7 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -619,14 +619,23 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadllet artist = args?["artist"] as? String ?? ""let duration = args?["duration"] as? Double ?? 0let elapsed = args?["elapsed"] as? Double ?? 0- var info: [String: Any] = [- MPMediaItemPropertyTitle: title,- MPMediaItemPropertyArtist: artist,- MPNowPlayingInfoPropertyPlaybackRate: 1.0,- MPNowPlayingInfoPropertyElapsedPlaybackTime: elapsed,- ]+ // Merge into what is on the tile for the same book rather than+ // replacing it: a full replace dropped the artwork audio_service had+ // set, and audio_service only rewrites when its own copy changes, so+ // the cover stayed missing on a locked phone until the next chapter.+ // The subtitle is "Author · Book", so a match means the same book and+ // its artwork is still right; anything else starts clean.+ let existing = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]+ let sameBook = (existing[MPMediaItemPropertyArtist] as? String) == artist+ var info: [String: Any] = sameBook ? existing : [:]+ info[MPMediaItemPropertyTitle] = title+ info[MPMediaItemPropertyArtist] = artist+ info[MPNowPlayingInfoPropertyPlaybackRate] = 1.0+ info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = elapsedif duration > 0 {info[MPMediaItemPropertyPlaybackDuration] = duration+ } else {+ info.removeValue(forKey: MPMediaItemPropertyPlaybackDuration)}MPNowPlayingInfoCenter.default().nowPlayingInfo = inforesult(true)diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex 288f7ee0..67c363da 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -1212,6 +1212,7 @@ class LibraryScreenState extends State<LibraryScreen>final limit =_loadedCount < 40 ? 20 : (_loadedCount < 80 ? 40 : _pageSize);final pageIndex = _loadedCount ~/ limit;+ debugPrint('[LibPage] request page=$pageIndex limit=$limit loaded=$_loadedCount');final sw = Stopwatch()..start();final result = await api.getLibraryItems(lib.selectedLibraryId!,diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 0ef2627b..98debfb4 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -2371,6 +2371,24 @@ class AudioPlayerService extends ChangeNotifier {Duration(milliseconds: (state.globalPositionS * 1000).round()),);}+ // The engine may have crossed chapters while Dart was suspended (a widget+ // or headset session driven by the native core). Chapter detection runs+ // off position ticks and a paused engine emits none, so the lock screen+ // kept the old chapter clamped at its end with no progress while the book+ // was chapters ahead. Work out the chapter for the adopted position and+ // republish.+ final adoptedItemId = _currentItemId;+ if (adoptedItemId != null) {+ final chapterTitle = _initChapterInfo(state.globalPositionS);+ _pushMediaItem(+ adoptedItemId,+ _currentTitle ?? '',+ _currentAuthor ?? '',+ _currentCoverUrl,+ _totalDuration,+ chapter: chapterTitle,+ );+ }_handler?.refreshPlaybackState();notifyListeners();}@@ -3066,6 +3084,22 @@ class AudioPlayerService extends ChangeNotifier {static void onAppBackgrounded() {_instance._isBackgrounded = true;debugPrint('[ClickDebug] App backgrounded');+ if (Platform.isIOS) _trimMemoryForBackground();+ }++ /// iOS: a paused app in the background has no audio keeping it alive, is+ /// suspended within seconds, and is a jetsam candidate whenever memory gets+ /// tight. When iOS evicts it, the audio session goes with it, and any app+ /// Absorb interrupted earlier is told to resume - it starts playing and owns+ /// Now Playing from then on. Nothing keeps a paused app alive for hours, so+ /// the lever is footprint: drop the decoded covers (up to 100MB) on the way+ /// out. They reload lazily on return, and the screen is off meanwhile.+ static void _trimMemoryForBackground() {+ final cache = PaintingBinding.instance.imageCache;+ final beforeMb = cache.currentSizeBytes ~/ 1048576;+ cache.clear();+ cache.clearLiveImages();+ debugPrint('[Memory] Backgrounded: dropped ${beforeMb}MB of decoded covers');}static Future<void> onAppForegrounded() async {diff --git a/lib/widgets/library_authors_tab.dart b/lib/widgets/library_authors_tab.dartindex a1fb2684..d40a6f0f 100644--- a/lib/widgets/library_authors_tab.dart+++ b/lib/widgets/library_authors_tab.dart@@ -82,6 +82,22 @@ class LibraryAuthorsTab extends StatelessWidget {],);} else {+ // Same next-page trigger as the books grid: driven by which tile index+ // the viewport builds, not by scroll metrics, which go stale after+ // items are appended beyond the fold (see LibraryBooksTab).+ final cols = responsiveGridCount(context);+ final loadAheadAt = authors.length - cols * 8;+ final route = ModalRoute.of(context);+ final loadMore = onLoadMore;+ void maybeLoadAhead(int index) {+ if (!hasMore || isLoadingAuthors || loadMore == null) return;+ if (index < loadAheadAt) return;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (route != null && !route.isCurrent) return;+ loadMore();+ });+ }+body = CustomScrollView(controller: scrollController,physics: const AlwaysScrollableScrollPhysics(),@@ -91,13 +107,14 @@ class LibraryAuthorsTab extends StatelessWidget {padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),sliver: SliverGrid(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: responsiveGridCount(context),+ crossAxisCount: cols,childAspectRatio: 0.68,crossAxisSpacing: 10,mainAxisSpacing: 10,),delegate: SliverChildBuilderDelegate((context, index) {+ maybeLoadAhead(index);if (index >= authors.length) {return const Center(child: Padding(@@ -126,32 +143,6 @@ class LibraryAuthorsTab extends StatelessWidget {);}- // Same load-ahead as the books grid: pull the next page while there is- // less than ~two screens left, and stay quiet while a sheet is on top.- const loadAheadPx = 1200.0;- final loadMore = onLoadMore;- if (hasMore && !isLoadingAuthors && authors.isNotEmpty && loadMore != null) {- final route = ModalRoute.of(context);- WidgetsBinding.instance.addPostFrameCallback((_) {- if (route != null && !route.isCurrent) return;- final c = scrollController;- if (c != null && c.hasClients && c.position.extentAfter < loadAheadPx) {- loadMore();- }- });- }-- return NotificationListener<ScrollNotification>(- onNotification: (n) {- if (hasMore &&- loadMore != null &&- n is ScrollUpdateNotification &&- n.metrics.pixels >= n.metrics.maxScrollExtent - loadAheadPx) {- loadMore();- }- return false;- },- child: RefreshIndicator(onRefresh: onRefresh, child: body),- );+ return RefreshIndicator(onRefresh: onRefresh, child: body);}}diff --git a/lib/widgets/library_books_tab.dart b/lib/widgets/library_books_tab.dartindex 270c41a5..3eb3fb9b 100644--- a/lib/widgets/library_books_tab.dart+++ b/lib/widgets/library_books_tab.dart@@ -26,14 +26,15 @@ class LibraryBooksTab extends StatelessWidget {/// floats independently.final Widget? headerSliver;- /// Called when the user scrolls within [_loadAheadPx] of the bottom, or taps- /// retry after a failed page; library_screen owns the actual page-fetch- /// logic.+ /// Called when the grid gets within [_loadAheadRows] rows of its end, or the+ /// user taps retry after a failed page; library_screen owns the actual+ /// page-fetch logic.final VoidCallback onLoadMore;- // How far above the bottom the next page is requested. About two phone- // screens, so the fetch is usually done before the user gets there.- static const double _loadAheadPx = 1200;+ // How many rows before the end the next page is requested. Eight rows is+ // about two phone screens, so the fetch is usually done before the user+ // gets there.+ static const _loadAheadRows = 8;/// Optional explicit ScrollController. When tabs are kept alive in an/// IndexedStack each one needs its own controller so scroll positions don't@@ -177,6 +178,29 @@ class LibraryBooksTab extends StatelessWidget {],);} else {+ // Next-page trigger, driven by what the viewport actually builds rather+ // than by scroll metrics. A sliver only re-measures when a child it has+ // already laid out changes, so after appending items beyond the fold it+ // kept quoting the old extent; an extent-based "is there less than two+ // screens left" check then read true on every rebuild and pulled the+ // whole library while the user sat at the top. A tile index can only be+ // built when it is really within a screen or so of the viewport, and+ // the loader cell itself gets built on a tall viewport a page can't+ // fill - so this covers both the scroll case and the iPad fill case.+ final cols = responsiveGridCount(context);+ final loadAheadAt = items.length - cols * _loadAheadRows;+ // Not while a sheet is open on top: on a slow server every grid page+ // is seconds of work, queued ahead of whatever the sheet is asking for.+ final route = ModalRoute.of(context);+ void maybeLoadAhead(int index) {+ if (!hasMore || isLoadingPage || loadFailed) return;+ if (index < loadAheadAt) return;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (route != null && !route.isCurrent) return;+ onLoadMore();+ });+ }+body = CustomScrollView(controller: scrollController,physics: const AlwaysScrollableScrollPhysics(),@@ -186,13 +210,14 @@ class LibraryBooksTab extends StatelessWidget {padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),sliver: SliverGrid(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: responsiveGridCount(context),+ crossAxisCount: cols,childAspectRatio: rectangleCovers ? 0.48 : 0.68,crossAxisSpacing: 10,mainAxisSpacing: 10,),delegate: SliverChildBuilderDelegate((context, index) {+ maybeLoadAhead(index);if (index >= items.length) {if (loadFailed) {return Center(@@ -239,38 +264,6 @@ class LibraryBooksTab extends StatelessWidget {);}- // On a tall/wide viewport (tablets) a page of results can land entirely- // within the current screen, so nothing scrolls and the bottom-trigger- // below never fires. After layout, keep pulling pages while there's less- // content below the fold than the scroll-trigger's own margin -- // stopping merely at "technically scrollable" left iPads sitting on a- // visible, forever-spinning loader until the user nudged the grid.- if (hasMore && !isLoadingPage && !loadFailed && items.isNotEmpty) {- // Don't keep pulling pages while a sheet is open on top: on a slow- // server every grid page is seconds of work, queued ahead of whatever- // the sheet is asking for.- final route = ModalRoute.of(context);- WidgetsBinding.instance.addPostFrameCallback((_) {- if (route != null && !route.isCurrent) return;- final c = scrollController;- if (c != null &&- c.hasClients &&- c.position.extentAfter < _loadAheadPx) {- onLoadMore();- }- });- }-- return NotificationListener<ScrollNotification>(- onNotification: (n) {- if (!loadFailed &&- n is ScrollUpdateNotification &&- n.metrics.pixels >= n.metrics.maxScrollExtent - _loadAheadPx) {- onLoadMore();- }- return false;- },- child: RefreshIndicator(onRefresh: onRefresh, child: body),- );+ return RefreshIndicator(onRefresh: onRefresh, child: body);}}diff --git a/lib/widgets/library_series_tab.dart b/lib/widgets/library_series_tab.dartindex 7927e82f..6bc1fb42 100644--- a/lib/widgets/library_series_tab.dart+++ b/lib/widgets/library_series_tab.dart@@ -124,6 +124,8 @@ class LibrarySeriesTab extends StatelessWidget {return NotificationListener<ScrollNotification>(onNotification: (n) {if (n is ScrollUpdateNotification &&+ n.depth == 0 &&+ n.metrics.axis == Axis.vertical &&n.metrics.pixels >= n.metrics.maxScrollExtent - 400) {onLoadMore();}