Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Battery optimizations: throttle progress bars, sleep timer, save intervals

Nathan Poulsondf2fcea48bea
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index b9f43cae..b8b50d20 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1861,13 +1861,10 @@ class AudioPlayerService extends ChangeNotifier {
_lastChapterCheckSec = -1;
_lastKnownPositionSec = 0;
- // Independent periodic timer for position persistence.
- // The positionStream listener (below) saves every 5s, but Android can
- // throttle stream events when the Dart isolate is backgrounded while
- // ExoPlayer keeps playing natively. This timer acts as a safety net so
- // progress is still written to SharedPreferences even when the stream
- // goes silent.
- _bgSaveTimer = Timer.periodic(const Duration(seconds: 10), (_) async {
+ // 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.
+ _bgSaveTimer = Timer.periodic(const Duration(seconds: 30), (_) async {
if (_currentItemId == null || _player == null || !_player!.playing) return;
final pos = position;
final posSec = pos.inMilliseconds / 1000.0;
@@ -1932,18 +1929,36 @@ class AudioPlayerService extends ChangeNotifier {
String? chapterTitle;
double chapterStart = 0;
double chapterEnd = _totalDuration;
- for (int i = 0; i < _chapters.length; i++) {
- final ch = _chapters[i] as Map<String, dynamic>;
- final start = (ch['start'] as num?)?.toDouble() ?? 0;
- final end = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
- if (posSec >= start && posSec < end) {
- chapterIdx = i;
+
+ // Fast path: check if still in the cached chapter
+ if (_lastNotifiedChapterIndex >= 0 && _lastNotifiedChapterIndex < _chapters.length) {
+ final ch = _chapters[_lastNotifiedChapterIndex] as Map<String, dynamic>;
+ final s = (ch['start'] as num?)?.toDouble() ?? 0;
+ final e = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
+ if (posSec >= s && posSec < e) {
+ chapterIdx = _lastNotifiedChapterIndex;
chapterTitle = ch['title'] as String?;
- chapterStart = start;
- chapterEnd = end;
- break;
+ chapterStart = s;
+ chapterEnd = e;
+ }
+ }
+
+ // Slow path: linear scan only if cached chapter didn't match
+ if (chapterIdx < 0) {
+ for (int i = 0; i < _chapters.length; i++) {
+ final ch = _chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? _totalDuration;
+ if (posSec >= start && posSec < end) {
+ chapterIdx = i;
+ chapterTitle = ch['title'] as String?;
+ chapterStart = start;
+ chapterEnd = end;
+ break;
+ }
}
}
+
if (chapterIdx >= 0 && chapterIdx != _lastNotifiedChapterIndex) {
_lastNotifiedChapterIndex = chapterIdx;
_currentChapterStart = chapterStart;
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index fb642ac7..fe7d21b3 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: 30), (_) {
+ _progressTimer = Timer.periodic(const Duration(seconds: 60), (_) {
_scheduleUpdate();
});
}
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
index 150cb064..5e1f07b3 100644
--- a/lib/services/sleep_timer_service.dart
+++ b/lib/services/sleep_timer_service.dart
@@ -168,56 +168,79 @@ class SleepTimerService extends ChangeNotifier {
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');
+ _lastTickTime = DateTime.now();
+ _scheduleNextTick();
+ }
+
+ DateTime _lastTickTime = DateTime.now();
+
+ /// Use a shorter interval during fade-out for smooth volume, longer otherwise.
+ void _scheduleNextTick() {
+ _timer?.cancel();
+ final interval = (_isFadingOut || _timeRemaining <= _warningThreshold)
+ ? const Duration(seconds: 1)
+ : const Duration(seconds: 5);
+ _timer = Timer.periodic(interval, (_) => _onTimerTick());
+ }
+
+ void _onTimerTick() 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(); // switch back to slow interval
}
- _wasPlaying = isPlaying;
-
- // Only count down when playing
- if (isPlaying) {
- _timeRemaining -= const Duration(seconds: 1);
-
- // 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');
- }
- }
-
- // 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));
+ }
+ _wasPlaying = isPlaying;
+
+ // Only count down when playing
+ if (isPlaying) {
+ // Use real elapsed time instead of assuming fixed tick interval
+ final now = DateTime.now();
+ final elapsed = now.difference(_lastTickTime);
+ _lastTickTime = now;
+ _timeRemaining -= elapsed;
+ if (_timeRemaining.isNegative) _timeRemaining = Duration.zero;
+
+ // 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');
}
+ _scheduleNextTick(); // switch to 1s for smooth fade
+ }
- notifyListeners();
+ // 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();
+ } else {
+ _lastTickTime = DateTime.now(); // don't accumulate paused time
+ }
}
/// Add time (used by shake reset in time mode, or manual add)
diff --git a/lib/widgets/card_edge_progress_bar.dart b/lib/widgets/card_edge_progress_bar.dart
index 073fc99b..f8f58fab 100644
--- a/lib/widgets/card_edge_progress_bar.dart
+++ b/lib/widgets/card_edge_progress_bar.dart
@@ -36,10 +36,11 @@ class CardEdgeProgressBar extends StatefulWidget {
}
class _CardEdgeProgressBarState extends State<CardEdgeProgressBar>
- with TickerProviderStateMixin, WidgetsBindingObserver {
+ with SingleTickerProviderStateMixin, WidgetsBindingObserver {
// ── Smooth position tracking (same pattern as CardDualProgressBar) ──
- late AnimationController _smoothTicker;
+ Timer? _smoothTicker;
+ final _tickNotifier = ChangeNotifier(); // drives ListenableBuilder rebuilds
double _lastKnownPos = 0;
DateTime _lastPosTime = DateTime.now();
double _currentSpeed = 1.0;
@@ -64,7 +65,6 @@ class _CardEdgeProgressBarState extends State<CardEdgeProgressBar>
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
- _smoothTicker = AnimationController(vsync: this, duration: const Duration(days: 999));
_expandController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 250),
@@ -108,10 +108,15 @@ class _CardEdgeProgressBarState extends State<CardEdgeProgressBar>
}
void _syncTicker() {
- if (_isPlaying && (widget.isActive || _isCastMode)) {
- if (!_smoothTicker.isAnimating) _smoothTicker.repeat();
- } else {
- if (_smoothTicker.isAnimating) _smoothTicker.stop();
+ final shouldRun = _isPlaying && (widget.isActive || _isCastMode);
+ if (shouldRun && _smoothTicker == null) {
+ _smoothTicker = Timer.periodic(const Duration(milliseconds: 100), (_) {
+ // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
+ _tickNotifier.notifyListeners();
+ });
+ } else if (!shouldRun && _smoothTicker != null) {
+ _smoothTicker!.cancel();
+ _smoothTicker = null;
}
}
@@ -212,7 +217,8 @@ class _CardEdgeProgressBarState extends State<CardEdgeProgressBar>
PlayerSettings.settingsChanged.removeListener(_loadSettings);
ChromecastService().removeListener(_onCastChanged);
_posSub?.cancel();
- _smoothTicker.dispose();
+ _smoothTicker?.cancel();
+ _tickNotifier.dispose();
_expandController.dispose();
super.dispose();
}
@@ -235,7 +241,7 @@ class _CardEdgeProgressBarState extends State<CardEdgeProgressBar>
final active = widget.isActive || _isCastMode;
return ListenableBuilder(
- listenable: Listenable.merge([_smoothTicker, _expandController]),
+ listenable: Listenable.merge([_tickNotifier, _expandController]),
builder: (context, _) {
final staticPos = widget.staticProgress * widget.staticDuration;
final posS = active ? _smoothPos : staticPos;
diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dart
index b8b5eea9..758c3cbb 100644
--- a/lib/widgets/card_progress_bar.dart
+++ b/lib/widgets/card_progress_bar.dart
@@ -25,7 +25,7 @@ class CardDualProgressBar extends StatefulWidget {
@override State<CardDualProgressBar> createState() => _CardDualProgressBarState();
}
-class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerProviderStateMixin, WidgetsBindingObserver {
+class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsBindingObserver {
double? _chapterDragValue;
double? _bookDragValue;
double _bookDragStartDy = 0;
@@ -34,7 +34,8 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
double _chapterScrubSpeed = 1.0;
bool _showBookSlider = false;
bool _speedAdjustedTime = true;
- late AnimationController _smoothTicker;
+ Timer? _smoothTicker;
+ final _tickNotifier = ChangeNotifier(); // drives ListenableBuilder rebuilds
// Smooth position tracking
double _lastKnownPos = 0;
@@ -48,7 +49,6 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
- _smoothTicker = AnimationController(vsync: this, duration: const Duration(days: 999));
_loadSettings();
_subscribePosition();
PlayerSettings.settingsChanged.addListener(_loadSettings);
@@ -79,10 +79,15 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
}
void _syncTicker() {
- if (_isPlaying && (widget.isActive || _isCastMode)) {
- if (!_smoothTicker.isAnimating) _smoothTicker.repeat();
- } else {
- if (_smoothTicker.isAnimating) _smoothTicker.stop();
+ final shouldRun = _isPlaying && (widget.isActive || _isCastMode);
+ if (shouldRun && _smoothTicker == null) {
+ _smoothTicker = Timer.periodic(const Duration(milliseconds: 100), (_) {
+ // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
+ _tickNotifier.notifyListeners();
+ });
+ } else if (!shouldRun && _smoothTicker != null) {
+ _smoothTicker!.cancel();
+ _smoothTicker = null;
}
}
@@ -176,7 +181,8 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
PlayerSettings.settingsChanged.removeListener(_loadSettings);
ChromecastService().removeListener(_onCastChanged);
_posSub?.cancel();
- _smoothTicker.dispose();
+ _smoothTicker?.cancel();
+ _tickNotifier.dispose();
super.dispose();
}
@@ -210,7 +216,7 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
final active = widget.isActive || _isCastMode;
return ListenableBuilder(
- listenable: _smoothTicker,
+ listenable: _tickNotifier,
builder: (context, _) {
final staticPos = widget.staticProgress * widget.staticDuration;
final posS = active ? _smoothPos : staticPos;