Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Log more about previews so odd start points can be traced

Barnabasbca3806d78cd
diff --git a/lib/services/bookmark_preview_player.dart b/lib/services/bookmark_preview_player.dart
index 1cc1a815..63e55d93 100644
--- a/lib/services/bookmark_preview_player.dart
+++ b/lib/services/bookmark_preview_player.dart
@@ -13,11 +13,17 @@ import 'offline_source.dart';
/// (per-file URLs built on demand). Pauses the main player while auditioning and
/// restores it on stop/dispose. Owned by the bookmark detail dialog.
class BookmarkPreviewPlayer extends ChangeNotifier {
- BookmarkPreviewPlayer({required this.itemId, this.api});
+ BookmarkPreviewPlayer({required this.itemId, this.api, this.label = 'preview'});
final String itemId;
final ApiService? api;
+ /// Which surface is auditioning, so the shared [Preview] log lines from the
+ /// book sample and the bookmark clip can be told apart.
+ final String label;
+
+ String get _tag => '[Preview] $label $itemId';
+
AudioPlayer? _player;
StreamSubscription<PlayerState>? _stateSub;
bool _loading = false;
@@ -82,7 +88,7 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
final tracks = await _resolveTracks();
if (_disposed) return;
if (tracks == null || tracks.isEmpty) {
- debugPrint('[BookmarkPreview] $itemId: no tracks resolved');
+ debugPrint('$_tag: no tracks resolved');
_loading = false;
notifyListeners();
throw StateError('no audio for $itemId');
@@ -91,8 +97,9 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
final hit = BookTrackResolver.mapGlobal(tracks, globalSeconds);
final track = hit.track;
final local = hit.localOffset;
- debugPrint('[BookmarkPreview] $itemId: play ${globalSeconds.toStringAsFixed(1)}s -> '
- 'track[${hit.index}] ${track.local ? "local" : "stream"} @${local.toStringAsFixed(1)}s');
+ debugPrint('$_tag: play ${globalSeconds.toStringAsFixed(1)}s -> '
+ 'track[${hit.index}] ${track.local ? "local" : "stream"} @${local.toStringAsFixed(1)}s '
+ 'clip=${clipLength.inSeconds}s');
try {
await _disposePlayer();
@@ -132,7 +139,7 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
_startAutoStop();
await player.play();
} catch (e) {
- debugPrint('[BookmarkPreview] $itemId: playback error: $e');
+ debugPrint('$_tag: playback error: $e');
if (_disposed) return;
_loading = false;
notifyListeners();
@@ -152,19 +159,11 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
if (main.isPlaying) await main.pause();
}
- /// Resume the main player only if the book we paused is still the loaded
- /// one and nothing else started playing meanwhile (the notification or
- /// Android Auto can change both while an audition runs).
- bool get _canResumeMain =>
- _mainWasPlaying == true &&
- !AudioPlayerService().isPlaying &&
- AudioPlayerService().currentItemId == _mainWasItemId;
-
void _startAutoStop() {
_autoStop?.cancel();
_autoStop = Timer(clipLength, () {
if (_disposed) return;
- debugPrint('[BookmarkPreview] auto-stop after ${clipLength.inSeconds}s');
+ debugPrint('$_tag: auto-stop after ${clipLength.inSeconds}s');
if (stopOnClipEnd) {
unawaited(stop());
} else {
@@ -186,16 +185,35 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
try {
await p.stop();
await p.dispose();
- } catch (_) {}
+ } catch (e) {
+ debugPrint('$_tag: teardown error: $e');
+ }
}
}
+ /// Resume the main player only if the book we paused is still the loaded one
+ /// and nothing else started playing meanwhile (the notification or Android
+ /// Auto can change both while an audition runs). Logged on every audition
+ /// end: "preview stopped my book and never brought it back" is otherwise
+ /// invisible, since all three inputs can shift underneath us.
+ bool _resumeDecision(String from) {
+ final main = AudioPlayerService();
+ final wasPlaying = _mainWasPlaying == true;
+ final mainIdle = !main.isPlaying;
+ final sameItem = main.currentItemId == _mainWasItemId;
+ final resume = wasPlaying && mainIdle && sameItem;
+ debugPrint('$_tag: $from resume=$resume (pausedMain=$wasPlaying '
+ 'mainIdle=$mainIdle sameItem=$sameItem was=$_mainWasItemId '
+ 'now=${main.currentItemId})');
+ return resume;
+ }
+
/// Stop the audition and resume the main player if we had paused it.
Future<void> stop() async {
await _disposePlayer();
// Reset the snapshot even when it's false, or a sheet-lifetime player's
// second audition would pause the main book and never resume it.
- final shouldResume = _canResumeMain;
+ final shouldResume = _resumeDecision('stop');
_mainWasPlaying = null;
_mainWasItemId = null;
if (shouldResume) await AudioPlayerService().play();
@@ -213,7 +231,7 @@ class BookmarkPreviewPlayer extends ChangeNotifier {
@override
void dispose() {
- final shouldResume = _canResumeMain;
+ final shouldResume = _resumeDecision('dispose');
_disposed = true;
_autoStop?.cancel();
_stateSub?.cancel();
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index b7682490..cce65745 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -188,6 +188,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
bool _chaptersExpanded = false;
bool _bookmarksExpanded = false;
BookmarkPreviewPlayer? _preview;
+ bool? _loggedPreviewVisible;
List<Bookmark> _bookmarks = [];
bool _isAbsorbing = false;
bool _hasLocalOverride = false;
@@ -537,6 +538,16 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
// lag local playback.
final showPreview = !isEbookOnly && !isFinished && currentTime < 60 &&
progress * duration < 60 && duration > 0;
+ // Deduped on the value so this fires once per change, not once per rebuild.
+ // "I don't have a preview button" needs the inputs, not just the outcome.
+ if (showPreview != _loggedPreviewVisible) {
+ _loggedPreviewVisible = showPreview;
+ debugPrint('[Preview] book ${widget.itemId}: button ${showPreview ? "shown" : "hidden"} '
+ '(ebookOnly=$isEbookOnly finished=$isFinished '
+ 'currentTime=${currentTime.toStringAsFixed(0)}s '
+ 'played=${(progress * duration).toStringAsFixed(0)}s '
+ 'duration=${duration.toStringAsFixed(0)}s)');
+ }
return ListView(controller: widget.scrollController, padding: EdgeInsets.fromLTRB(20, 8, 20, 32 + MediaQuery.of(context).viewPadding.bottom), children: [
Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),
@@ -2042,41 +2053,70 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
/// is always short, so the first chapter long enough to be real prose is the
/// sample point - capped to the first 10% of the book so a preview can never
/// spoil. Books without a usable chapter land shortly past the credits.
- double _previewStartSeconds(List<dynamic> chapters, double duration) {
+ /// Returns the start point and the rule that produced it. Every branch here
+ /// can land on the same number, so the reason has to be logged alongside it
+ /// or a "preview started somewhere odd" report is undiagnosable.
+ ({double seconds, String why}) _previewStartSeconds(
+ List<dynamic> chapters, double duration) {
const minRealChapter = 300.0;
const fallback = 90.0;
final clampedFallback = duration * 0.25 < fallback ? duration * 0.25 : fallback;
final spoilerCap = duration * 0.10;
+ var index = -1;
for (final c in chapters) {
+ index++;
if (c is! Map<String, dynamic>) continue;
final start = (c['start'] as num?)?.toDouble() ?? 0;
final end = (c['end'] as num?)?.toDouble() ?? 0;
if (end - start >= minRealChapter && start <= spoilerCap) {
// A qualifying chapter at 0:00 means the credits are baked into it
// (single-file books) - nudge past them instead.
- return start == 0 ? clampedFallback : start;
+ if (start == 0) {
+ return (
+ seconds: clampedFallback,
+ why: 'chapter[$index] qualifies but starts at 0:00, nudged past credits'
+ );
+ }
+ return (
+ seconds: start,
+ why: 'chapter[$index] is ${(end - start).toStringAsFixed(0)}s long '
+ 'and starts at ${start.toStringAsFixed(0)}s (cap ${spoilerCap.toStringAsFixed(0)}s)'
+ );
}
}
- return clampedFallback;
+ return (
+ seconds: clampedFallback,
+ why: 'no chapter >=${minRealChapter.toInt()}s starting within the first '
+ '${spoilerCap.toStringAsFixed(0)}s, fell back'
+ );
}
Future<void> _togglePreview(BuildContext context, List<dynamic> chapters, double duration) async {
final l = AppLocalizations.of(context)!;
- if (_preview?.isLoading ?? false) return;
+ if (_preview?.isLoading ?? false) {
+ // Every tap is a no-op while loading, which reads as a dead button if the
+ // audio never finishes buffering.
+ debugPrint('[Preview] book ${widget.itemId}: tap ignored, still loading');
+ return;
+ }
if (_preview?.isPlaying ?? false) {
await _preview!.stop();
return;
}
- _preview ??= BookmarkPreviewPlayer(itemId: widget.itemId, api: context.read<AuthProvider>().apiService)
+ _preview ??= BookmarkPreviewPlayer(
+ itemId: widget.itemId,
+ api: context.read<AuthProvider>().apiService,
+ label: 'book')
..clipLength = const Duration(minutes: 5)
..stopOnClipEnd = true
..addListener(_onPreviewChanged);
- final startAt = _previewStartSeconds(chapters, duration);
- debugPrint('[BookDetail] preview start at ${startAt.toStringAsFixed(1)}s of ${duration.toStringAsFixed(0)}s');
+ final pick = _previewStartSeconds(chapters, duration);
+ debugPrint('[Preview] book ${widget.itemId}: start ${pick.seconds.toStringAsFixed(1)}s '
+ 'of ${duration.toStringAsFixed(0)}s across ${chapters.length} chapters - ${pick.why}');
try {
- await _preview!.toggleAt(startAt);
+ await _preview!.toggleAt(pick.seconds);
} catch (e) {
- debugPrint('[BookDetail] preview failed: $e');
+ debugPrint('[Preview] book ${widget.itemId}: failed: $e');
// stop() resumes the main book we paused and resets for a retry.
await _preview?.stop();
if (mounted) {
diff --git a/lib/widgets/bookmark_detail_dialog.dart b/lib/widgets/bookmark_detail_dialog.dart
index e0e032da..f5e6362c 100644
--- a/lib/widgets/bookmark_detail_dialog.dart
+++ b/lib/widgets/bookmark_detail_dialog.dart
@@ -52,7 +52,8 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
// Clamp a stray negative position to 0 so it shows 0:00 (not "59:59") and
// self-heals to 0 if the user saves.
_seconds = widget.bookmark.positionSeconds < 0 ? 0.0 : widget.bookmark.positionSeconds;
- _preview = BookmarkPreviewPlayer(itemId: widget.itemId, api: widget.api)
+ _preview = BookmarkPreviewPlayer(
+ itemId: widget.itemId, api: widget.api, label: 'bookmark')
..clipLength = const Duration(seconds: 60)
..addListener(_onPreview);
}
@@ -89,7 +90,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
try {
await _preview.toggleAt(_seconds);
} catch (e) {
- debugPrint('[BookmarkPreview] toggle failed: $e');
+ debugPrint('[Preview] bookmark ${widget.itemId}: toggle failed: $e');
// stop() resumes the main book we paused and resets for a retry.
await _preview.stop();
if (!mounted) return;