Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix podcast casting, download queue, and casting UX

Nathan Poulsonfc81b4ad66a8
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index 31d0a98d..4f4ca2be 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
+import '../services/chromecast_service.dart';
import '../services/download_service.dart';
import '../services/scoped_prefs.dart';
import '../widgets/absorb_page_header.dart';
@@ -27,10 +28,13 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
final _player = AudioPlayerService();
final _pageController = PageController(viewportFraction: 0.92);
+ final _cast = ChromecastService();
+
@override
void initState() {
super.initState();
_player.addListener(_rebuild);
+ _cast.addListener(_rebuild);
_restoreLastFinished();
}
@@ -44,6 +48,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
@override
void dispose() {
_player.removeListener(_rebuild);
+ _cast.removeListener(_rebuild);
_pageController.dispose();
super.dispose();
}
@@ -51,6 +56,9 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
String? _lastPlayingId;
String? _lastPlayingEpisodeId;
String? _lastFinishedId;
+ bool _wasCasting = false;
+ String? _lastCastItemId;
+ String? _lastCastEpisodeId;
bool _isSyncing = false;
// When true, _getAbsorbingBooks keeps the original list order (no move-to-front).
// Used during the slide-to-front animation so the user sees their book smoothly
@@ -94,6 +102,23 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
ScopedPrefs.setString('absorbing_last_finished', finishedKey);
}
}
+
+ // Track cast state — when casting stops/disconnects, keep that card at front
+ final nowCasting = _cast.isCasting;
+ if (nowCasting) {
+ _lastCastItemId = _cast.castingItemId;
+ _lastCastEpisodeId = _cast.castingEpisodeId;
+ } else if (_wasCasting && _lastCastItemId != null) {
+ final finishedKey = _lastCastEpisodeId != null
+ ? '$_lastCastItemId-$_lastCastEpisodeId'
+ : _lastCastItemId!;
+ _lastFinishedId = finishedKey;
+ ScopedPrefs.setString('absorbing_last_finished', finishedKey);
+ _lastCastItemId = null;
+ _lastCastEpisodeId = null;
+ }
+ _wasCasting = nowCasting;
+
setState(() {});
}
@@ -245,42 +270,66 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
}
}
- // If the currently playing item isn't in the list, add it at the front.
+ // If the currently playing/casting item isn't in the list, add it at the front.
// For podcast episodes, match by compound key.
// Skip if the playing item belongs to a different library type.
final isPod = lib.isPodcastLibrary;
+
+ // Determine active item — local player takes priority, then Chromecast
+ String? activeId;
+ String? activeEpId;
+ String? activeTitle;
+ String? activeAuthor;
+ String? activeEpTitle;
+ double activeDuration = 0;
+ List<dynamic> activeChapters = [];
+
if (_player.hasBook && _player.currentItemId != null) {
- final playingId = _player.currentItemId!;
- final playingEpId = _player.currentEpisodeId;
- final playingIsPodcast = playingEpId != null;
- // Only show if the playing item matches the current library type
- if (playingIsPodcast == isPod) {
- final playingKey = playingEpId != null ? '$playingId-$playingEpId' : playingId;
-
- final existingIdx = items.indexWhere((b) => _absorbingKey(b) == playingKey);
+ activeId = _player.currentItemId;
+ activeEpId = _player.currentEpisodeId;
+ activeTitle = _player.currentTitle;
+ activeAuthor = _player.currentAuthor;
+ activeEpTitle = _player.currentEpisodeTitle;
+ activeDuration = _player.totalDuration;
+ activeChapters = _player.chapters;
+ } else if (_cast.isCasting && _cast.castingItemId != null) {
+ activeId = _cast.castingItemId;
+ activeTitle = _cast.castingTitle;
+ activeAuthor = _cast.castingAuthor;
+ activeDuration = _cast.castingDuration;
+ activeChapters = _cast.castingChapters;
+ }
+
+ if (activeId != null) {
+ final activeIsPodcast = activeEpId != null;
+ // Only show if the active item matches the current library type
+ if (activeIsPodcast == isPod) {
+ final activeKey = activeEpId != null ? '$activeId-$activeEpId' : activeId;
+
+ final existingIdx = items.indexWhere((b) => _absorbingKey(b) == activeKey);
if (!_suppressReorder && existingIdx > 0) {
final item = items.removeAt(existingIdx);
items.insert(0, item);
} else if (existingIdx < 0) {
- // Synthesize entry for the currently playing item
+ // Synthesize entry for the currently active item
final entry = <String, dynamic>{
- 'id': playingId,
+ 'id': activeId,
'media': {
'metadata': {
- 'title': _player.currentTitle,
- 'authorName': _player.currentAuthor,
+ 'title': activeTitle,
+ 'authorName': activeAuthor,
},
- 'duration': _player.totalDuration,
- 'chapters': _player.chapters,
+ 'duration': activeDuration,
+ 'chapters': activeChapters,
},
};
- if (playingEpId != null) {
+ if (activeEpId != null) {
entry['recentEpisode'] = {
- 'id': playingEpId,
- 'title': _player.currentEpisodeTitle ?? _player.currentTitle,
- 'duration': _player.totalDuration,
+ 'id': activeEpId,
+ 'title': activeEpTitle ?? activeTitle,
+ 'duration': activeDuration,
};
- entry['_absorbingKey'] = playingKey;
+ entry['_absorbingKey'] = activeKey;
}
items.insert(0, entry);
}
diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dart
index 0cc21ca8..d101df4c 100644
--- a/lib/services/chromecast_service.dart
+++ b/lib/services/chromecast_service.dart
@@ -22,7 +22,7 @@ class ChromecastService extends ChangeNotifier {
bool get isCasting => isConnected && _playbackState != CastPlaybackState.idle;
bool get isPlaying => _playbackState == CastPlaybackState.playing;
- String? _castingItemId, _castingTitle, _castingAuthor, _castingCoverUrl;
+ String? _castingItemId, _castingEpisodeId, _castingTitle, _castingAuthor, _castingCoverUrl;
double _castingDuration = 0;
List<dynamic> _castingChapters = [];
ApiService? _api;
@@ -30,6 +30,7 @@ class ChromecastService extends ChangeNotifier {
String? _connectedDeviceName;
String? get castingItemId => _castingItemId;
+ String? get castingEpisodeId => _castingEpisodeId;
String? get castingTitle => _castingTitle;
String? get castingAuthor => _castingAuthor;
String? get castingCoverUrl => _castingCoverUrl;
@@ -106,7 +107,7 @@ class ChromecastService extends ChangeNotifier {
_connectionState = CastConnectionState.disconnected;
_playbackState = CastPlaybackState.idle;
_connectedDeviceName = null;
- _castingItemId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
+ _castingItemId = _castingEpisodeId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
_castingDuration = 0;
_castingChapters = [];
_castPosition = Duration.zero;
@@ -190,6 +191,7 @@ class ChromecastService extends ChangeNotifier {
required String title, required String author,
required String? coverUrl, required double totalDuration,
required List<dynamic> chapters, double startTime = 0,
+ String? episodeId,
}) async {
debugPrint('[Cast] >>> castItem() — "$title" (id: $itemId)');
debugPrint('[Cast] isConnected=$isConnected, connectionState=$_connectionState');
@@ -206,6 +208,7 @@ class ChromecastService extends ChangeNotifier {
_api = api;
_castingItemId = itemId;
+ _castingEpisodeId = episodeId;
_castingTitle = title;
_castingAuthor = author;
_castingCoverUrl = coverUrl;
@@ -219,8 +222,10 @@ class ChromecastService extends ChangeNotifier {
if (localPos > 0 && startTime == 0) startTime = localPos;
try {
- debugPrint('[Cast] Starting playback session with server...');
- final sessionData = await api.startPlaybackSession(itemId);
+ debugPrint('[Cast] Starting playback session with server... (episodeId: $episodeId)');
+ final sessionData = episodeId != null
+ ? await api.startEpisodePlaybackSession(itemId, episodeId)
+ : await api.startPlaybackSession(itemId);
if (sessionData == null) {
debugPrint('[Cast] Server returned null session — aborting');
_playbackState = CastPlaybackState.idle; notifyListeners(); return false;
@@ -247,14 +252,32 @@ class ChromecastService extends ChangeNotifier {
final sid = sessionData['id'] as String?;
if (sid != null) try { await api.closePlaybackSession(sid); } catch (_) {}
- debugPrint('[Cast] Starting from position: ${startTime}s');
+ // Load per-book speed (or global default)
+ final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
+ final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
+ _castSpeed = speed;
+
+ debugPrint('[Cast] Starting from position: ${startTime}s, speed: ${speed}x');
+ bool loaded;
if (audioTracks.length == 1) {
debugPrint('[Cast] Single track mode');
- return _loadSingleTrack(api, audioTracks.first, title, author, coverUrl, totalDuration, startTime);
+ loaded = await _loadSingleTrack(api, audioTracks.first, title, author, coverUrl, totalDuration, startTime);
} else {
debugPrint('[Cast] Multi-track queue mode (${audioTracks.length} tracks)');
- return _loadMultiTrackQueue(api, audioTracks, title, author, coverUrl, totalDuration, chapters, startTime);
+ loaded = await _loadMultiTrackQueue(api, audioTracks, title, author, coverUrl, totalDuration, chapters, startTime);
+ }
+
+ // Apply playback speed after media is loaded
+ if (loaded && (speed - 1.0).abs() > 0.01) {
+ await Future.delayed(const Duration(milliseconds: 300));
+ try {
+ await GoogleCastRemoteMediaClient.instance.setPlaybackRate(speed);
+ debugPrint('[Cast] Applied book speed: ${speed}x');
+ } catch (e) {
+ debugPrint('[Cast] setPlaybackRate error: $e');
+ }
}
+ return loaded;
} catch (e, st) {
debugPrint('[Cast] castItem error: $e\n$st');
_playbackState = CastPlaybackState.idle; notifyListeners(); return false;
@@ -449,7 +472,7 @@ class ChromecastService extends ChangeNotifier {
await _syncProgressToServer();
try { await GoogleCastRemoteMediaClient.instance.stop(); } catch (_) {}
_playbackState = CastPlaybackState.idle;
- _castingItemId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
+ _castingItemId = _castingEpisodeId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
_castingDuration = 0; _castingChapters = [];
notifyListeners();
}
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 4161d644..0da53a42 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -92,6 +92,24 @@ class DownloadInfo {
}
}
+class _QueuedDownload {
+ final ApiService api;
+ final String itemId;
+ final String title;
+ final String? author;
+ final String? coverUrl;
+ final String? episodeId;
+
+ _QueuedDownload({
+ required this.api,
+ required this.itemId,
+ required this.title,
+ this.author,
+ this.coverUrl,
+ this.episodeId,
+ });
+}
+
class DownloadService extends ChangeNotifier {
static final DownloadService _instance = DownloadService._();
factory DownloadService() => _instance;
@@ -103,6 +121,10 @@ class DownloadService extends ChangeNotifier {
bool _cancelled = false;
String? _customDownloadPath;
+ /// Queue of pending download requests.
+ final List<_QueuedDownload> _queue = [];
+ bool _processingQueue = false;
+
/// The current download directory path, or null if using default.
String? get customDownloadPath => _customDownloadPath;
@@ -360,6 +382,8 @@ class DownloadService extends ChangeNotifier {
}) async {
if (_activeDownloadId == itemId) return null;
if (isDownloaded(itemId)) return null;
+ // Already queued — don't duplicate
+ if (_queue.any((q) => q.itemId == itemId)) return null;
// Check wifi-only setting
final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
@@ -370,6 +394,61 @@ class DownloadService extends ChangeNotifier {
}
}
+ // If another download is active, queue this one
+ if (_activeDownloadId != null) {
+ _queue.add(_QueuedDownload(
+ api: api,
+ itemId: itemId,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ episodeId: episodeId,
+ ));
+ _downloads[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.downloading,
+ progress: 0,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ );
+ notifyListeners();
+ // Ensure queue processor is running
+ if (!_processingQueue) _processQueue();
+ return null;
+ }
+
+ await _executeDownload(
+ api: api, itemId: itemId, title: title,
+ author: author, coverUrl: coverUrl, episodeId: episodeId,
+ );
+ // Process any queued downloads
+ if (_queue.isNotEmpty && !_processingQueue) _processQueue();
+ return null;
+ }
+
+ Future<void> _processQueue() async {
+ _processingQueue = true;
+ while (_queue.isNotEmpty) {
+ final next = _queue.removeAt(0);
+ // Skip if cancelled/removed while waiting
+ if (isDownloaded(next.itemId)) continue;
+ await _executeDownload(
+ api: next.api, itemId: next.itemId, title: next.title,
+ author: next.author, coverUrl: next.coverUrl, episodeId: next.episodeId,
+ );
+ }
+ _processingQueue = false;
+ }
+
+ Future<void> _executeDownload({
+ required ApiService api,
+ required String itemId,
+ required String title,
+ String? author,
+ String? coverUrl,
+ String? episodeId,
+ }) async {
_activeDownloadId = itemId;
_cancelled = false;
_downloads[itemId] = DownloadInfo(
@@ -610,6 +689,8 @@ class DownloadService extends ChangeNotifier {
_activeDownloadId = null;
DownloadNotificationService().dismiss();
}
+ // Remove from queue if it was waiting
+ _queue.removeWhere((q) => q.itemId == itemId);
_downloads.remove(itemId);
notifyListeners();
}
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index 6b835b1d..0beb6553 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -407,7 +407,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
final coverSize = coverWidth < constraints.maxHeight
? coverWidth
: constraints.maxHeight;
- final isDownloaded = DownloadService().isDownloaded(_itemId);
+ final dlKey = _episodeId != null ? '$_itemId-$_episodeId' : _itemId;
+ final isDownloaded = DownloadService().isDownloaded(dlKey);
final castService = ChromecastService();
final isCastingThis = castService.isCasting && castService.castingItemId == _itemId;
return GestureDetector(
@@ -613,26 +614,47 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
)),
]),
const SizedBox(height: 8),
- // More menu: Details + History (centered below buttons)
+ // More menu / Cast controls (centered below buttons)
Center(
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: () => _showMoreMenu(context, accent, tt),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
- decoration: BoxDecoration(
- color: cs.onSurface.withValues(alpha: 0.08),
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.more_horiz_rounded, size: 18, color: cs.onSurface.withValues(alpha: 0.54)),
- const SizedBox(width: 4),
- Text('More', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: cs.onSurface.withValues(alpha: 0.54))),
- ],
- ),
- ),
+ child: ListenableBuilder(
+ listenable: ChromecastService(),
+ builder: (context, _) {
+ final castActive = ChromecastService().isCasting;
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: castActive
+ ? () => showModalBottomSheet(
+ context: context,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ builder: (_) => const CastControlSheet(),
+ )
+ : () => _showMoreMenu(context, accent, tt),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
+ decoration: BoxDecoration(
+ color: castActive ? accent.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: castActive
+ ? [
+ Icon(Icons.cast_connected_rounded, size: 18, color: accent),
+ const SizedBox(width: 4),
+ Text('Casting', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: accent)),
+ ]
+ : [
+ Icon(Icons.more_horiz_rounded, size: 18, color: cs.onSurface.withValues(alpha: 0.54)),
+ const SizedBox(width: 4),
+ Text('More', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: cs.onSurface.withValues(alpha: 0.54))),
+ ],
+ ),
+ ),
+ );
+ },
),
),
const SizedBox(height: 8),
@@ -973,12 +995,14 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
cast.castItem(
api: api, itemId: _itemId, title: _title, author: _author,
coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,
+ episodeId: _episodeId ?? widget.player.currentEpisodeId,
);
}
} else {
showCastDevicePicker(context,
api: api, itemId: _itemId, title: _title, author: _author,
- coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters);
+ coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,
+ episodeId: _episodeId ?? widget.player.currentEpisodeId);
}
},
);
diff --git a/lib/widgets/chromecast_button.dart b/lib/widgets/chromecast_button.dart
index 12232d1f..ed33ff69 100644
--- a/lib/widgets/chromecast_button.dart
+++ b/lib/widgets/chromecast_button.dart
@@ -17,6 +17,7 @@ void showCastDevicePicker(
String? coverUrl,
double? totalDuration,
List<dynamic>? chapters,
+ String? episodeId,
}) {
final cast = ChromecastService();
showModalBottomSheet(
@@ -71,7 +72,7 @@ void showCastDevicePicker(
_waitAndCast(cast, api: api, itemId: itemId,
title: title ?? '', author: author ?? '',
coverUrl: coverUrl, totalDuration: totalDuration ?? 0,
- chapters: chapters ?? []);
+ chapters: chapters ?? [], episodeId: episodeId);
}
},
);
@@ -98,10 +99,12 @@ void _waitAndCast(
required String? coverUrl,
required double totalDuration,
required List<dynamic> chapters,
+ String? episodeId,
}) {
if (cast.isConnected) {
cast.castItem(api: api, itemId: itemId, title: title, author: author,
- coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters);
+ coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters,
+ episodeId: episodeId);
return;
}
@@ -118,7 +121,8 @@ void _waitAndCast(
cleanup();
Future.delayed(const Duration(milliseconds: 500), () {
cast.castItem(api: api, itemId: itemId, title: title, author: author,
- coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters);
+ coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters,
+ episodeId: episodeId);
});
}
});
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index b23cf897..7658aab6 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -134,6 +134,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
coverUrl: coverUrl,
totalDuration: duration,
chapters: [],
+ episodeId: episodeId,
);
if (mounted) Navigator.pop(context);
return;
@@ -512,6 +513,7 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {
await cast.castItem(
api: api, itemId: _itemId, title: _episodeTitle, author: _showTitle,
coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: [],
+ episodeId: _episodeId,
);
if (mounted) Navigator.pop(context);
return;
diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dart
index 645ec111..971c3429 100644
--- a/lib/widgets/expanded_card.dart
+++ b/lib/widgets/expanded_card.dart
@@ -514,7 +514,8 @@ class _ExpandedCardState extends State<ExpandedCard> {
builder: (context, constraints) {
final coverWidth = constraints.maxWidth * 0.90;
final coverSize = coverWidth < constraints.maxHeight ? coverWidth : constraints.maxHeight;
- final isDownloaded = DownloadService().isDownloaded(_itemId);
+ final dlKey = _episodeId != null ? '$_itemId-$_episodeId' : _itemId;
+ final isDownloaded = DownloadService().isDownloaded(dlKey);
final castService = ChromecastService();
final isCastingThis = castService.isCasting && castService.castingItemId == _itemId;
return Container(
@@ -1111,12 +1112,14 @@ class _ExpandedCardState extends State<ExpandedCard> {
cast.castItem(
api: api, itemId: _itemId, title: _title, author: _author,
coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,
+ episodeId: _episodeId ?? widget.player.currentEpisodeId,
);
}
} else {
showCastDevicePicker(context,
api: api, itemId: _itemId, title: _title, author: _author,
- coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters);
+ coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,
+ episodeId: _episodeId ?? widget.player.currentEpisodeId);
}
},
);