Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Split book/podcast queue modes, per-show advance direction, auto-advance fixes

Nathan Poulson641583316870
diff --git a/lib/main.dart b/lib/main.dart
index 9e4d8d45..b4e9f360 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -402,6 +402,8 @@ class _AuthGateState extends State<AuthGate> {
// Migrate old auto-play booleans → unified queueMode (one-time, no-op after first run)
debugPrint('[Init] migrateQueueMode... (${sw.elapsedMilliseconds}ms)');
await PlayerSettings.migrateQueueMode();
+ // Migrate unified queueMode → per-type book/podcast modes (one-time)
+ await PlayerSettings.migrateBookPodcastQueueMode();
// Load device info for server identification
debugPrint('[Init] device info... (${sw.elapsedMilliseconds}ms)');
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 594b844f..653ffde5 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -808,6 +808,13 @@ class LibraryProvider extends ChangeNotifier {
}
}
notifyListeners();
+ } else {
+ // Partial payload (e.g. mark-as-finished from web UI) — debounce a
+ // full progress refresh so episode sheets update without a manual pull.
+ _progressRefreshDebounce?.cancel();
+ _progressRefreshDebounce = Timer(const Duration(milliseconds: 800), () {
+ refreshProgressShelves(force: true, reason: 'user-updated');
+ });
}
}
@@ -1787,14 +1794,41 @@ class LibraryProvider extends ChangeNotifier {
// Auto-play the next book in series if auto_next mode is enabled.
if (newContinueSeriesKey != null && _api != null) {
- PlayerSettings.getQueueMode().then((mode) {
+ PlayerSettings.getBookQueueMode().then((mode) {
if (mode != 'auto_next') return;
// Don't auto-play if BT/headphones just disconnected — the server
// refresh is async and may return after the user left the car.
if (AudioPlayerService.wasNoisyPause) return;
// Skip if local auto-advance already started playback
if (AudioPlayerService().isPlaying) return;
- final cached = _absorbingItemCache[newContinueSeriesKey];
+
+ // The server's continue-series skips partially-read books (they appear
+ // in continue-listening instead). Find the actual lowest-seq unfinished
+ // book in the same series so we don't skip over in-progress books.
+ final finishedData = _lastFinishedItemId != null
+ ? _itemDataWithSeries(_lastFinishedItemId!)
+ : null;
+ final (finSeriesId, finSeq) =
+ finishedData != null ? _extractSeries(finishedData) : (null, null);
+
+ String actualNextKey = newContinueSeriesKey!;
+ if (finSeriesId != null && finSeq != null) {
+ double lowestSeq = double.infinity;
+ for (final key in _absorbingBookIds) {
+ if (key.length > 36) continue; // skip podcast episodes
+ if (isItemFinishedByKey(key)) continue;
+ final data = _absorbingItemCache[key];
+ if (data == null) continue;
+ final (sid, seq) = _extractSeries(data);
+ if (sid != finSeriesId || seq == null || seq <= finSeq) continue;
+ if (seq < lowestSeq) {
+ lowestSeq = seq;
+ actualNextKey = key;
+ }
+ }
+ }
+
+ final cached = _absorbingItemCache[actualNextKey];
if (cached == null) return;
final media = cached['media'] as Map<String, dynamic>? ?? {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
@@ -1804,10 +1838,10 @@ class LibraryProvider extends ChangeNotifier {
final chapters = media['chapters'] as List<dynamic>? ?? [];
AudioPlayerService().playItem(
api: _api!,
- itemId: newContinueSeriesKey!,
+ itemId: actualNextKey,
title: title,
author: author,
- coverUrl: getCoverUrl(newContinueSeriesKey),
+ coverUrl: getCoverUrl(actualNextKey),
totalDuration: duration,
chapters: chapters,
);
@@ -2095,8 +2129,12 @@ class LibraryProvider extends ChangeNotifier {
// then the server refresh still runs in the background when online.
// Skip when user manually marks an item finished (not natural playback completion).
if (!skipAutoAdvance) {
- PlayerSettings.getQueueMode().then((mode) {
- debugPrint('[AutoAdvance] queueMode=$mode for finished item $itemId');
+ final isPodcast = itemId.length > 36;
+ final modeFuture = isPodcast
+ ? PlayerSettings.getPodcastQueueMode()
+ : PlayerSettings.getBookQueueMode();
+ modeFuture.then((mode) {
+ debugPrint('[AutoAdvance] queueMode=$mode (${isPodcast ? 'podcast' : 'book'}) for finished item $itemId');
if (mode == 'manual') {
_manualQueueAdvance(itemId);
} else if (mode == 'auto_next') {
@@ -2134,8 +2172,9 @@ class LibraryProvider extends ChangeNotifier {
// Auto-delete for queue-based downloads (manual queue + queueAutoDownload)
if (DownloadService().isDownloaded(itemId)) {
+ final isPodcastItem = itemId.length > 36;
Future.wait([
- PlayerSettings.getQueueMode(),
+ isPodcastItem ? PlayerSettings.getPodcastQueueMode() : PlayerSettings.getBookQueueMode(),
PlayerSettings.getQueueAutoDownload(),
PlayerSettings.getRollingDownloadDeleteFinished(),
]).then((results) {
@@ -2172,7 +2211,7 @@ class LibraryProvider extends ChangeNotifier {
if (isCompound && !skipRefresh && _api != null && !isOffline) {
final showId = itemId.substring(0, 36);
final episodeId = itemId.substring(37);
- PlayerSettings.getQueueMode().then((queueMode) {
+ PlayerSettings.getPodcastQueueMode().then((queueMode) {
if (queueMode == 'auto_next') {
_addNextPodcastEpisode(showId, episodeId, itemId).then((_) {
if (_selectedLibraryId != null && !isOffline) {
@@ -2200,7 +2239,8 @@ class LibraryProvider extends ChangeNotifier {
_selectedLibraryId != null &&
!isOffline) {
// Brief delay so the server has time to populate continue-series
- Future.delayed(const Duration(milliseconds: 500), () {
+ Future.delayed(const Duration(milliseconds: 500), () async {
+ await _refreshProgress(); // refresh _progressMap so stale isFinished flags don't block auto-advance
refreshProgressShelves(force: true, reason: 'item-finished');
PlayerSettings.getWhenFinished().then((mode) {
if (mode == 'auto_remove') removeFromAbsorbing(itemId);
@@ -2222,6 +2262,7 @@ class LibraryProvider extends ChangeNotifier {
// Brief delay so the server has time to register the finished state
await Future.delayed(const Duration(milliseconds: 500));
try {
+ if (_api == null) return;
final fullItem = await _api!.getLibraryItem(showId);
if (fullItem == null) return;
final media = fullItem['media'] as Map<String, dynamic>? ?? {};
@@ -2229,11 +2270,16 @@ class LibraryProvider extends ChangeNotifier {
List<dynamic>.from(media['episodes'] as List<dynamic>? ?? []);
if (episodes.isEmpty) return;
- // Sort oldest-first (ascending publishedAt) so "next" = index + 1
+ // Check per-show advance direction
+ final prefs = await SharedPreferences.getInstance();
+ final advanceNewestFirst =
+ (prefs.getString('podcast_advance_dir_$showId') ?? 'oldest_first') == 'newest_first';
+
+ // Sort by publishedAt; direction determines which episode comes "next"
episodes.sort((a, b) {
final aTime = (a['publishedAt'] as num?)?.toInt() ?? 0;
final bTime = (b['publishedAt'] as num?)?.toInt() ?? 0;
- return aTime.compareTo(bTime);
+ return advanceNewestFirst ? bTime.compareTo(aTime) : aTime.compareTo(bTime);
});
final currentIdx = episodes.indexWhere(
@@ -2243,13 +2289,39 @@ class LibraryProvider extends ChangeNotifier {
);
if (currentIdx < 0 || currentIdx >= episodes.length - 1) return;
- final nextEp = episodes[currentIdx + 1] as Map<String, dynamic>;
- final nextEpId = nextEp['id'] as String?;
- if (nextEpId == null) return;
-
- final nextKey = '$showId-$nextEpId';
- if (_manualAbsorbRemoves.contains(nextKey)) return;
- if (_progressMap[nextKey]?['isFinished'] == true) return;
+ // Find the first unfinished episode after the current one (in sorted order)
+ Map<String, dynamic>? nextEp;
+ String? nextEpId;
+ String? nextKey;
+ int serverChecks = 0;
+ bool trustCache = false;
+ for (int i = currentIdx + 1; i < episodes.length; i++) {
+ final candidate = episodes[i] as Map<String, dynamic>;
+ final candidateId = candidate['id'] as String?;
+ if (candidateId == null) continue;
+ final candidateKey = '$showId-$candidateId';
+ final cachedFinished = _progressMap[candidateKey]?['isFinished'] == true;
+ if (cachedFinished) {
+ if (trustCache) continue;
+ // _progressMap can be stale; verify with server before skipping.
+ // Cap checks to avoid hammering the server for large backlogs.
+ final freshProg = await _api?.getEpisodeProgress(showId, candidateId);
+ serverChecks++;
+ if (freshProg?['isFinished'] == true) {
+ if (serverChecks >= 5) trustCache = true;
+ continue;
+ }
+ if (freshProg != null) {
+ _progressMap[candidateKey] = freshProg;
+ _localProgressOverrides.remove(candidateKey);
+ }
+ }
+ nextEp = candidate;
+ nextEpId = candidateId;
+ nextKey = candidateKey;
+ break;
+ }
+ if (nextEp == null || nextEpId == null || nextKey == null) return;
// Build a synthetic cache entry from the show data
final showData =
@@ -2263,6 +2335,7 @@ class LibraryProvider extends ChangeNotifier {
syntheticEntry['_absorbingKey'] = nextKey;
// Mark as manually added so pruning won't remove it (no progress yet)
+ _manualAbsorbRemoves.remove(nextKey);
_manualAbsorbAdds.add(nextKey);
_absorbingIdsAdd(nextKey, afterKey: finishedKey);
_absorbingItemCache[nextKey] = syntheticEntry;
@@ -2271,7 +2344,7 @@ class LibraryProvider extends ChangeNotifier {
// Auto-play the next episode if auto_next mode is enabled.
// Skip if local auto-advance already started playback.
- if ((await PlayerSettings.getQueueMode()) == 'auto_next' &&
+ if ((await PlayerSettings.getPodcastQueueMode()) == 'auto_next' &&
_api != null &&
!AudioPlayerService().isPlaying) {
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
@@ -2281,6 +2354,10 @@ class LibraryProvider extends ChangeNotifier {
(nextEp['audioFile'] as Map<String, dynamic>?)?['duration']
as double? ??
0;
+ // Resume from saved position if the episode was partially listened to.
+ final savedProgress = _progressMap[nextKey];
+ final startTime =
+ (savedProgress?['currentTime'] as num?)?.toDouble() ?? 0.0;
AudioPlayerService().playItem(
api: _api!,
itemId: showId,
@@ -2291,9 +2368,12 @@ class LibraryProvider extends ChangeNotifier {
chapters: [],
episodeId: nextEpId,
episodeTitle: nextEp['title'] as String?,
+ startTime: startTime,
);
}
- } catch (_) {}
+ } catch (e, st) {
+ debugPrint('[AutoAdvance] _addNextPodcastEpisode error: $e\n$st');
+ }
}
/// Manual queue auto-advance: scan absorbing list from after the finished
@@ -2430,7 +2510,7 @@ class LibraryProvider extends ChangeNotifier {
}
void _autoAdvanceOfflineBook(String finishedBookId) {
- PlayerSettings.getQueueMode().then((mode) {
+ PlayerSettings.getBookQueueMode().then((mode) {
if (mode != 'auto_next') return;
if (AudioPlayerService.wasNoisyPause) return;
@@ -2483,13 +2563,18 @@ class LibraryProvider extends ChangeNotifier {
}
void _autoAdvanceOfflinePodcast(String finishedKey) {
- PlayerSettings.getQueueMode().then((mode) {
+ PlayerSettings.getPodcastQueueMode().then((mode) async {
if (mode != 'auto_next') return;
if (AudioPlayerService.wasNoisyPause) return;
final showId = finishedKey.substring(0, 36);
final finishedEpId = finishedKey.substring(37);
+ // Check per-show advance direction
+ final prefs = await SharedPreferences.getInstance();
+ final advanceNewestFirst =
+ (prefs.getString('podcast_advance_dir_$showId') ?? 'oldest_first') == 'newest_first';
+
// Find all downloaded episodes for this show from the cache
final dl = DownloadService();
final episodes = <int, MapEntry<String, Map<String, dynamic>>>{};
@@ -2512,10 +2597,16 @@ class LibraryProvider extends ChangeNotifier {
}
if (finishedTimestamp == null || episodes.isEmpty) return;
- // Find the next episode after the finished one (ascending publishedAt)
+ // Find the next episode in the configured direction
final sorted = episodes.keys.toList()..sort();
- final nextTimestamp =
- sorted.where((t) => t > finishedTimestamp!).firstOrNull;
+ final int? nextTimestamp;
+ if (advanceNewestFirst) {
+ // newest-first: pick the most recent episode published before the current one
+ nextTimestamp = sorted.where((t) => t < finishedTimestamp!).lastOrNull;
+ } else {
+ // oldest-first: pick the oldest episode published after the current one
+ nextTimestamp = sorted.where((t) => t > finishedTimestamp!).firstOrNull;
+ }
if (nextTimestamp == null) return;
final nextEntry = episodes[nextTimestamp]!;
@@ -2638,7 +2729,10 @@ class LibraryProvider extends ChangeNotifier {
/// queue mode is active and queueAutoDownload is enabled.
void _checkQueueAutoDownloads(String playingKey) async {
if (_api == null || isOffline) return;
- final queueMode = await PlayerSettings.getQueueMode();
+ final isPodcastKey = playingKey.length > 36;
+ final queueMode = isPodcastKey
+ ? await PlayerSettings.getPodcastQueueMode()
+ : await PlayerSettings.getBookQueueMode();
if (queueMode != 'manual') return;
final enabled = await PlayerSettings.getQueueAutoDownload();
if (!enabled) return;
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 68bb45fc..4f7d3527 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -48,7 +48,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _resetSleepOnPause = false;
bool _sleepFadeOut = true;
int _shakeAddMinutes = 5;
- String _queueMode = 'off';
+ String _bookQueueMode = 'off';
+ String _podcastQueueMode = 'off';
+ // Returns the more restrictive of the two modes so the merged control
+ // never shows 'Auto' if one type is still 'off' or 'manual'.
+ String get _mergedQueueMode {
+ const order = ['off', 'manual', 'auto_next'];
+ final bi = order.indexOf(_bookQueueMode);
+ final pi = order.indexOf(_podcastQueueMode);
+ return order[(bi < pi ? bi : pi).clamp(0, 2)];
+ }
bool _queueAutoDownload = false;
bool _mergeAbsorbingLibraries = false;
int _maxConcurrentDownloads = 1;
@@ -126,7 +135,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getResetSleepOnPause(), // 11
PlayerSettings.getSleepFadeOut(), // 12
PlayerSettings.getShakeAddMinutes(), // 13
- PlayerSettings.getQueueMode(), // 14
+ PlayerSettings.getBookQueueMode(), // 14
PlayerSettings.getQueueAutoDownload(), // 15
PlayerSettings.getMergeAbsorbingLibraries(), // 16
PlayerSettings.getMaxConcurrentDownloads(), // 17
@@ -148,7 +157,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getDisableAudioFocus(), // 33
PlayerSettings.getAutoDownloadOnStream(), // 34
PlayerSettings.getColorSource(), // 35
- PlayerSettings.getStartScreen(), // 36
+ PlayerSettings.getStartScreen(), // 36
+ PlayerSettings.getPodcastQueueMode(), // 37
]);
final s = results[0] as AutoRewindSettings;
final speed = results[1] as double;
@@ -164,7 +174,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
final resetOnPause = results[11] as bool;
final sleepFade = results[12] as bool;
final shakeMins = results[13] as int;
- final queueMode = results[14] as String;
+ final bookQueueMode = results[14] as String;
final queueAutoDl = results[15] as bool;
final mergeLibs = results[16] as bool;
final maxConc = results[17] as int;
@@ -187,6 +197,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
final autoDlStream = results[34] as bool;
final colorSource = results[35] as String;
final startScreen = results[36] as int;
+ final podcastQueueMode = results[37] as String;
if (mounted) setState(() {
_rewindSettings = s;
_defaultSpeed = speed;
@@ -203,7 +214,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
_resetSleepOnPause = resetOnPause;
_sleepFadeOut = sleepFade;
_shakeAddMinutes = shakeMins;
- _queueMode = queueMode;
+ _bookQueueMode = bookQueueMode;
+ _podcastQueueMode = podcastQueueMode;
_queueAutoDownload = queueAutoDl;
_mergeAbsorbingLibraries = mergeLibs;
_maxConcurrentDownloads = maxConc;
@@ -798,28 +810,66 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: Icon(Icons.info_outline_rounded, size: 16, color: cs.onSurfaceVariant),
),
]),
- const SizedBox(height: 4),
- Text(
- _queueMode == 'off' ? 'Playback stops when current item finishes'
- : _queueMode == 'manual' ? 'Auto-plays next non-finished card in order'
- : 'Auto-absorbs next book in series or podcast episode',
- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
- ),
const SizedBox(height: 8),
- SizedBox(width: double.infinity, child: SegmentedButton<String>(
- segments: const [
- ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
- ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
- ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ // When libraries are merged, show a single unified control
+ if (_mergeAbsorbingLibraries) ...[
+ Text('Playback stops, manual queue, or auto-absorbs next item',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
+ ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
+ ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ ],
+ selected: {_mergedQueueMode},
+ onSelectionChanged: _loaded ? (s) {
+ setState(() {
+ _bookQueueMode = s.first;
+ _podcastQueueMode = s.first;
+ });
+ PlayerSettings.setBookQueueMode(s.first);
+ PlayerSettings.setPodcastQueueMode(s.first);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ ] else ...[
+ // Separate controls per type
+ Text('Books', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
+ ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
+ ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ ],
+ selected: {_bookQueueMode},
+ onSelectionChanged: _loaded ? (s) {
+ setState(() => _bookQueueMode = s.first);
+ PlayerSettings.setBookQueueMode(s.first);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ if (lib.libraries.any((l) => l['mediaType'] == 'podcast')) ...[
+ const SizedBox(height: 8),
+ Text('Podcasts', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
+ ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
+ ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ ],
+ selected: {_podcastQueueMode},
+ onSelectionChanged: _loaded ? (s) {
+ setState(() => _podcastQueueMode = s.first);
+ PlayerSettings.setPodcastQueueMode(s.first);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
],
- selected: {_queueMode},
- onSelectionChanged: _loaded ? (s) {
- setState(() => _queueMode = s.first);
- PlayerSettings.setQueueMode(s.first);
- } : null,
- style: const ButtonStyle(visualDensity: VisualDensity.compact),
- )),
- if (_queueMode == 'manual') ...[
+ ],
+ if (_bookQueueMode == 'manual' || _podcastQueueMode == 'manual') ...[
const SizedBox(height: 4),
SwitchListTile(
title: const Text('Auto-download queue'),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index fb371891..91cd3755 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -124,6 +124,18 @@ class PlayerSettings {
static Future<String> getQueueMode() => _get('queueMode', 'off');
static Future<void> setQueueMode(String value) => _set('queueMode', value);
+ static Future<String> getBookQueueMode() async {
+ final value = await ScopedPrefs.getString('bookQueueMode');
+ return value ?? await getQueueMode();
+ }
+ static Future<void> setBookQueueMode(String value) => _set('bookQueueMode', value);
+
+ static Future<String> getPodcastQueueMode() async {
+ final value = await ScopedPrefs.getString('podcastQueueMode');
+ return value ?? await getQueueMode();
+ }
+ static Future<void> setPodcastQueueMode(String value) => _set('podcastQueueMode', value);
+
/// One-time migration from the old boolean auto-play settings to queueMode.
static Future<void> migrateQueueMode() async {
if (await ScopedPrefs.containsKey('queueMode')) return;
@@ -132,6 +144,14 @@ class PlayerSettings {
await ScopedPrefs.setString('queueMode', (autoBook || autoPod) ? 'auto_next' : 'off');
}
+ /// One-time migration from the unified queueMode to per-type book/podcast modes.
+ static Future<void> migrateBookPodcastQueueMode() async {
+ if (await ScopedPrefs.containsKey('bookQueueMode')) return;
+ final existing = await getQueueMode();
+ await setBookQueueMode(existing);
+ await setPodcastQueueMode(existing);
+ }
+
// Legacy getters kept for backup service compatibility
static Future<bool> getAutoPlayNextBook() => _get('autoPlayNextBook', false);
static Future<void> setAutoPlayNextBook(bool value) => _set('autoPlayNextBook', value);
@@ -350,6 +370,16 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
);
AudioPlayerService? _service; // back-reference for auto-rewind
+ // Cached skip amounts for notification icon selection (updated when settings change)
+ int _cachedForwardSkip = 30;
+ int _cachedBackSkip = 10;
+
+ // Samsung (One UI) and OnePlus/Oppo/Realme (ColorOS) rearrange media session buttons.
+ static bool get _isReorderingOEM {
+ final m = ApiService.deviceManufacturer.toLowerCase();
+ return m == 'samsung' || m == 'oneplus' || m == 'oppo' || m == 'realme';
+ }
+
AudioPlayer get player => _player;
void bindService(AudioPlayerService service) => _service = service;
@@ -383,66 +413,47 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
}
- // OnePlus/Oppo/Realme (ColorOS) rearrange media session buttons.
- static bool get _isOnePlusFamily {
- final m = ApiService.deviceManufacturer.toLowerCase();
- return m == 'oneplus' || m == 'oppo' || m == 'realme';
- }
-
- // Speed presets for Android Auto cycling (matches in-app presets)
- static const _aaSpeedPresets = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5];
-
PlaybackState _transformEvent(PlaybackEvent event) {
final playPause = _player.playing ? MediaControl.pause : MediaControl.play;
- // Speed action first — Android Auto places the first custom action
- // inline on the left of transport controls. Use per-speed drawables
- // so the icon shows the actual speed value (7-segment style digits).
- final speed = _player.speed;
- final speedLabel = '${speed.toStringAsFixed(2)}x';
- String speedIcon;
- if ((speed - 0.75).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_075';
- } else if ((speed - 1.0).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_100';
- } else if ((speed - 1.25).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_125';
- } else if ((speed - 1.5).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_150';
- } else if ((speed - 1.75).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_175';
- } else if ((speed - 2.0).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_200';
- } else if ((speed - 2.5).abs() < 0.01) {
- speedIcon = 'drawable/ic_speed_250';
- } else {
- speedIcon = 'drawable/ic_speed_100'; // Safe fallback
- }
- final speedAction = MediaControl.custom(
- androidIcon: speedIcon,
- label: speedLabel,
- name: 'cycleSpeed',
+ final rewindControl = MediaControl(
+ androidIcon: 'drawable/ic_skip_back',
+ label: 'Back ${_cachedBackSkip}s',
+ action: MediaAction.rewind,
+ );
+ final fastForwardControl = MediaControl(
+ androidIcon: 'drawable/ic_skip_forward',
+ label: 'Forward ${_cachedForwardSkip}s',
+ action: MediaAction.fastForward,
+ );
+
+ // Chapter navigation controls — use widget icons (no tint attr, white fill)
+ final prevChapterControl = MediaControl.custom(
+ androidIcon: 'drawable/ic_widget_prev_chapter',
+ label: 'Previous chapter',
+ name: 'previousChapter',
+ );
+ final nextChapterControl = MediaControl.custom(
+ androidIcon: 'drawable/ic_widget_next_chapter',
+ label: 'Next chapter',
+ name: 'nextChapter',
);
- // Build the controls list. On most devices, AA places custom actions
- // in alternating slots outward from play/pause, giving the visual order
- // [speed][rw][play][ff] when transport comes first.
- //
- // OnePlus/Oppo/Realme (ColorOS) rearrange media buttons:
- // API < 33 — notification renders the entire row in reverse, so
- // send the mirror image.
- // API >= 33 — MediaSession custom-action slot placement differs,
- // so send controls in the desired visual order directly.
- // Desired visual order on OnePlus: speed | rw | play/pause | ff
+ // Samsung (One UI) rearranges our 5-button array: it displays indices
+ // [3, 0, 2, 1, 4] from our input. Send the inverse permutation so the
+ // visual result is prevChapter | skipBack | play/pause | skipForward | nextChapter.
+ // Samsung-specific input: [rewind, fastForward, playPause, prevChapter, nextChapter]
+ // → Samsung displays: [fastForward→pos0… wait, inverse] → correct visual order.
final List<MediaControl> controls;
- if (_isOnePlusFamily) {
- if (ApiService.deviceSdkInt >= 33) {
- controls = [speedAction, MediaControl.rewind, playPause, MediaControl.fastForward];
- } else {
- controls = [MediaControl.fastForward, playPause, MediaControl.rewind, speedAction];
- }
+ final List<int> compactIndices;
+ if (_isReorderingOEM) {
+ controls = [rewindControl, fastForwardControl, playPause, prevChapterControl, nextChapterControl];
+ // Compact: rewind(0), play/pause(2), fastForward(1)
+ compactIndices = const [0, 2, 1];
} else {
- controls = [MediaControl.rewind, playPause, MediaControl.fastForward, speedAction];
+ // Standard: prevChapter | skipBack | play/pause | skipForward | nextChapter
+ controls = [prevChapterControl, rewindControl, playPause, fastForwardControl, nextChapterControl];
+ compactIndices = const [1, 2, 3];
}
return PlaybackState(
@@ -453,9 +464,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
MediaAction.seekBackward,
MediaAction.skipToQueueItem,
},
- // Notification compact: indices into nativeActions (custom actions are
- // separated out on the platform side, so standard controls are always 0-2).
- androidCompactActionIndices: const [0, 1, 2],
+ androidCompactActionIndices: compactIndices,
processingState: const {
ProcessingState.idle: AudioProcessingState.idle,
ProcessingState.loading: AudioProcessingState.loading,
@@ -685,17 +694,6 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
case 'previousChapter':
if (_service != null) await _service!.skipToPreviousChapter();
break;
- case 'cycleSpeed':
- if (_service != null) {
- final current = _service!.speed;
- // Find next preset above current speed, or wrap to first
- final next = _aaSpeedPresets.cast<double>().firstWhere(
- (s) => s > current + 0.01,
- orElse: () => _aaSpeedPresets.first,
- );
- await _service!.setSpeed(next);
- }
- break;
}
}
@@ -989,6 +987,19 @@ class AudioPlayerService extends ChangeNotifier {
_handler?.refreshPlaybackState();
}
});
+ // Update cached skip amounts so notification icons stay in sync
+ PlayerSettings.getForwardSkip().then((v) {
+ if (_handler != null && v != _handler!._cachedForwardSkip) {
+ _handler!._cachedForwardSkip = v;
+ _handler!.refreshPlaybackState();
+ }
+ });
+ PlayerSettings.getBackSkip().then((v) {
+ if (_handler != null && v != _handler!._cachedBackSkip) {
+ _handler!._cachedBackSkip = v;
+ _handler!.refreshPlaybackState();
+ }
+ });
}
/// The last seek target in seconds (absolute book position).
@@ -1179,6 +1190,9 @@ class AudioPlayerService extends ChangeNotifier {
);
// Bind service so handler routes play/pause through service (for auto-rewind)
_handler!.bindService(_instance);
+ // Initialize cached skip amounts so notification icons show the correct values
+ _handler!._cachedForwardSkip = fwdSkip;
+ _handler!._cachedBackSkip = backSkip;
debugPrint('[Player] AudioService initialized');
// Configure streaming cache if enabled
final cacheSizeMb = await PlayerSettings.getStreamingCacheSizeMb();
@@ -1274,7 +1288,20 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
- await session.configure(const AudioSessionConfiguration.speech());
+ await session.configure(const AudioSessionConfiguration(
+ // iOS: playback category with spokenAudio mode (auto-pauses for other audio)
+ avAudioSessionCategory: AVAudioSessionCategory.playback,
+ avAudioSessionMode: AVAudioSessionMode.spokenAudio,
+ avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.duckOthers,
+ // Android: use music content type to avoid speech-specific volume normalization
+ // that makes audiobooks quieter than music apps on Pixel and other devices
+ androidAudioAttributes: AndroidAudioAttributes(
+ contentType: AndroidAudioContentType.music,
+ usage: AndroidAudioUsage.media,
+ ),
+ androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
+ androidWillPauseWhenDucked: true,
+ ));
await session.setActive(true);
_interruptSub?.cancel();
@@ -1660,6 +1687,7 @@ class AudioPlayerService extends ChangeNotifier {
if (startTime > 0) {
await _seekAbsolute(startTime);
}
+ clearSeekTarget(); // Seek done; let position events flow immediately
_subscribeTrackIndex();
final initChapter = _initChapterInfo(startTime);
@@ -1779,6 +1807,7 @@ class AudioPlayerService extends ChangeNotifier {
if (startTime > 0) {
await _seekAbsolute(startTime);
}
+ clearSeekTarget(); // Seek done; let position events flow immediately
_subscribeTrackIndex();
final initChapter = _initChapterInfo(startTime);
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 4e9d61e5..0202b0fd 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -18,6 +18,8 @@ class BackupService {
'defaultSpeed': await PlayerSettings.getDefaultSpeed(),
'wifiOnlyDownloads': await PlayerSettings.getWifiOnlyDownloads(),
'queueMode': await PlayerSettings.getQueueMode(),
+ 'bookQueueMode': await PlayerSettings.getBookQueueMode(),
+ 'podcastQueueMode': await PlayerSettings.getPodcastQueueMode(),
// Legacy keys for backward compat with older app versions
'autoPlayNextBook': (await PlayerSettings.getQueueMode()) == 'auto_next',
'autoPlayNextPodcast': (await PlayerSettings.getQueueMode()) == 'auto_next',
@@ -188,6 +190,8 @@ class BackupService {
final autoPod = s['autoPlayNextPodcast'] as bool? ?? false;
PlayerSettings.setQueueMode((autoBook || autoPod) ? 'auto_next' : 'off');
}
+ if (s['bookQueueMode'] != null) PlayerSettings.setBookQueueMode(s['bookQueueMode'] as String);
+ if (s['podcastQueueMode'] != null) PlayerSettings.setPodcastQueueMode(s['podcastQueueMode'] as String);
if (s['whenFinished'] != null) PlayerSettings.setWhenFinished(s['whenFinished'] as String);
if (s['showBookSlider'] != null) PlayerSettings.setShowBookSlider(s['showBookSlider'] as bool);
if (s['speedAdjustedTime'] != null) PlayerSettings.setSpeedAdjustedTime(s['speedAdjustedTime'] as bool);
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index 3f30c1a5..0429038a 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -57,6 +57,9 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
bool _isDownloadingAll = false;
bool _autoDownloadEnabled = false;
bool _newestFirst = true;
+ bool _hideFinished = false;
+ String _podcastAdvanceDir = 'oldest_first'; // 'oldest_first' or 'newest_first'
+ bool _podcastAutoAdvanceOn = false;
String get _itemId => widget.podcastItem['id'] as String? ?? '';
@@ -74,6 +77,8 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
void initState() {
super.initState();
_loadSortOrder();
+ _loadHideFinished();
+ _loadAutoAdvanceDir();
_loadEpisodes();
_loadAutoDownloadState();
}
@@ -140,6 +145,35 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
return sorted;
}
+ void _loadHideFinished() async {
+ final prefs = await SharedPreferences.getInstance();
+ final saved = prefs.getBool('podcast_hide_finished_$_itemId');
+ if (saved != null && mounted) setState(() => _hideFinished = saved);
+ }
+
+ void _loadAutoAdvanceDir() async {
+ final prefs = await SharedPreferences.getInstance();
+ final saved = prefs.getString('podcast_advance_dir_$_itemId');
+ if (saved != null && mounted) setState(() => _podcastAdvanceDir = saved);
+ final mode = await PlayerSettings.getPodcastQueueMode();
+ if (mounted) setState(() => _podcastAutoAdvanceOn = mode == 'auto_next');
+ }
+
+ void _toggleAutoAdvanceDir() {
+ final newDir = _podcastAdvanceDir == 'oldest_first' ? 'newest_first' : 'oldest_first';
+ setState(() => _podcastAdvanceDir = newDir);
+ SharedPreferences.getInstance().then((prefs) {
+ prefs.setString('podcast_advance_dir_$_itemId', newDir);
+ });
+ }
+
+ void _toggleHideFinished() {
+ setState(() => _hideFinished = !_hideFinished);
+ SharedPreferences.getInstance().then((prefs) {
+ prefs.setBool('podcast_hide_finished_$_itemId', _hideFinished);
+ });
+ }
+
void _toggleSortOrder() {
setState(() {
_newestFirst = !_newestFirst;
@@ -320,6 +354,48 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
await lib.toggleRollingDownload(_itemId);
setState(() => _autoDownloadEnabled = lib.isRollingDownloadEnabled(_itemId));
}),
+ _podMoreItem(cs,
+ _hideFinished ? Icons.visibility_rounded : Icons.visibility_off_rounded,
+ _hideFinished ? 'Show Finished Episodes' : 'Hide Finished Episodes',
+ onTap: () { Navigator.pop(ctx); _toggleHideFinished(); }),
+ if (_podcastAutoAdvanceOn)
+ StatefulBuilder(builder: (ctx, setLocalState) {
+ final reversed = _podcastAdvanceDir == 'newest_first';
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Container(
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.1)),
+ ),
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+ child: Row(children: [
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text('Reverse play order', style: TextStyle(color: cs.onSurface, fontSize: 13, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 2),
+ Text(
+ reversed ? 'Plays newer to older episodes' : 'Plays older to newer episodes',
+ style: TextStyle(color: cs.onSurfaceVariant, fontSize: 11.5),
+ ),
+ ])),
+ SizedBox(
+ height: 28,
+ child: FittedBox(
+ fit: BoxFit.contain,
+ child: Switch(
+ value: reversed,
+ onChanged: (v) {
+ _toggleAutoAdvanceDir();
+ setLocalState(() {});
+ },
+ ),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }),
]),
),
);
@@ -474,22 +550,31 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
],
),
)
- : ListView.builder(
- controller: widget.scrollController,
- padding: EdgeInsets.only(bottom: 32 + MediaQuery.of(context).viewPadding.bottom),
- itemCount: _episodes.length,
- itemBuilder: (context, index) {
- final ep = _episodes[index] as Map<String, dynamic>;
- return _EpisodeRow(
- episode: ep,
- podcastItem: widget.podcastItem,
- itemId: _itemId,
- podcastTitle: _title,
- onPlay: () => _playEpisode(ep),
- onDownload: () => _downloadEpisode(ep),
- );
- },
- ),
+ : Builder(builder: (context) {
+ final visibleEpisodes = _hideFinished
+ ? _episodes.where((e) {
+ final ep = e as Map<String, dynamic>;
+ final epId = ep['id'] as String? ?? '';
+ return lib.getEpisodeProgressData(_itemId, epId)?['isFinished'] != true;
+ }).toList()
+ : _episodes;
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.only(bottom: 32 + MediaQuery.of(context).viewPadding.bottom),
+ itemCount: visibleEpisodes.length,
+ itemBuilder: (context, index) {
+ final ep = visibleEpisodes[index] as Map<String, dynamic>;
+ return _EpisodeRow(
+ episode: ep,
+ podcastItem: widget.podcastItem,
+ itemId: _itemId,
+ podcastTitle: _title,
+ onPlay: () => _playEpisode(ep),
+ onDownload: () => _downloadEpisode(ep),
+ );
+ },
+ );
+ }),
),
]),
]),