A cross platform Audiobookshelf client for Android and iOS
Dart
Sync all player controls with Chromecast and improve cast reliability
Nathan Poulson52a6b9759ea7
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dartindex c73ad4e6..fcbd8513 100644--- a/lib/screens/app_shell.dart+++ b/lib/screens/app_shell.dart@@ -1,9 +1,11 @@+import 'dart:async';import 'dart:math' as math;import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:provider/provider.dart';import '../providers/library_provider.dart';import '../services/audio_player_service.dart';+import '../services/chromecast_service.dart';import '../services/sleep_timer_service.dart';import '../services/android_auto_service.dart';import '../widgets/expanded_card.dart';@@ -47,6 +49,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {bool _wasPlaying = false;String? _lastItemId;bool _expandedIsOpen = false;+ Timer? _castDisconnectTimer;void _switchToAbsorbing() {if (mounted) {@@ -167,9 +170,23 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {if (state == AppLifecycleState.resumed) {+ _castDisconnectTimer?.cancel();+ _castDisconnectTimer = null;_refreshData();// Check auto sleep in case we resumed into the windowSleepTimerService().checkAutoSleep();+ } else if (state == AppLifecycleState.paused) {+ // Disconnect cast if app doesn't resume (e.g. swiped away).+ // detached doesn't fire reliably on Android swipe-away.+ final cast = ChromecastService();+ if (cast.isConnected) {+ _castDisconnectTimer = Timer(const Duration(seconds: 3), () {+ cast.disconnect();+ });+ }+ } else if (state == AppLifecycleState.detached) {+ final cast = ChromecastService();+ if (cast.isConnected) cast.disconnect();}}diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dartindex d101df4c..7f2a16f1 100644--- a/lib/services/chromecast_service.dart+++ b/lib/services/chromecast_service.dart@@ -430,7 +430,12 @@ class ChromecastService extends ChangeNotifier {// ── Controls ──Future<void> play() async { if (isConnected) try { await GoogleCastRemoteMediaClient.instance.play(); } catch (_) {} }- Future<void> pause() async { if (isConnected) try { await GoogleCastRemoteMediaClient.instance.pause(); _saveProgressLocal(); _syncProgressToServer(); } catch (_) {} }+ Future<void> pause() async {+ if (!isConnected) return;+ try { await GoogleCastRemoteMediaClient.instance.pause(); } catch (_) {}+ await _saveProgressLocal();+ await _syncProgressToServer();+ }Future<void> togglePlayPause() async { isPlaying ? await pause() : await play(); }Future<void> seekTo(Duration position) async {@@ -488,7 +493,22 @@ class ChromecastService extends ChangeNotifier {Future<void> _syncProgressToServer() async {if (_castingItemId == null || _api == null) return;- try { await _progressSync.syncToServer(api: _api!, itemId: _castingItemId!); } catch (_) {}+ final ct = _castPosition.inMilliseconds / 1000.0;+ if (ct <= 0) return;+ try {+ final sessionData = _castingEpisodeId != null+ ? await _api!.startEpisodePlaybackSession(_castingItemId!, _castingEpisodeId!)+ : await _api!.startPlaybackSession(_castingItemId!);+ if (sessionData != null) {+ final sid = sessionData['id'] as String?;+ if (sid != null) {+ await _api!.syncPlaybackSession(sid, currentTime: ct, duration: _castingDuration);+ await _api!.closePlaybackSession(sid);+ }+ }+ } catch (e) {+ debugPrint('[Cast] Server sync error: $e');+ }}// ── Chapters ──diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dartindex 46fa3b2d..14147d16 100644--- a/lib/services/sleep_timer_service.dart+++ b/lib/services/sleep_timer_service.dart@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';import 'package:sensors_plus/sensors_plus.dart';import 'package:shared_preferences/shared_preferences.dart';import 'audio_player_service.dart';+import 'chromecast_service.dart';enum SleepTimerMode { off, time, chapters }@@ -81,6 +82,9 @@ class SleepTimerService extends ChangeNotifier {SleepTimerService._();final _player = AudioPlayerService();+ final _cast = ChromecastService();++ bool get _isPlaybackActive => _player.isPlaying || _cast.isPlaying;// ── State ──SleepTimerMode _mode = SleepTimerMode.off;@@ -147,13 +151,13 @@ class SleepTimerService extends ChangeNotifier {void _startTimeCountdown() {_timer?.cancel();- _wasPlaying = _player.isPlaying;+ _wasPlaying = _isPlaybackActive;_timer = Timer.periodic(const Duration(seconds: 1), (_) async {if (_timeRemaining.inSeconds <= 0) {_triggerSleep();return;}- final isPlaying = _player.isPlaying;+ final isPlaying = _isPlaybackActive;// Detect pause→play transition and reset if setting is onif (isPlaying && !_wasPlaying) {@@ -221,17 +225,22 @@ class SleepTimerService extends ChangeNotifier {void _startChapterMonitor() {_positionSub?.cancel();- _positionSub = _player.positionStream.listen((pos) {- if (!_player.isPlaying) return;-+ // Use cast position stream when casting, local player stream otherwise+ final stream = _cast.isCasting+ ? _cast.castPositionStream+ : _player.positionStream;+ if (stream == null) return;+ _positionSub = stream.listen((pos) {+ if (!_isPlaybackActive) return;+final currentIdx = _getCurrentChapterIndex();if (currentIdx < 0) return;-+// Update chapters remainingif (_targetChapterIndex >= 0) {_chaptersRemaining = (_targetChapterIndex - currentIdx).clamp(0, 999);notifyListeners();-+// Check if we've reached the end of the target chapterif (currentIdx >= _targetChapterIndex) {_triggerSleep();@@ -252,9 +261,12 @@ class SleepTimerService extends ChangeNotifier {// ── Common ──int _getCurrentChapterIndex() {- final chapters = _player.chapters;+ final casting = _cast.isCasting;+ final chapters = casting ? _cast.castingChapters : _player.chapters;if (chapters.isEmpty) return -1;- final pos = _player.position.inMilliseconds / 1000.0;+ final pos = casting+ ? _cast.castPosition.inMilliseconds / 1000.0+ : _player.position.inMilliseconds / 1000.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;@@ -267,7 +279,11 @@ class SleepTimerService extends ChangeNotifier {void _triggerSleep() {debugPrint('[SleepTimer] Triggering sleep — pausing playback');_vibrateSleep();- _player.pause();+ if (_cast.isCasting) {+ _cast.pause();+ } else {+ _player.pause();+ }cancel();}@@ -426,7 +442,7 @@ class SleepTimerService extends ChangeNotifier {debugPrint('[SleepTimer] Window boundary timer set for ${delay.inMinutes}m from now');_windowBoundaryTimer = Timer(delay, () {_windowBoundaryTimer = null;- if (_player.isPlaying && !isActive && !_autoSleepDismissed) {+ if (_isPlaybackActive && !isActive && !_autoSleepDismissed) {_wasInWindow = true;debugPrint('[SleepTimer] Window boundary hit — starting ${settings.durationMinutes}m timer');setTimeSleep(Duration(minutes: settings.durationMinutes));diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex a25caa5e..54dd5ad7 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -63,6 +63,11 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}return true;}+ bool get _isCastingThis {+ final cast = ChromecastService();+ return cast.isCasting && cast.castingItemId == _itemId;+ }+ bool get _isPlaybackActive => _isActive || _isCastingThis;bool get _isPodcastEpisode => _isActive && widget.player.currentEpisodeId != null;// For inactive podcast show cards: recentEpisode is embedded in the continue-listening entity@@ -93,6 +98,12 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClisuper.initState();_fetchChaptersIfNeeded();_startChapterTracking();+ ChromecastService().addListener(_onCastChanged);+ }++ void _onCastChanged() {+ _startChapterTracking();+ if (mounted) setState(() {});}Future<void> _fetchChaptersIfNeeded() async {@@ -121,12 +132,42 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClivoid _startChapterTracking() {_chapterTrackSub?.cancel();++ if (_isCastingThis) {+ final stream = ChromecastService().castPositionStream;+ if (stream == null) return;+ _chapterTrackSub = stream.listen((pos) {+ if (!_isCastingThis) return;+ final posS = pos.inMilliseconds / 1000.0;+ final chapters = ChromecastService().castingChapters;+ if (chapters.isEmpty) {+ final sec = pos.inSeconds;+ if (sec != _lastChapterIdx) {+ _lastChapterIdx = sec;+ if (mounted) setState(() {});+ }+ return;+ }+ int idx = 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() ?? 0;+ if (posS >= start && posS < end) { idx = i; break; }+ }+ if (idx != _lastChapterIdx) {+ _lastChapterIdx = idx;+ if (mounted) setState(() {});+ }+ });+ return;+ }+_chapterTrackSub = widget.player.absolutePositionStream.listen((pos) {if (!_isActive) return;final posS = pos.inMilliseconds / 1000.0;final chapters = widget.player.chapters.isNotEmpty ? widget.player.chapters : _chapters;if (chapters.isEmpty) {- // No chapters (podcast episode) — rebuild every second to keep % livefinal sec = pos.inSeconds;if (sec != _lastChapterIdx) {_lastChapterIdx = sec;@@ -175,6 +216,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli@overridevoid dispose() {+ ChromecastService().removeListener(_onCastChanged);_chapterTrackSub?.cancel();_blurredCover?.dispose();super.dispose();@@ -277,19 +319,20 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliisFinished = lib.getProgressData(_itemId)?['isFinished'] == true;}final chapterIdx = _currentChapterIndex();- final totalChapters = _isActive ? widget.player.chapters.length : _chapters.length;+ final cast = ChromecastService();+ final totalChapters = _isCastingThis ? cast.castingChapters.length : (_isActive ? widget.player.chapters.length : _chapters.length);final double bookProgress;- if (_isActive && widget.player.totalDuration > 0) {+ if (_isCastingThis && cast.castingDuration > 0) {+ final castPos = cast.castPosition.inMilliseconds / 1000.0;+ bookProgress = (castPos / cast.castingDuration).clamp(0.0, 1.0);+ } else if (_isActive && widget.player.totalDuration > 0) {final playerPos = widget.player.position.inMilliseconds / 1000.0;- // Don't use player position if it's near zero while we have real progress- // (means the player is still loading/seeking to resume point)if (playerPos < 1.0 && progress > 0.01) {- bookProgress = progress; // Keep showing stored progress during load+ bookProgress = progress;} else {bookProgress = (playerPos / widget.player.totalDuration).clamp(0.0, 1.0);}} else {- // For inactive cards, use stored progress (episode-level for podcast shows)bookProgress = progress;}@@ -391,7 +434,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli// ── Book progress bar ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false, itemId: _itemId),),const SizedBox(height: 10),// ── Cover with title/author/chapter overlaid + download badge ──@@ -412,7 +455,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifinal castService = ChromecastService();final isCastingThis = castService.isCasting && castService.castingItemId == _itemId;return GestureDetector(- onTap: _isActive && !isFinished ? () => _expandCard(context) : null,+ onTap: _isPlaybackActive && !isFinished ? () => _expandCard(context) : null,child: Container(width: coverSize,height: coverSize,@@ -563,7 +606,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli// ── Chapter pill-scrubber (same width as book bar) ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),),// ── Controls + buttons ──Expanded(@@ -585,14 +628,14 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliRow(children: [Expanded(child: CardWideButton(icon: Icons.list_rounded, label: 'Chapters',- accent: accent, isActive: _isActive,+ accent: accent, isActive: _isPlaybackActive,onTap: () => _showChapters(context, accent, tt),)),const SizedBox(width: 8),Expanded(child: CardWideButton(icon: Icons.speed_rounded, label: 'Speed',- accent: accent, isActive: _isActive,- child: CardSpeedButtonInline(player: widget.player, accent: accent, isActive: _isActive),+ accent: accent, isActive: _isPlaybackActive,+ child: CardSpeedButtonInline(player: widget.player, accent: accent, isActive: _isActive, itemId: _itemId),)),]),const SizedBox(height: 8),@@ -600,13 +643,13 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliRow(children: [Expanded(child: CardWideButton(icon: Icons.bedtime_outlined, label: 'Sleep Timer',- accent: accent, isActive: _isActive,- child: CardSleepButtonInline(accent: accent, isActive: _isActive),+ accent: accent, isActive: _isPlaybackActive,+ child: CardSleepButtonInline(accent: accent, isActive: _isPlaybackActive),)),const SizedBox(width: 8),Expanded(child: CardWideButton(icon: Icons.bookmark_outline_rounded, label: 'Bookmarks',- accent: accent, isActive: _isActive,+ accent: accent, isActive: _isPlaybackActive,child: CardBookmarkButtonInline(player: widget.player, accent: accent,isActive: _isActive, itemId: _itemId,@@ -671,10 +714,13 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}int _currentChapterIndex() {- final chapters = _isActive ? widget.player.chapters : _chapters;+ final cast = ChromecastService();+ final chapters = _isCastingThis ? cast.castingChapters : (_isActive ? widget.player.chapters : _chapters);if (chapters.isEmpty) return -1;double pos;- if (_isActive) {+ if (_isCastingThis) {+ pos = cast.castPosition.inMilliseconds / 1000.0;+ } else if (_isActive) {pos = widget.player.position.inMilliseconds / 1000.0;} else {// Use stored progress to calculate position when not actively playing@@ -696,6 +742,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}String? _chapterName(int chapterIdx) {+ if (_isCastingThis) {+ final ch = ChromecastService().currentChapter;+ return ch?['title'] as String?;+ }if (_isActive && widget.player.currentChapter != null) {return widget.player.currentChapter!['title'] as String?;}@@ -789,10 +839,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}void _showChapters(BuildContext context, Color accent, TextTheme tt) {- final chapters = _isActive ? widget.player.chapters : _chapters;+ final cast = ChromecastService();+ final chapters = _isCastingThis ? cast.castingChapters : (_isActive ? widget.player.chapters : _chapters);if (chapters.isEmpty) return;- // Get total duration for percentage calc- final totalDur = _isActive ? widget.player.totalDuration : _duration;+ final totalDur = _isCastingThis ? cast.castingDuration : (_isActive ? widget.player.totalDuration : _duration);showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true,@@ -817,9 +867,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifinal chTitle = ch['title'] as String? ?? 'Chapter ${i + 1}';final start = (ch['start'] as num?)?.toDouble() ?? 0;final end = (ch['end'] as num?)?.toDouble() ?? 0;- final pos = _isActive ? widget.player.position.inMilliseconds / 1000.0 : 0.0;- final isCurrent = _isActive && pos >= start && pos < end;- // Percentage of book at end of this chapter+ final pos = _isCastingThis+ ? cast.castPosition.inMilliseconds / 1000.0+ : (_isActive ? widget.player.position.inMilliseconds / 1000.0 : 0.0);+ final isCurrent = _isPlaybackActive && pos >= start && pos < end;final pct = totalDur > 0 ? (end / totalDur * 100).round() : 0;return ListTile(dense: true, selected: isCurrent,@@ -834,8 +885,13 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliconst SizedBox(width: 8),Text(_fmtDur(end - start), style: tt.labelSmall?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant)),]),- onTap: _isActive ? () {- widget.player.seekTo(Duration(seconds: start.round()));+ onTap: _isPlaybackActive ? () {+ final seekDur = Duration(seconds: start.round());+ if (_isCastingThis) {+ cast.seekTo(seekDur);+ } else {+ widget.player.seekTo(seekDur);+ }Navigator.pop(ctx);} : null,);diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dartindex 1d66d1d8..880180ce 100644--- a/lib/widgets/card_buttons.dart+++ b/lib/widgets/card_buttons.dart@@ -2,6 +2,7 @@ import 'dart:ui';import 'package:flutter/material.dart';import '../services/audio_player_service.dart';import '../services/bookmark_service.dart';+import '../services/chromecast_service.dart';import '../services/sleep_timer_service.dart';import 'absorb_slider.dart';import 'sleep_timer_sheet.dart';@@ -202,9 +203,10 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {@override Widget build(BuildContext context) {final cs = Theme.of(context).colorScheme;final lg = widget.large;+ final enabled = widget.isActive || _isCasting;return GestureDetector(- onTap: widget.isActive ? () => _showBookmarks(context) : () => showInactiveToast(context),- onLongPress: widget.isActive ? () => _quickAdd(context) : null,+ onTap: enabled ? () => _showBookmarks(context) : () => showInactiveToast(context),+ onLongPress: enabled ? () => _quickAdd(context) : null,child: Container(padding: EdgeInsets.symmetric(vertical: lg ? 12 : 8),decoration: BoxDecoration(@@ -216,10 +218,10 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {mainAxisAlignment: MainAxisAlignment.center,children: [Icon(Icons.bookmark_outline_rounded, size: lg ? 22 : 18,- color: widget.isActive ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24)),+ color: enabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24)),const SizedBox(width: 8),Text(_count > 0 ? 'Bookmarks ($_count)' : 'Bookmark', style: TextStyle(- color: widget.isActive ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24),+ color: enabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24),fontSize: lg ? 14 : 12, fontWeight: FontWeight.w500)),],),@@ -227,10 +229,19 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {);}+ bool get _isCasting {+ final cast = ChromecastService();+ return cast.isCasting && cast.castingItemId == widget.itemId;+ }+void _quickAdd(BuildContext ctx) async {- final pos = widget.player.position.inMilliseconds / 1000.0;+ final cast = ChromecastService();+ final pos = _isCasting+ ? cast.castPosition.inMilliseconds / 1000.0+ : widget.player.position.inMilliseconds / 1000.0;+ final chapters = _isCasting ? cast.castingChapters : widget.player.chapters;String? chTitle;- for (final ch in widget.player.chapters) {+ for (final ch in chapters) {final m = ch as Map<String, dynamic>;final s = (m['start'] as num?)?.toDouble() ?? 0;final e = (m['end'] as num?)?.toDouble() ?? 0;@@ -261,35 +272,45 @@ class CardSpeedButtonInline extends StatelessWidget {final Color accent;final bool isActive;final bool large;- const CardSpeedButtonInline({super.key, required this.player, required this.accent, required this.isActive, this.large = false});+ final String? itemId;+ const CardSpeedButtonInline({super.key, required this.player, required this.accent, required this.isActive, this.large = false, this.itemId});@override Widget build(BuildContext context) {final cs = Theme.of(context).colorScheme;- return GestureDetector(- onTap: isActive ? () {- showModalBottomSheet(context: context, backgroundColor: Colors.transparent,- useSafeArea: true,- builder: (ctx) => CardSpeedSheet(player: player, accent: accent));- } : () => showInactiveToast(context),- child: Container(- height: large ? 48 : 36,- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(large ? 16 : 14),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),- ),- child: Row(- mainAxisAlignment: MainAxisAlignment.center,- children: [- Icon(Icons.speed_rounded, size: large ? 20 : 16,- color: isActive ? accent : cs.onSurface.withValues(alpha: 0.24)),- const SizedBox(width: 8),- Text('${player.speed.toStringAsFixed(2)}x', style: TextStyle(- color: isActive ? accent : cs.onSurface.withValues(alpha: 0.24),- fontSize: large ? 15 : 13, fontWeight: FontWeight.w700)),- ],- ),- ),+ final cast = ChromecastService();+ return ListenableBuilder(+ listenable: cast,+ builder: (context, _) {+ final castNow = itemId != null && cast.isCasting && cast.castingItemId == itemId;+ final enabledNow = isActive || castNow;+ final speedNow = castNow ? cast.castSpeed : player.speed;+ return GestureDetector(+ onTap: enabledNow ? () {+ showModalBottomSheet(context: context, backgroundColor: Colors.transparent,+ useSafeArea: true,+ builder: (ctx) => CardSpeedSheet(player: player, accent: accent, itemId: itemId));+ } : () => showInactiveToast(context),+ child: Container(+ height: large ? 48 : 36,+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(large ? 16 : 14),+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),+ ),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Icon(Icons.speed_rounded, size: large ? 20 : 16,+ color: enabledNow ? accent : cs.onSurface.withValues(alpha: 0.24)),+ const SizedBox(width: 8),+ Text('${speedNow.toStringAsFixed(2)}x', style: TextStyle(+ color: enabledNow ? accent : cs.onSurface.withValues(alpha: 0.24),+ fontSize: large ? 15 : 13, fontWeight: FontWeight.w700)),+ ],+ ),+ ),+ );+ },);}}@@ -297,8 +318,8 @@ class CardSpeedButtonInline extends StatelessWidget {// ─── SPEED SHEET ─────────────────────────────────────────────class CardSpeedSheet extends StatefulWidget {- final AudioPlayerService player; final Color accent;- const CardSpeedSheet({super.key, required this.player, required this.accent});+ final AudioPlayerService player; final Color accent; final String? itemId;+ const CardSpeedSheet({super.key, required this.player, required this.accent, this.itemId});@override State<CardSpeedSheet> createState() => _CardSpeedSheetState();}@@ -306,8 +327,25 @@ class _CardSpeedSheetState extends State<CardSpeedSheet> {late double _speed;static const _presets = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5];- @override void initState() { super.initState(); _speed = (widget.player.speed * 20).round() / 20.0; }- void _setSpeed(double v) { final s = (v * 20).round() / 20.0; setState(() => _speed = s.clamp(0.5, 3.0)); widget.player.setSpeed(_speed); }+ bool get _isCasting {+ final cast = ChromecastService();+ return widget.itemId != null && cast.isCasting && cast.castingItemId == widget.itemId;+ }++ @override void initState() {+ super.initState();+ final initialSpeed = _isCasting ? ChromecastService().castSpeed : widget.player.speed;+ _speed = (initialSpeed * 20).round() / 20.0;+ }+ void _setSpeed(double v) {+ final s = (v * 20).round() / 20.0;+ setState(() => _speed = s.clamp(0.5, 3.0));+ if (_isCasting) {+ ChromecastService().setSpeed(_speed);+ } else {+ widget.player.setSpeed(_speed);+ }+ }@override Widget build(BuildContext context) {final tt = Theme.of(context).textTheme;@@ -403,7 +441,15 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {final bm = _bookmarks![i];final hasNote = bm.note != null && bm.note!.isNotEmpty;return InkWell(- onTap: () { widget.player.seekTo(Duration(seconds: bm.positionSeconds.round())); Navigator.pop(ctx); },+ onTap: () {+ final seekDur = Duration(seconds: bm.positionSeconds.round());+ if (_isCasting) {+ ChromecastService().seekTo(seekDur);+ } else {+ widget.player.seekTo(seekDur);+ }+ Navigator.pop(ctx);+ },onLongPress: () => _editBookmark(bm),child: Padding(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),@@ -451,14 +497,23 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {);}+ bool get _isCasting {+ final cast = ChromecastService();+ return cast.isCasting && cast.castingItemId == widget.itemId;+ }+Future<void> _addBookmark() async {- final pos = widget.player.position.inMilliseconds / 1000.0;+ final cast = ChromecastService();+ final pos = _isCasting+ ? cast.castPosition.inMilliseconds / 1000.0+ : widget.player.position.inMilliseconds / 1000.0;final h = pos ~/ 3600; final m = (pos % 3600) ~/ 60; final s = pos.toInt() % 60;final posStr = h > 0 ? '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}' : '$m:${s.toString().padLeft(2, '0')}';// Find current chapter name for default title+ final chapters = _isCasting ? cast.castingChapters : widget.player.chapters;String defaultTitle = 'Bookmark at $posStr';- for (final ch in widget.player.chapters) {+ for (final ch in chapters) {final cm = ch as Map<String, dynamic>;final cs = (cm['start'] as num?)?.toDouble() ?? 0;final ce = (cm['end'] as num?)?.toDouble() ?? 0;diff --git a/lib/widgets/card_playback_controls.dart b/lib/widgets/card_playback_controls.dartindex 5381240a..1b333ffb 100644--- a/lib/widgets/card_playback_controls.dart+++ b/lib/widgets/card_playback_controls.dart@@ -147,11 +147,6 @@ class _CardPlaybackControlsState extends State<CardPlaybackControls> with Single),),),- // Cast indicator badge- Positioned(- bottom: 4,- child: Icon(Icons.cast_connected_rounded, size: 14, color: widget.accent.withValues(alpha: 0.7)),- ),],),),diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dartindex a81bd489..bbb1ae11 100644--- a/lib/widgets/card_progress_bar.dart+++ b/lib/widgets/card_progress_bar.dart@@ -3,6 +3,7 @@ import 'dart:math';import 'dart:ui';import 'package:flutter/material.dart';import '../services/audio_player_service.dart';+import '../services/chromecast_service.dart';import 'absorb_slider.dart';import 'absorbing_shared.dart';@@ -20,7 +21,8 @@ class CardDualProgressBar extends StatefulWidget {final String? chapterName;final int chapterIndex;final int totalChapters;- const CardDualProgressBar({super.key, required this.player, required this.accent, required this.isActive, required this.staticProgress, required this.staticDuration, required this.chapters, this.showBookBar = true, this.showChapterBar = true, this.chapterName, this.chapterIndex = 0, this.totalChapters = 0});+ final String? itemId;+ const CardDualProgressBar({super.key, required this.player, required this.accent, required this.isActive, required this.staticProgress, required this.staticDuration, required this.chapters, this.showBookBar = true, this.showChapterBar = true, this.chapterName, this.chapterIndex = 0, this.totalChapters = 0, this.itemId});@override State<CardDualProgressBar> createState() => _CardDualProgressBarState();}@@ -37,6 +39,7 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPrDateTime _lastPosTime = DateTime.now();double _currentSpeed = 1.0;bool _isPlaying = false;+ bool _isCastMode = false;StreamSubscription<Duration>? _posSub;@override@@ -47,8 +50,8 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr_smoothTicker = AnimationController(vsync: this, duration: const Duration(days: 999))..repeat();_loadSettings();_subscribePosition();- // Listen for settings changes instead of pollingPlayerSettings.settingsChanged.addListener(_loadSettings);+ ChromecastService().addListener(_onCastChanged);}void _loadSettings() {@@ -56,6 +59,13 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPrPlayerSettings.getSpeedAdjustedTime().then((v) { if (mounted && v != _speedAdjustedTime) setState(() => _speedAdjustedTime = v); });}+ void _onCastChanged() {+ final cast = ChromecastService();+ final wasCast = _isCastMode;+ final isCast = widget.itemId != null && cast.isCasting && cast.castingItemId == widget.itemId;+ if (wasCast != isCast) _subscribePosition();+ }+@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {if (state == AppLifecycleState.resumed) _loadSettings();@@ -69,7 +79,22 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPrvoid _subscribePosition() {_posSub?.cancel();- if (widget.isActive) {+ final cast = ChromecastService();+ _isCastMode = widget.itemId != null && cast.isCasting && cast.castingItemId == widget.itemId;++ if (_isCastMode) {+ _lastKnownPos = cast.castPosition.inMilliseconds / 1000.0;+ _lastPosTime = DateTime.now();+ _currentSpeed = cast.castSpeed;+ _isPlaying = cast.isPlaying;+ _posSub = cast.castPositionStream?.listen((dur) {+ final posSeconds = dur.inMilliseconds / 1000.0;+ _lastKnownPos = posSeconds;+ _lastPosTime = DateTime.now();+ _currentSpeed = cast.castSpeed;+ _isPlaying = cast.isPlaying;+ });+ } else if (widget.isActive) {// Reset to the seed on a fresh subscription — clears stale position from a// previous episode and gives the near-zero rejection filter a clean baseline.final seedPos = widget.staticProgress * widget.staticDuration;@@ -114,6 +139,11 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr/// Smoothly interpolated position — predicts where playback is right now./// Snaps immediately to seek target when a seek is in progress.double get _smoothPos {+ if (_isCastMode) {+ if (!_isPlaying) return _lastKnownPos;+ final elapsed = DateTime.now().difference(_lastPosTime).inMilliseconds / 1000.0;+ return _lastKnownPos + elapsed * _currentSpeed;+ }// If a seek just happened, snap to the target immediatelyfinal seekTarget = widget.player.activeSeekTarget;if (seekTarget != null && (seekTarget - _lastKnownPos).abs() > 2.0) {@@ -127,31 +157,58 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr@override void dispose() {WidgetsBinding.instance.removeObserver(this);PlayerSettings.settingsChanged.removeListener(_loadSettings);+ ChromecastService().removeListener(_onCastChanged);_posSub?.cancel();_waveController.dispose();_smoothTicker.dispose();super.dispose();}+ void _doSeek(int seekMs) {+ if (_isCastMode) {+ ChromecastService().seekTo(Duration(milliseconds: seekMs));+ } else {+ widget.player.seekTo(Duration(milliseconds: seekMs));+ }+ }+@overrideWidget build(BuildContext context) {final tt = Theme.of(context).textTheme;final cs = Theme.of(context).colorScheme;final player = widget.player;- final active = widget.isActive;+ final cast = ChromecastService();+ final active = widget.isActive || _isCastMode;return ListenableBuilder(listenable: _smoothTicker,builder: (context, _) {final staticPos = widget.staticProgress * widget.staticDuration;final posS = active ? _smoothPos : staticPos;- final totalDur = active ? player.totalDuration : widget.staticDuration;+ final totalDur = _isCastMode ? cast.castingDuration : (widget.isActive ? player.totalDuration : widget.staticDuration);final speed = active ? _currentSpeed : 1.0;final isPlaying = active && _isPlaying;final bookProgress = totalDur > 0 ? (posS / totalDur).clamp(0.0, 1.0) : 0.0;double chapterStart = 0, chapterEnd = totalDur;- if (active) {+ 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;+ }+ }+ }+ } else if (widget.isActive) {final chapter = player.currentChapter;if (chapter != null) {chapterStart = (chapter['start'] as num?)?.toDouble() ?? 0;@@ -202,8 +259,8 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPrbehavior: HitTestBehavior.opaque,onHorizontalDragStart: active ? (d) { setState(() => _bookDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,onHorizontalDragUpdate: active ? (d) { setState(() => _bookDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,- onHorizontalDragEnd: active ? (_) { if (_bookDragValue != null) { final seekMs = (_bookDragValue! * totalDur * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } setState(() => _bookDragValue = null); } : null,- onTapUp: active ? (d) { final v = (d.localPosition.dx / w).clamp(0.0, 1.0); final seekMs = (v * totalDur * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } : null,+ onHorizontalDragEnd: active ? (_) { if (_bookDragValue != null) { final seekMs = (_bookDragValue! * totalDur * 1000).round(); _doSeek(seekMs); } setState(() => _bookDragValue = null); } : null,+ onTapUp: active ? (d) { final v = (d.localPosition.dx / w).clamp(0.0, 1.0); final seekMs = (v * totalDur * 1000).round(); _doSeek(seekMs); } : null,child: CustomPaint(size: Size(w, 32), painter: AbsorbProgressPainter(progress: p, accent: widget.accent.withValues(alpha: 0.5), isDragging: _bookDragValue != null)),);})),@@ -241,8 +298,8 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPrbehavior: HitTestBehavior.opaque,onHorizontalDragStart: active ? (d) { setState(() => _chapterDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,onHorizontalDragUpdate: active ? (d) { setState(() => _chapterDragValue = (d.localPosition.dx / w).clamp(0.0, 1.0)); } : null,- onHorizontalDragEnd: active ? (_) { if (_chapterDragValue != null) { final seekMs = ((chapterStart + _chapterDragValue! * chapterDur) * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } setState(() => _chapterDragValue = null); } : null,- onTapUp: active ? (d) { final v = (d.localPosition.dx / w).clamp(0.0, 1.0); final seekMs = ((chapterStart + v * chapterDur) * 1000).round(); player.seekTo(Duration(milliseconds: seekMs)); } : null,+ onHorizontalDragEnd: active ? (_) { if (_chapterDragValue != null) { final seekMs = ((chapterStart + _chapterDragValue! * chapterDur) * 1000).round(); _doSeek(seekMs); } setState(() => _chapterDragValue = null); } : null,+ onTapUp: active ? (d) { final v = (d.localPosition.dx / w).clamp(0.0, 1.0); final seekMs = ((chapterStart + v * chapterDur) * 1000).round(); _doSeek(seekMs); } : null,child: CustomPaint(size: Size(w, 30),painter: ChapterPillPainter(diff --git a/lib/widgets/chromecast_button.dart b/lib/widgets/chromecast_button.dartindex ed33ff69..4bbb5a1b 100644--- a/lib/widgets/chromecast_button.dart+++ b/lib/widgets/chromecast_button.dart@@ -1,8 +1,5 @@-import 'dart:async';import 'package:flutter/material.dart';import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';-import 'package:provider/provider.dart';-import '../providers/library_provider.dart';import '../services/chromecast_service.dart';import '../services/api_service.dart';@@ -90,7 +87,7 @@ void showCastDevicePicker(}/// Wait for connection to establish, then cast the item.-void _waitAndCast(+Future<void> _waitAndCast(ChromecastService cast, {required ApiService api,required String itemId,@@ -100,40 +97,27 @@ void _waitAndCast(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,- episodeId: episodeId);- return;- }-- StreamSubscription? sub;- Timer? timeout;-- void cleanup() {- sub?.cancel();- timeout?.cancel();- }-- sub = GoogleCastSessionManager.instance.currentSessionStream.listen((session) {- if (cast.isConnected) {- cleanup();- Future.delayed(const Duration(milliseconds: 500), () {- cast.castItem(api: api, itemId: itemId, title: title, author: author,- coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters,- episodeId: episodeId);- });+}) async {+ // Poll for connection (up to 15s)+ if (!cast.isConnected) {+ for (int i = 0; i < 30; i++) {+ await Future.delayed(const Duration(milliseconds: 500));+ if (cast.isConnected) break;+ }+ if (!cast.isConnected) {+ debugPrint('[Cast] Connection timeout — giving up auto-cast');+ return;}- });+ }- timeout = Timer(const Duration(seconds: 15), () {- debugPrint('[Cast] Connection timeout — giving up auto-cast');- cleanup();- });+ // Small delay to let session fully initialise+ await Future.delayed(const Duration(milliseconds: 500));+ cast.castItem(api: api, itemId: itemId, title: title, author: author,+ coverUrl: coverUrl, totalDuration: totalDuration, chapters: chapters,+ episodeId: episodeId);}-/// Bottom sheet with cast controls when connected.+/// Bottom sheet with cast volume, stop, and disconnect controls.class CastControlSheet extends StatelessWidget {const CastControlSheet({super.key});@@ -161,73 +145,8 @@ class CastControlSheet extends StatelessWidget {style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: accent), overflow: TextOverflow.ellipsis)),]),- if (cast.isCasting) ...[- const SizedBox(height: 20),- // Book info + chapter- Row(children: [- if (cast.castingCoverUrl != null)- ClipRRect(borderRadius: BorderRadius.circular(8),- child: Image.network(cast.castingCoverUrl!, width: 48, height: 48, fit: BoxFit.cover,- headers: context.read<LibraryProvider>().mediaHeaders,- errorBuilder: (_, __, ___) => Container(width: 48, height: 48,- decoration: BoxDecoration(color: Colors.white10, borderRadius: BorderRadius.circular(8)),- child: const Icon(Icons.headphones_rounded, size: 24, color: Colors.white24)))),- const SizedBox(width: 14),- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(cast.castingTitle ?? 'Unknown', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis),- const SizedBox(height: 2),- Text(cast.castingAuthor ?? '', style: const TextStyle(fontSize: 12, color: Colors.white60), maxLines: 1, overflow: TextOverflow.ellipsis),- if (cast.currentChapterTitle != null) ...[- const SizedBox(height: 2),- Text(cast.currentChapterTitle!, style: TextStyle(fontSize: 11, color: accent.withValues(alpha: 0.7)), maxLines: 1, overflow: TextOverflow.ellipsis),- ],- ])),- ]),- const SizedBox(height: 16),-- // Progress bar- StreamBuilder<Duration>(- stream: cast.castPositionStream?.map((d) => d ?? Duration.zero),- initialData: cast.castPosition,- builder: (_, snap) {- final pos = snap.data ?? Duration.zero;- final totalMs = (cast.castingDuration * 1000).round();- final progress = totalMs > 0 ? (pos.inMilliseconds / totalMs).clamp(0.0, 1.0) : 0.0;- return Column(children: [- LinearProgressIndicator(value: progress, backgroundColor: Colors.white10, color: accent, minHeight: 3, borderRadius: BorderRadius.circular(2)),- const SizedBox(height: 6),- Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [- Text(_fmt(pos), style: const TextStyle(fontSize: 11, color: Colors.white38)),- Text(_fmt(Duration(seconds: cast.castingDuration.round())), style: const TextStyle(fontSize: 11, color: Colors.white38)),- ]),- ]);- },- ),- const SizedBox(height: 12),-- // Playback controls- Row(mainAxisAlignment: MainAxisAlignment.center, children: [- IconButton(onPressed: cast.skipToPreviousChapter, icon: const Icon(Icons.skip_previous_rounded, size: 24, color: Colors.white38)),- IconButton(onPressed: () => cast.skipBackward(10), icon: const Icon(Icons.replay_10_rounded, size: 32, color: Colors.white70)),- const SizedBox(width: 8),- Container(width: 52, height: 52,- decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white,- boxShadow: [BoxShadow(color: accent.withValues(alpha: 0.3), blurRadius: 16, spreadRadius: -4)]),- child: IconButton(onPressed: cast.togglePlayPause,- icon: Icon(cast.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded, size: 28, color: Colors.black87))),- const SizedBox(width: 8),- IconButton(onPressed: () => cast.skipForward(30), icon: const Icon(Icons.forward_30_rounded, size: 32, color: Colors.white70)),- IconButton(onPressed: cast.skipToNextChapter, icon: const Icon(Icons.skip_next_rounded, size: 24, color: Colors.white38)),- ]),-- // Speed control- const SizedBox(height: 12),- _CastSpeedControl(cast: cast, accent: accent),-- // Volume control- const SizedBox(height: 8),- _CastVolumeControl(cast: cast, accent: accent),- ],+ const SizedBox(height: 16),+ _CastVolumeControl(cast: cast, accent: accent),const SizedBox(height: 20),Row(children: [@@ -253,67 +172,6 @@ class CastControlSheet extends StatelessWidget {},);}-- String _fmt(Duration d) {- final h = d.inHours, m = d.inMinutes % 60, s = d.inSeconds % 60;- if (h > 0) return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';- return '$m:${s.toString().padLeft(2, '0')}';- }-}--// ─── Cast Speed Control ─────────────────────────────────────--class _CastSpeedControl extends StatelessWidget {- final ChromecastService cast;- final Color accent;- const _CastSpeedControl({required this.cast, required this.accent});-- static const _presets = [0.75, 1.0, 1.25, 1.5, 1.75, 2.0];-- @override- Widget build(BuildContext context) {- final speed = cast.castSpeed;- return Row(- children: [- Icon(Icons.speed_rounded, size: 16, color: accent),- const SizedBox(width: 8),- Text('${speed.toStringAsFixed(2)}x',- style: TextStyle(fontSize: 13, fontWeight: FontWeight.w700, color: accent)),- const SizedBox(width: 12),- Expanded(- child: SizedBox(- height: 32,- child: ListView(- scrollDirection: Axis.horizontal,- children: _presets.map((s) {- final selected = (s - speed).abs() < 0.01;- return Padding(- padding: const EdgeInsets.only(right: 6),- child: GestureDetector(- onTap: () => cast.setSpeed(s),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),- decoration: BoxDecoration(- color: selected ? accent.withValues(alpha: 0.2) : Colors.white.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(8),- border: Border.all(color: selected ? accent.withValues(alpha: 0.4) : Colors.white12),- ),- child: Text('${s}x',- style: TextStyle(- fontSize: 12, fontWeight: FontWeight.w600,- color: selected ? accent : Colors.white54,- ),- ),- ),- ),- );- }).toList(),- ),- ),- ),- ],- );- }}// ─── Cast Volume Control ────────────────────────────────────diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dartindex 6484cfac..57d53596 100644--- a/lib/widgets/expanded_card.dart+++ b/lib/widgets/expanded_card.dart@@ -112,6 +112,11 @@ class _ExpandedCardState extends State<ExpandedCard> {}return true;}+ bool get _isCastingThis {+ final cast = ChromecastService();+ return cast.isCasting && cast.castingItemId == _itemId;+ }+ bool get _isPlaybackActive => _isActive || _isCastingThis;bool get _isPodcastEpisode => _isActive && widget.player.currentEpisodeId != null;Map<String, dynamic>? get _recentEpisode => _item['recentEpisode'] as Map<String, dynamic>?;@@ -143,12 +148,19 @@ class _ExpandedCardState extends State<ExpandedCard> {_currentEpisodeId = widget.player.currentEpisodeId;_wasPlaying = widget.player.hasBook;widget.player.addListener(_onPlayerChanged);+ ChromecastService().addListener(_onCastChanged);_startChapterTracking();_fetchChaptersIfNeeded();// Generate our own blurred cover_generateBlur();}+ void _onCastChanged() {+ if (!mounted || _isPopping) return;+ _startChapterTracking();+ setState(() {});+ }+@overridevoid didChangeDependencies() {super.didChangeDependencies();@@ -160,6 +172,7 @@ class _ExpandedCardState extends State<ExpandedCard> {void dispose() {if (!_isPopping) {widget.player.removeListener(_onPlayerChanged);+ ChromecastService().removeListener(_onCastChanged);_chapterTrackSub?.cancel();}_blurredCover?.dispose();@@ -191,8 +204,9 @@ class _ExpandedCardState extends State<ExpandedCard> {void _dismissExpanded() {if (_isPopping) return;_isPopping = true;- // Remove listener immediately to prevent further callbacks during pop animation+ // Remove listeners immediately to prevent further callbacks during pop animationwidget.player.removeListener(_onPlayerChanged);+ ChromecastService().removeListener(_onCastChanged);_chapterTrackSub?.cancel();WidgetsBinding.instance.addPostFrameCallback((_) {if (!mounted) return;@@ -262,6 +276,31 @@ class _ExpandedCardState extends State<ExpandedCard> {void _startChapterTracking() {_chapterTrackSub?.cancel();++ if (_isCastingThis) {+ final stream = ChromecastService().castPositionStream;+ if (stream == null) return;+ _chapterTrackSub = stream.listen((pos) {+ if (!_isCastingThis) return;+ final posS = pos.inMilliseconds / 1000.0;+ final chapters = ChromecastService().castingChapters;+ if (chapters.isEmpty) {+ final sec = pos.inSeconds;+ if (sec != _lastChapterIdx) { _lastChapterIdx = sec; if (mounted) setState(() {}); }+ return;+ }+ int idx = 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() ?? 0;+ if (posS >= start && posS < end) { idx = i; break; }+ }+ if (idx != _lastChapterIdx) { _lastChapterIdx = idx; if (mounted) setState(() {}); }+ });+ return;+ }+_chapterTrackSub = widget.player.absolutePositionStream.listen((pos) {if (!_isActive) return;final posS = pos.inMilliseconds / 1000.0;@@ -410,9 +449,13 @@ class _ExpandedCardState extends State<ExpandedCard> {isFinished = lib.getProgressData(_itemId)?['isFinished'] == true;}final chapterIdx = _currentChapterIndex();- final totalChapters = _isActive ? widget.player.chapters.length : _chapters.length;+ final cast = ChromecastService();+ final totalChapters = _isCastingThis ? cast.castingChapters.length : (_isActive ? widget.player.chapters.length : _chapters.length);final double bookProgress;- if (_isActive && widget.player.totalDuration > 0) {+ if (_isCastingThis && cast.castingDuration > 0) {+ final castPos = cast.castPosition.inMilliseconds / 1000.0;+ bookProgress = (castPos / cast.castingDuration).clamp(0.0, 1.0);+ } else if (_isActive && widget.player.totalDuration > 0) {final playerPos = widget.player.position.inMilliseconds / 1000.0;if (playerPos < 1.0 && progress > 0.01) {bookProgress = progress;@@ -501,7 +544,7 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Book progress bar ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false, itemId: _itemId),),const SizedBox(height: 16),// ── Cover art (larger — 90% width) ──@@ -668,7 +711,7 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Chapter scrubber ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),),// ── Controls + buttons ──Expanded(@@ -690,27 +733,27 @@ class _ExpandedCardState extends State<ExpandedCard> {Row(children: [Expanded(child: CardWideButton(icon: Icons.list_rounded, label: 'Chapters',- accent: accent, isActive: _isActive, large: true,+ accent: accent, isActive: _isPlaybackActive, large: true,onTap: () => _showChapters(context, accent, tt),)),const SizedBox(width: 10),Expanded(child: CardWideButton(icon: Icons.speed_rounded, label: 'Speed',- accent: accent, isActive: _isActive, large: true,- child: CardSpeedButtonInline(player: widget.player, accent: accent, isActive: _isActive, large: true),+ accent: accent, isActive: _isPlaybackActive, large: true,+ child: CardSpeedButtonInline(player: widget.player, accent: accent, isActive: _isActive, large: true, itemId: _itemId),)),]),const SizedBox(height: 10),Row(children: [Expanded(child: CardWideButton(icon: Icons.bedtime_outlined, label: 'Sleep Timer',- accent: accent, isActive: _isActive, large: true,- child: CardSleepButtonInline(accent: accent, isActive: _isActive, large: true),+ accent: accent, isActive: _isPlaybackActive, large: true,+ child: CardSleepButtonInline(accent: accent, isActive: _isPlaybackActive, large: true),)),const SizedBox(width: 10),Expanded(child: CardWideButton(icon: Icons.bookmark_outline_rounded, label: 'Bookmarks',- accent: accent, isActive: _isActive, large: true,+ accent: accent, isActive: _isPlaybackActive, large: true,child: CardBookmarkButtonInline(player: widget.player, accent: accent,isActive: _isActive, itemId: _itemId, large: true,@@ -718,26 +761,47 @@ class _ExpandedCardState extends State<ExpandedCard> {)),]),const SizedBox(height: 10),- // More menu+ // More menu / Cast controlsCenter(- child: GestureDetector(- behavior: HitTestBehavior.opaque,- onTap: () => _showMoreMenu(context, accent, tt),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.08),- borderRadius: BorderRadius.circular(22),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(Icons.more_horiz_rounded, size: 20, color: cs.onSurface.withValues(alpha: 0.54)),- const SizedBox(width: 6),- Text('More', style: TextStyle(fontSize: 13, 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: 24, vertical: 10),+ decoration: BoxDecoration(+ color: castActive ? accent.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.08),+ borderRadius: BorderRadius.circular(22),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: castActive+ ? [+ Icon(Icons.cast_connected_rounded, size: 20, color: accent),+ const SizedBox(width: 6),+ Text('Casting', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: accent)),+ ]+ : [+ Icon(Icons.more_horiz_rounded, size: 20, color: cs.onSurface.withValues(alpha: 0.54)),+ const SizedBox(width: 6),+ Text('More', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: cs.onSurface.withValues(alpha: 0.54))),+ ],+ ),+ ),+ );+ },),),const SizedBox(height: 8),@@ -805,10 +869,13 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Helpers (mirrored from AbsorbingCard) ──int _currentChapterIndex() {- final chapters = _isActive ? widget.player.chapters : _chapters;+ final cast = ChromecastService();+ final chapters = _isCastingThis ? cast.castingChapters : (_isActive ? widget.player.chapters : _chapters);if (chapters.isEmpty) return -1;double pos;- if (_isActive) {+ if (_isCastingThis) {+ pos = cast.castPosition.inMilliseconds / 1000.0;+ } else if (_isActive) {pos = widget.player.position.inMilliseconds / 1000.0;} else {final lib = context.read<LibraryProvider>();@@ -828,6 +895,10 @@ class _ExpandedCardState extends State<ExpandedCard> {}String? _chapterName(int chapterIdx) {+ if (_isCastingThis) {+ final ch = ChromecastService().currentChapter;+ return ch?['title'] as String?;+ }if (_isActive && widget.player.currentChapter != null) {return widget.player.currentChapter!['title'] as String?;}@@ -912,9 +983,10 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Bottom sheets ──void _showChapters(BuildContext context, Color accent, TextTheme tt) {- final chapters = _isActive ? widget.player.chapters : _chapters;+ final cast = ChromecastService();+ final chapters = _isCastingThis ? cast.castingChapters : (_isActive ? widget.player.chapters : _chapters);if (chapters.isEmpty) return;- final totalDur = _isActive ? widget.player.totalDuration : _duration;+ final totalDur = _isCastingThis ? cast.castingDuration : (_isActive ? widget.player.totalDuration : _duration);showModalBottomSheet(context: context, isScrollControlled: true, useSafeArea: true,@@ -939,8 +1011,10 @@ class _ExpandedCardState extends State<ExpandedCard> {final chTitle = ch['title'] as String? ?? 'Chapter ${i + 1}';final start = (ch['start'] as num?)?.toDouble() ?? 0;final end = (ch['end'] as num?)?.toDouble() ?? 0;- final pos = _isActive ? widget.player.position.inMilliseconds / 1000.0 : 0.0;- final isCurrent = _isActive && pos >= start && pos < end;+ final pos = _isCastingThis+ ? cast.castPosition.inMilliseconds / 1000.0+ : (_isActive ? widget.player.position.inMilliseconds / 1000.0 : 0.0);+ final isCurrent = _isPlaybackActive && pos >= start && pos < end;final pct = totalDur > 0 ? (end / totalDur * 100).round() : 0;return ListTile(dense: true, selected: isCurrent,@@ -955,8 +1029,13 @@ class _ExpandedCardState extends State<ExpandedCard> {const SizedBox(width: 8),Text(_fmtDur(end - start), style: tt.labelSmall?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant)),]),- onTap: _isActive ? () {- widget.player.seekTo(Duration(seconds: start.round()));+ onTap: _isPlaybackActive ? () {+ final seekDur = Duration(seconds: start.round());+ if (_isCastingThis) {+ cast.seekTo(seekDur);+ } else {+ widget.player.seekTo(seekDur);+ }Navigator.pop(ctx);} : null,);diff --git a/pubspec.yaml b/pubspec.yamlindex 45f2d006..dbbe6049 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: A Material 3 Audiobookshelf client for Android.publish_to: 'none'-version: 1.7.14+34+version: 1.7.16+34environment:sdk: '>=3.1.0 <4.0.0'