Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Reduce battery drain, fix buffer settings, misc fixes

Nathan Poulson771e19d3df1c
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 90b22c69..ddecb548 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -12,6 +12,7 @@ import android.media.audiofx.Virtualizer
import android.os.Build
import android.os.Environment
import android.os.StatFs
+
import android.util.Log
import com.ryanheise.audioservice.AudioServiceActivity
import com.ryanheise.just_audio.MonoController
@@ -46,6 +47,7 @@ class MainActivity : AudioServiceActivity() {
moveTaskToBack(true)
result.success(true)
}
+
"isBluetoothAudioConnected" -> {
result.success(isBluetoothAudioConnected())
}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index ed8f412a..ca247382 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -136,6 +136,7 @@ class ApiService {
/// Make an authenticated GET request, retrying once on 401 with a refreshed token.
Future<http.Response> _authGet(Uri url, {Map<String, String>? headers, Duration timeout = const Duration(seconds: 15)}) async {
+
final h = headers ?? _headers;
var response = await http.get(url, headers: h).timeout(timeout);
if (response.statusCode == 401) {
@@ -154,6 +155,7 @@ class ApiService {
/// Make an authenticated POST request, retrying once on 401 with a refreshed token.
Future<http.Response> _authPost(Uri url, {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) async {
+
final h = headers ?? _headers;
var response = await http.post(url, headers: h, body: body).timeout(timeout);
if (response.statusCode == 401 && !_isLegacyToken) {
@@ -568,7 +570,7 @@ class ApiService {
'manufacturer': deviceManufacturer,
'model': deviceModel,
},
- 'forceDirectPlay': forceDirectPlay,
+ 'forceDirectPlay': !forceTranscode,
'forceTranscode': forceTranscode,
'mediaPlayer': 'unknown',
'supportedMimeTypes': [
@@ -577,6 +579,14 @@ class ApiService {
'audio/mp4',
'audio/ogg',
'audio/aac',
+ 'audio/x-m4a',
+ 'audio/x-m4b',
+ 'audio/opus',
+ 'audio/webm',
+ 'audio/wav',
+ 'audio/x-wav',
+ 'audio/x-matroska',
+ 'audio/x-ms-wma',
],
};
if (startOffset != null && startOffset > 0) body['startOffset'] = startOffset;
@@ -810,6 +820,14 @@ class ApiService {
'audio/mp4',
'audio/ogg',
'audio/aac',
+ 'audio/x-m4a',
+ 'audio/x-m4b',
+ 'audio/opus',
+ 'audio/webm',
+ 'audio/wav',
+ 'audio/x-wav',
+ 'audio/x-matroska',
+ 'audio/x-ms-wma',
],
}),
timeout: const Duration(seconds: 20));
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 8c4e3486..7aee969e 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -26,11 +26,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
handleInterruptions: false,
audioLoadConfiguration: const AudioLoadConfiguration(
androidLoadControl: AndroidLoadControl(
- minBufferDuration: Duration(minutes: 5),
- maxBufferDuration: Duration(minutes: 5),
bufferForPlaybackDuration: Duration(milliseconds: 500),
- bufferForPlaybackAfterRebufferDuration: Duration(milliseconds: 2000),
- backBufferDuration: Duration(minutes: 5),
+ bufferForPlaybackAfterRebufferDuration: Duration(seconds: 2),
+ targetBufferBytes: 1 * 1024 * 1024, // 1 MB hard cap
),
),
);
@@ -1822,14 +1820,14 @@ class AudioPlayerService extends ChangeNotifier {
_completionSub?.cancel();
_completionSub = null;
_lastKnownPositionSec = 0;
- if (_bgSaveTimer != null) debugPrint('[Battery] bgSaveTimer CANCELLED (clearState)');
+
_bgSaveTimer?.cancel();
_bgSaveTimer = null;
_eqSessionSub?.cancel();
_eqSessionSub = null;
_streamRetryCount = 0;
_retryInProgress = false;
- if (_stuckCheckTimer != null) debugPrint('[Battery] stuckCheckTimer CANCELLED (clearState)');
+
_stuckCheckTimer?.cancel();
_stuckCheckTimer = null;
_resetStuckDetection();
@@ -1945,7 +1943,7 @@ class AudioPlayerService extends ChangeNotifier {
// Safety-net timer for position persistence when Android throttles the
// Dart position stream in the background. The primary positionStream
// listener saves every 5s; this only matters when that stream goes silent.
- debugPrint('[Battery] bgSaveTimer STARTED (60s interval)');
+
_bgSaveTimer = Timer.periodic(const Duration(seconds: 60), (_) async {
if (_currentItemId == null || _player == null || !_player!.playing) return;
final pos = position;
@@ -2129,7 +2127,11 @@ class AudioPlayerService extends ChangeNotifier {
_stuckCheckTimer?.cancel();
_resetStuckDetection();
- debugPrint('[Battery] stuckCheckTimer STARTED (10s interval)');
+ // Stuck detection is only needed on iOS (xHE-AAC/USAC decoder freeze).
+ // Skip on Android to reduce background CPU wakeups.
+ if (!Platform.isIOS) return;
+
+
_stuckCheckTimer = Timer.periodic(const Duration(seconds: 10), (_) async {
// Only check while actively playing
if (_player == null || !_player!.playing) {
@@ -2444,7 +2446,6 @@ class AudioPlayerService extends ChangeNotifier {
_updateWakeLock(true);
// Restart safety-net save timer (stopped on pause to avoid background wakes)
if (_bgSaveTimer == null || !_bgSaveTimer!.isActive) {
- debugPrint('[Battery] bgSaveTimer RESTARTED (play)');
_bgSaveTimer?.cancel();
_bgSaveTimer = Timer.periodic(const Duration(seconds: 60), (_) async {
if (_currentItemId == null || _player == null || !_player!.playing) return;
@@ -2469,12 +2470,10 @@ class AudioPlayerService extends ChangeNotifier {
_lastPauseTime = DateTime.now();
// Stop timers to avoid background wakes while paused
if (_bgSaveTimer != null) {
- debugPrint('[Battery] bgSaveTimer STOPPED (pause)');
_bgSaveTimer!.cancel();
_bgSaveTimer = null;
}
if (_stuckCheckTimer != null) {
- debugPrint('[Battery] stuckCheckTimer STOPPED (pause)');
_stuckCheckTimer!.cancel();
_stuckCheckTimer = null;
}
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index fe7d21b3..766935dc 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -295,7 +295,7 @@ class HomeWidgetService {
void _startProgressTimer() {
if (_progressTimer?.isActive == true) return;
- _progressTimer = Timer.periodic(const Duration(seconds: 60), (_) {
+ _progressTimer = Timer.periodic(const Duration(seconds: 120), (_) {
_scheduleUpdate();
});
}
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
index 88b9b347..22d075db 100644
--- a/lib/services/sleep_timer_service.dart
+++ b/lib/services/sleep_timer_service.dart
@@ -165,62 +165,81 @@ class SleepTimerService extends ChangeNotifier {
debugPrint('[SleepTimer] Set time sleep: ${duration.inMinutes}m');
}
+ int _tickIntervalSeconds = 5;
+
void _startTimeCountdown() {
_timer?.cancel();
_wasPlaying = _isPlaybackActive;
- _timer = Timer.periodic(const Duration(seconds: 1), (_) async {
- if (_timeRemaining.inSeconds <= 0) {
- _triggerSleep();
- return;
- }
- final isPlaying = _isPlaybackActive;
-
- // Detect pause->play transition and reset if setting is on
- if (isPlaying && !_wasPlaying) {
- final resetOnPause = await PlayerSettings.getResetSleepOnPause();
- if (resetOnPause) {
- _timeRemaining = _initialDuration;
- _warningSent = false;
- if (_isFadingOut) {
- _isFadingOut = false;
- _player.setVolume(_fadeStartVolume);
- }
- debugPrint('[SleepTimer] Reset to ${_initialDuration.inMinutes}m on resume');
- onToast?.call('Sleep timer reset: ${_initialDuration.inMinutes}m');
+ _scheduleNextTick();
+ }
+
+ void _scheduleNextTick() {
+ _timer?.cancel();
+ // Tick every 1s during fade period (last 35s), every 5s otherwise
+ final nearFade = _timeRemaining <= _warningThreshold + const Duration(seconds: 5);
+ _tickIntervalSeconds = nearFade ? 1 : 5;
+ _timer = Timer.periodic(Duration(seconds: _tickIntervalSeconds), _onTimerTick);
+ }
+
+ void _onTimerTick(Timer timer) async {
+ if (_timeRemaining.inSeconds <= 0) {
+ _triggerSleep();
+ return;
+ }
+ final isPlaying = _isPlaybackActive;
+
+ // Detect pause->play transition and reset if setting is on
+ if (isPlaying && !_wasPlaying) {
+ final resetOnPause = await PlayerSettings.getResetSleepOnPause();
+ if (resetOnPause) {
+ _timeRemaining = _initialDuration;
+ _warningSent = false;
+ if (_isFadingOut) {
+ _isFadingOut = false;
+ _player.setVolume(_fadeStartVolume);
}
+ debugPrint('[SleepTimer] Reset to ${_initialDuration.inMinutes}m on resume');
+ onToast?.call('Sleep timer reset: ${_initialDuration.inMinutes}m');
+ _scheduleNextTick();
}
- _wasPlaying = isPlaying;
+ }
+ _wasPlaying = isPlaying;
- // Only count down when playing
- if (isPlaying) {
- _timeRemaining -= const Duration(seconds: 1);
- if (_timeRemaining.inSeconds % 30 == 0) {
- debugPrint('[Battery] SleepTimer TICK: ${_timeRemaining.inMinutes}m${_timeRemaining.inSeconds % 60}s remaining');
- }
+ // Only count down when playing
+ if (isPlaying) {
+ _timeRemaining -= Duration(seconds: _tickIntervalSeconds);
+ if (_timeRemaining.inSeconds % 30 == 0) {
- // Wind-down warning at 30 seconds: vibration + optional fade
- if (!_warningSent && _timeRemaining <= _warningThreshold && _timeRemaining.inSeconds > 0) {
- _warningSent = true;
- onToast?.call('Sleep timer ending soon...');
- final fadeEnabled = await PlayerSettings.getSleepFadeOut();
- if (fadeEnabled && !_cast.isCasting) {
- _isFadingOut = true;
- _fadeStartVolume = _player.volume;
- debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining - starting fade');
- } else {
- debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining');
- }
- }
+ }
+
+ // Switch to fast ticks when approaching warning threshold
+ if (_tickIntervalSeconds > 1 &&
+ _timeRemaining <= _warningThreshold + const Duration(seconds: 5)) {
+ _scheduleNextTick();
+ }
- // Gradually lower volume during the last 30 seconds
- if (_isFadingOut && _timeRemaining.inSeconds > 0 && !_cast.isCasting) {
- final fraction = _timeRemaining.inSeconds / _warningThreshold.inSeconds;
- _player.setVolume((_fadeStartVolume * fraction).clamp(0.0, 1.0));
+ // Wind-down warning at 30 seconds: vibration + optional fade
+ if (!_warningSent && _timeRemaining <= _warningThreshold && _timeRemaining.inSeconds > 0) {
+ _warningSent = true;
+ onToast?.call('Sleep timer ending soon...');
+ final fadeEnabled = await PlayerSettings.getSleepFadeOut();
+ if (fadeEnabled && !_cast.isCasting) {
+ _isFadingOut = true;
+ _fadeStartVolume = _player.volume;
+ debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining - starting fade');
+ } else {
+ debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining');
}
+ }
- notifyListeners(); // fires every 1s while playing - drives UI countdown
+ // Gradually lower volume during the last 30 seconds
+ if (_isFadingOut && _timeRemaining.inSeconds > 0 && !_cast.isCasting) {
+ final fraction = _timeRemaining.inSeconds / _warningThreshold.inSeconds;
+ _player.setVolume((_fadeStartVolume * fraction).clamp(0.0, 1.0));
}
- });
+
+ notifyListeners();
+ }
}
/// Add time (used by shake reset in time mode, or manual add)
@@ -235,6 +254,8 @@ class SleepTimerService extends ChangeNotifier {
_player.setVolume(_fadeStartVolume);
}
}
+ // Reschedule in case we jumped between slow/fast tick zones
+ if (_timer?.isActive == true) _scheduleNextTick();
notifyListeners();
debugPrint('[SleepTimer] Added ${extra.inMinutes}m — now ${_timeRemaining.inMinutes}m');
}
@@ -380,7 +401,9 @@ class SleepTimerService extends ChangeNotifier {
_accelSub?.cancel();
debugPrint('[Battery] Accelerometer stream STARTED (shakeMode=$_shakeMode)');
- _accelSub = userAccelerometerEventStream().listen((event) {
+ _accelSub = userAccelerometerEventStream(
+ samplingPeriod: const Duration(milliseconds: 100),
+ ).listen((event) {
final magnitude = sqrt(
event.x * event.x + event.y * event.y + event.z * event.z);
if (magnitude > _shakeThreshold) {
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index f96ad8bd..f6adc2d9 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -610,8 +610,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
if (_hasLocalOverride)
_moreItem(cs, Icons.layers_clear_rounded, 'Clear Local Metadata',
onTap: () { Navigator.pop(ctx); _clearOverride(context); }),
- _moreItem(cs, Icons.recommend_rounded, 'Recommend Book',
- onTap: () { Navigator.pop(ctx); _recommendBook(context, title, authorName); }),
+
if (_showGoodreads)
_moreItem(cs, Icons.local_library_rounded, 'Search on Goodreads',
onTap: () { Navigator.pop(ctx); _openGoodreads(title, authorName); }),
@@ -1220,149 +1219,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
}
}
- /// Build an Audible URL for the book, using ASIN if available, otherwise search.
- String _buildAudibleUrl(String title, String author) {
- // Map device locale to Audible domain
- final locale = ui.PlatformDispatcher.instance.locale;
- final country = locale.countryCode?.toUpperCase() ?? '';
- final lang = locale.languageCode;
- String domain;
- switch (country) {
- case 'GB': domain = 'audible.co.uk'; break;
- case 'AU': domain = 'audible.com.au'; break;
- case 'DE': case 'AT': case 'CH': domain = 'audible.de'; break;
- case 'FR': domain = 'audible.fr'; break;
- case 'IT': domain = 'audible.it'; break;
- case 'ES': domain = 'audible.es'; break;
- case 'JP': domain = 'audible.co.jp'; break;
- case 'IN': domain = 'audible.in'; break;
- case 'CA': domain = 'audible.ca'; break;
- case 'BR': domain = 'audible.com.br'; break;
- default:
- if (lang == 'de') { domain = 'audible.de'; }
- else if (lang == 'fr') { domain = 'audible.fr'; }
- else if (lang == 'ja') { domain = 'audible.co.jp'; }
- else { domain = 'audible.com'; }
- }
-
- if (_asin != null && _asin!.isNotEmpty) {
- return 'https://www.$domain/pd/$_asin';
- }
- final query = Uri.encodeComponent('$title $author'.trim());
- return 'https://www.$domain/search?keywords=$query';
- }
-
- Future<void> _recommendBook(BuildContext context, String title, String author) async {
- final lib = context.read<LibraryProvider>();
- final coverUrl = _fullResCoverUrl ?? _coverUrl;
- if (coverUrl == null) return;
-
- // Show a loading indicator
- showDialog(
- context: context,
- barrierDismissible: false,
- builder: (_) => const Center(child: CircularProgressIndicator()),
- );
-
- try {
- // Download cover
- final response = await http.get(Uri.parse(coverUrl), headers: lib.mediaHeaders);
- if (response.statusCode != 200) throw Exception('Failed to download cover');
- final coverBytes = response.bodyBytes;
-
- // Decode the cover image
- final codec = await ui.instantiateImageCodec(coverBytes);
- final frame = await codec.getNextFrame();
- final coverImage = frame.image;
-
- // Build poster: cover image with a gradient bar at the bottom for title/author
- final coverW = coverImage.width.toDouble();
- final coverH = coverImage.height.toDouble();
- final barHeight = coverH * 0.18;
- final posterH = coverH + barHeight;
-
- final recorder = ui.PictureRecorder();
- final canvas = Canvas(recorder, Rect.fromLTWH(0, 0, coverW, posterH));
-
- // Dark background for the bar area
- canvas.drawRect(Rect.fromLTWH(0, 0, coverW, posterH), Paint()..color = const Color(0xFF1A1A1A));
-
- // Draw cover
- canvas.drawImage(coverImage, Offset.zero, Paint());
-
- // Title text
- final titleFontSize = coverW * 0.045;
- final authorFontSize = coverW * 0.035;
- final padding = coverW * 0.04;
-
- final titleBuilder = ui.ParagraphBuilder(ui.ParagraphStyle(
- textAlign: TextAlign.left,
- maxLines: 2,
- ellipsis: '...',
- ))
- ..pushStyle(ui.TextStyle(
- color: const Color(0xFFFFFFFF),
- fontSize: titleFontSize,
- fontWeight: FontWeight.w700,
- ))
- ..addText(title);
- final titleParagraph = titleBuilder.build()..layout(ui.ParagraphConstraints(width: coverW - padding * 2));
-
- canvas.drawParagraph(titleParagraph, Offset(padding, coverH + padding * 0.5));
-
- // Author text
- final authorBuilder = ui.ParagraphBuilder(ui.ParagraphStyle(
- textAlign: TextAlign.left,
- maxLines: 1,
- ellipsis: '...',
- ))
- ..pushStyle(ui.TextStyle(
- color: const Color(0xFFAAAAAA),
- fontSize: authorFontSize,
- fontWeight: FontWeight.w400,
- ))
- ..addText(author);
- final authorParagraph = authorBuilder.build()..layout(ui.ParagraphConstraints(width: coverW - padding * 2));
-
- canvas.drawParagraph(authorParagraph, Offset(padding, coverH + padding * 0.5 + titleParagraph.height + padding * 0.25));
-
- // Convert to image
- final picture = recorder.endRecording();
- final posterImage = await picture.toImage(coverW.toInt(), posterH.toInt());
- final byteData = await posterImage.toByteData(format: ui.ImageByteFormat.png);
- if (byteData == null) throw Exception('Failed to encode poster');
-
- // Save to temp file
- final safeTitle = title.replaceAll(RegExp(r'[^\w\s-]'), '').trim();
- final dir = await getTemporaryDirectory();
- final file = File('${dir.path}/${safeTitle}_recommend.png');
- await file.writeAsBytes(byteData.buffer.asUint8List());
-
- // Build Audible link
- final audibleUrl = _buildAudibleUrl(title, author);
-
- if (!mounted) return;
- Navigator.pop(context); // dismiss loading
-
- final box = context.findRenderObject() as RenderBox?;
- final origin = box != null ? box.localToGlobal(Offset.zero) & box.size : null;
- await Share.shareXFiles(
- [XFile(file.path)],
- text: audibleUrl,
- sharePositionOrigin: origin,
- );
- } catch (e) {
- if (mounted) {
- Navigator.pop(context); // dismiss loading
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text('Failed to create recommendation: $e'),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
- }
- }
- }
-
void _showFullCover(BuildContext context, String url, Map<String, String> headers, String title) {
Navigator.of(context).push(PageRouteBuilder(
opaque: false,
diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dart
index 30735bd0..71f74884 100644
--- a/lib/widgets/card_progress_bar.dart
+++ b/lib/widgets/card_progress_bar.dart
@@ -236,52 +236,42 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB
final bookProgress = totalDur > 0 ? (posS / totalDur).clamp(0.0, 1.0) : 0.0;
double chapterStart = 0, chapterEnd = totalDur;
+ String? resolvedChapterName;
+ int resolvedChapterIdx = -1;
+
+ // Always resolve chapter from posS so boundaries, fill, and name
+ // all use the same position. Using player.currentChapter can
+ // disagree with _smoothPos in multi-track books (track index race).
+ List<dynamic> chapterSource;
if (_isCastMode) {
- final chapter = cast.currentChapter;
- if (chapter != null) {
- chapterStart = (chapter['start'] as num?)?.toDouble() ?? 0;
- chapterEnd = (chapter['end'] as num?)?.toDouble() ?? totalDur;
- } else if (cast.castingChapters.isNotEmpty) {
- for (final ch in cast.castingChapters) {
- final m = ch as Map<String, dynamic>;
- final s = (m['start'] as num?)?.toDouble() ?? 0;
- final e = (m['end'] as num?)?.toDouble() ?? 0;
- if (posS >= s && posS < e) {
- chapterStart = s;
- chapterEnd = e;
- break;
- }
- }
- }
+ chapterSource = cast.castingChapters;
} else if (widget.isActive) {
- final chapter = player.activeSeekTarget == null ? player.currentChapter : null;
- if (chapter != null) {
- chapterStart = (chapter['start'] as num?)?.toDouble() ?? 0;
- chapterEnd = (chapter['end'] as num?)?.toDouble() ?? totalDur;
- } else if (player.chapters.isNotEmpty) {
- for (final ch in player.chapters) {
- final m = ch as Map<String, dynamic>;
- final s = (m['start'] as num?)?.toDouble() ?? 0;
- final e = (m['end'] as num?)?.toDouble() ?? 0;
- if (posS >= s && posS < e) {
- chapterStart = s;
- chapterEnd = e;
- break;
- }
- }
- }
- } else if (widget.chapters.isNotEmpty) {
- // Inactive card: find chapter from stored chapters list using static position
- for (final ch in widget.chapters) {
- final m = ch as Map<String, dynamic>;
+ chapterSource = player.chapters.isNotEmpty ? player.chapters : widget.chapters;
+ } else {
+ chapterSource = widget.chapters;
+ }
+
+ if (chapterSource.isNotEmpty) {
+ for (int ci = 0; ci < chapterSource.length; ci++) {
+ final m = chapterSource[ci] as Map<String, dynamic>;
final s = (m['start'] as num?)?.toDouble() ?? 0;
final e = (m['end'] as num?)?.toDouble() ?? 0;
if (posS >= s && posS < e) {
chapterStart = s;
chapterEnd = e;
+ resolvedChapterName = m['title'] as String?;
+ resolvedChapterIdx = ci;
break;
}
}
+ // Past last chapter end - use last chapter
+ if (resolvedChapterIdx < 0 && posS > 0) {
+ final last = chapterSource.last as Map<String, dynamic>;
+ chapterStart = (last['start'] as num?)?.toDouble() ?? 0;
+ chapterEnd = (last['end'] as num?)?.toDouble() ?? totalDur;
+ resolvedChapterName = last['title'] as String?;
+ resolvedChapterIdx = chapterSource.length - 1;
+ }
}
final chapterDur = chapterEnd - chapterStart;
final chapterPos = (posS - chapterStart).clamp(0.0, chapterDur);
@@ -337,8 +327,13 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB
final w = cons.maxWidth;
final p = _chapterDragValue ?? chapterProgress;
final isDragging = _chapterDragValue != null;
- final chName = widget.chapterName != null
- ? _smartChapterName(widget.chapterName!, widget.chapterIndex, widget.totalChapters)
+ // Prefer the chapter name resolved from posS (consistent with
+ // the fill position) over the externally-passed name which
+ // may come from player.currentChapter (different position source).
+ final rawName = resolvedChapterName ?? widget.chapterName;
+ final chIdx = resolvedChapterIdx >= 0 ? resolvedChapterIdx : widget.chapterIndex;
+ final chName = rawName != null
+ ? _smartChapterName(rawName, chIdx, widget.totalChapters)
: null;
return GestureDetector(
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index 0b8b958b..38b522c0 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -462,7 +462,8 @@ class GridSeriesTile extends StatelessWidget {
final itemIds = (collapsedSeries['libraryItemIds'] as List<dynamic>?)
?.map((e) => e as String)
.toList() ?? [item['id'] as String? ?? ''];
- final numBooks = collapsedSeries['numBooks'] as int? ?? itemIds.length;
+ final rawNumBooks = collapsedSeries['numBooks'] as int? ?? 0;
+ final numBooks = rawNumBooks > 0 ? rawNumBooks : itemIds.length;
final coverUrls = itemIds
.take(4)
.map((id) => lib.getCoverUrl(id))
diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dart
index ae79fdf7..0adf0e89 100644
--- a/lib/widgets/series_books_sheet.dart
+++ b/lib/widgets/series_books_sheet.dart
@@ -357,7 +357,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
'name': collapsed['name'] as String? ?? '',
'id': collapsed['id'] as String? ?? '',
'books': matchingBooks,
- 'numBooks': collapsed['numBooks'] as int? ?? itemIds.length,
+ 'numBooks': (collapsed['numBooks'] as int? ?? 0) > 0 ? collapsed['numBooks'] as int : itemIds.length,
});
_assignedBookIds.addAll(itemIds);
}
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
index 2477ffe1..4e948be2 100644
--- a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
@@ -55,6 +55,7 @@ import androidx.media3.datasource.DefaultHttpDataSource;
import androidx.media3.datasource.cache.Cache;
import androidx.media3.datasource.cache.CacheDataSink;
import androidx.media3.datasource.cache.CacheDataSource;
+
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor;
import androidx.media3.datasource.cache.SimpleCache;
import androidx.media3.database.StandaloneDatabaseProvider;
@@ -179,13 +180,13 @@ public class AudioPlayer implements MethodCallHandler, Player.Listener, Metadata
}
switch (player.getPlaybackState()) {
case Player.STATE_BUFFERING:
- handler.postDelayed(this, 200);
+ handler.postDelayed(this, 500);
break;
case Player.STATE_READY:
if (player.getPlayWhenReady()) {
- handler.postDelayed(this, 500);
+ handler.postDelayed(this, 2000);
} else {
- handler.postDelayed(this, 1000);
+ handler.postDelayed(this, 5000);
}
break;
default:
@@ -223,7 +224,7 @@ public class AudioPlayer implements MethodCallHandler, Player.Listener, Metadata
.setPrioritizeTimeOverSizeThresholds((Boolean)loadControlMap.get("prioritizeTimeOverSizeThresholds"))
.setBackBuffer((int)((getLong(loadControlMap.get("backBufferDuration")))/1000), false);
if (loadControlMap.get("targetBufferBytes") != null) {
- builder.setTargetBufferBytes((Integer)loadControlMap.get("targetBufferBytes"));
+ builder.setTargetBufferBytes((int)(long)(getLong(loadControlMap.get("targetBufferBytes"))));
}
loadControl = builder.build();
}
@@ -532,6 +533,7 @@ public class AudioPlayer implements MethodCallHandler, Player.Listener, Metadata
case "setPreferredPeakBitRate":
result.success(new HashMap<String, Object>());
break;
+
case "seek":
Long position = getLong(call.argument("position"));
Integer index = call.argument("index");
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java
index cc4453fe..99705f37 100644
--- a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/MainMethodCallHandler.java
@@ -78,6 +78,7 @@ public class MainMethodCallHandler implements MethodCallHandler {
result.success(null);
break;
}
+
default:
result.notImplemented();
break;
diff --git a/packages/just_audio/lib/just_audio.dart b/packages/just_audio/lib/just_audio.dart
index 6abae1d4..0aa64da4 100644
--- a/packages/just_audio/lib/just_audio.dart
+++ b/packages/just_audio/lib/just_audio.dart
@@ -640,8 +640,8 @@ class AudioPlayer {
if (!_disposed) {
_positionSubject!.addStream(createPositionStream(
steps: 800,
- minPeriod: const Duration(milliseconds: 16),
- maxPeriod: const Duration(milliseconds: 200)));
+ minPeriod: const Duration(milliseconds: 500),
+ maxPeriod: const Duration(milliseconds: 1000)));
}
}
return _positionSubject!.stream;
diff --git a/pubspec.yaml b/pubspec.yaml
index a2ec0ad7..f73d2a7c 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.52+71
+version: 1.8.53+72
# v1.8.41: JWT auth (accessToken + refreshToken), MANAGE_EXTERNAL_STORAGE removed from playstore flavor
# Build scripts (run from Git Bash):
# . ./build_bundle.sh - Play Store AAB (no MANAGE_EXTERNAL_STORAGE)