diff --git a/lib/controllers/queue_library_refresh_policy.dart b/lib/controllers/queue_library_refresh_policy.dart index 6c4e3d79a..98eb7b214 100644 --- a/lib/controllers/queue_library_refresh_policy.dart +++ b/lib/controllers/queue_library_refresh_policy.dart @@ -1,10 +1,12 @@ import 'dart:async'; +import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:mornye/utils/audio_format_utils.dart'; import 'package:mornye/utils/audio_quality_badge_policy.dart'; import 'package:mornye/services/downloaded_embedded_cover_resolver.dart'; import 'package:mornye/services/library_database.dart'; +import 'package:mornye/services/platform_bridge.dart'; import 'package:mornye/utils/file_access.dart'; bool queueLibraryCountsHaveContent(QueueLibraryCounts counts) => @@ -128,6 +130,10 @@ typedef LibraryFilePathNormalizer = String Function(String? path); /// rebuilt (for example after returning from the Metadata screen). class LibraryFileAvailabilityCache { static const int _defaultMaxEntries = 500; + static const int _maxResultEntries = 5000; + static const int _safBatchSize = 64; + static const int _maxConcurrentLocalProbes = 8; + static const Duration _foundRecheckAfter = Duration(minutes: 5); static const List _defaultRetryDelays = [ Duration(milliseconds: 350), Duration(milliseconds: 700), @@ -140,12 +146,14 @@ class LibraryFileAvailabilityCache { final List _retryDelays; final Duration _missingRecheckAfter; final int _maxEntries; - final Map _cache = {}; + final LinkedHashMap _cache = LinkedHashMap(); final Map _checkedAt = {}; final Map _notifiers = {}; final Map _retryTimers = {}; final Map _generations = {}; final Set _probingPaths = {}; + final Map _pendingProbes = {}; + Timer? _flushTimer; final ValueNotifier _alwaysMissingNotifier = ValueNotifier(false); bool _disposed = false; @@ -167,9 +175,9 @@ class LibraryFileAvailabilityCache { final path = _normalizePath(filePath); if (path.isEmpty || _disposed) return _alwaysMissingNotifier; + final cached = _cache[path]; final existingNotifier = _notifiers[path]; if (existingNotifier != null) { - final cached = _cache[path]; if (cached != null && existingNotifier.value != cached) { existingNotifier.value = cached; } @@ -184,9 +192,15 @@ class LibraryFileAvailabilityCache { } _evictUnusedEntriesIfNeeded(); - final notifier = _LibraryFileAvailabilityNotifier(_cache[path] ?? true); + final notifier = _LibraryFileAvailabilityNotifier(cached ?? true); _notifiers[path] = notifier; - _beginProbe(path); + if (cached == null) { + _beginProbe(path); + } else if (cached ? _foundIsStale(path) : _confirmedMissIsStale(path)) { + _beginProbe(path, force: true); + } else { + _touchCachedResult(path, cached); + } return notifier; } @@ -207,27 +221,51 @@ class LibraryFileAvailabilityCache { _generations[path] = (_generations[path] ?? 0) + 1; _retryTimers.remove(path)?.cancel(); + _pendingProbes.remove(path); _probingPaths.remove(path); - _cache[path] = true; - _checkedAt[path] = DateTime.now(); + _recordResult(path, true); final notifier = _notifiers[path]; if (notifier != null && !notifier.value) { notifier.value = true; } } + void _touchCachedResult(String path, bool exists) { + _cache.remove(path); + _cache[path] = exists; + } + + void _recordResult(String path, bool exists) { + _touchCachedResult(path, exists); + _checkedAt[path] = DateTime.now(); + while (_cache.length > _maxResultEntries) { + final oldest = _cache.keys.first; + _cache.remove(oldest); + _checkedAt.remove(oldest); + } + } + bool _confirmedMissIsStale(String path) { final checkedAt = _checkedAt[path]; return checkedAt == null || DateTime.now().difference(checkedAt) >= _missingRecheckAfter; } + /// A found file is checked again when its card returns after this long, so + /// one deleted outside the app does not stay playable for the session. + bool _foundIsStale(String path) { + final checkedAt = _checkedAt[path]; + return checkedAt == null || + DateTime.now().difference(checkedAt) >= _foundRecheckAfter; + } + void _beginProbe(String path, {bool force = false, bool optimistic = false}) { if (_disposed || (!force && _probingPaths.contains(path))) return; final generation = (_generations[path] ?? 0) + 1; _generations[path] = generation; _retryTimers.remove(path)?.cancel(); + _pendingProbes.remove(path); _probingPaths.add(path); _cache.remove(path); _checkedAt.remove(path); @@ -235,18 +273,125 @@ class LibraryFileAvailabilityCache { final notifier = _notifiers[path]; if (notifier != null && !notifier.value) notifier.value = true; } - unawaited(_probe(path, generation: generation, attempt: 0)); + _enqueueProbe(path, generation: generation, attempt: 0); } - Future _probe( + void _enqueueProbe( String path, { required int generation, required int attempt, - }) async { - var exists = false; - try { - exists = await _pathExists(path); - } catch (_) {} + }) { + if (_disposed || _generations[path] != generation) return; + _pendingProbes[path] = (generation: generation, attempt: attempt); + _flushTimer ??= Timer(Duration.zero, _flushPendingProbes); + } + + void _flushPendingProbes() { + _flushTimer = null; + if (_disposed || _pendingProbes.isEmpty) return; + + final batch = Map.of( + _pendingProbes, + ); + _pendingProbes.clear(); + + final canBatchSaf = identical(_pathExists, fileExists); + final safEntries = >[]; + final singleEntries = >[]; + for (final entry in batch.entries) { + if (_generations[entry.key] != entry.value.generation) continue; + if (canBatchSaf && isContentUri(entry.key)) { + safEntries.add(entry); + } else { + singleEntries.add(entry); + } + } + + if (safEntries.isNotEmpty) { + unawaited(_probeSafBatch(safEntries)); + } + if (singleEntries.isNotEmpty) { + unawaited(_probeSingleBatch(singleEntries)); + } + } + + Future _probeSafBatch( + List> entries, + ) async { + for (var i = 0; i < entries.length; i += _safBatchSize) { + if (_disposed) return; + final end = i + _safBatchSize > entries.length + ? entries.length + : i + _safBatchSize; + final chunk = entries.sublist(i, end); + // A CUE track is checked against its backing file, as fileExists does. + final uris = { + for (final entry in chunk) stripCueTrackSuffix(entry.key), + }.toList(growable: false); + Map? results; + try { + results = await PlatformBridge.safExistsBatch(uris); + } catch (_) {} + if (_disposed) return; + + final fallback = >[]; + for (final entry in chunk) { + if (_generations[entry.key] != entry.value.generation) continue; + final exists = results?[stripCueTrackSuffix(entry.key)]; + if (exists != null) { + _handleProbeResult( + entry.key, + generation: entry.value.generation, + attempt: entry.value.attempt, + exists: exists, + ); + } else { + fallback.add(entry); + } + } + if (fallback.isNotEmpty) { + await _probeSingleBatch(fallback); + } + } + } + + Future _probeSingleBatch( + List> entries, + ) async { + var cursor = 0; + final workers = entries.length < _maxConcurrentLocalProbes + ? entries.length + : _maxConcurrentLocalProbes; + Future worker() async { + while (!_disposed) { + if (cursor >= entries.length) return; + final entry = entries[cursor++]; + final path = entry.key; + final generation = entry.value.generation; + if (_generations[path] != generation) continue; + var exists = false; + try { + exists = await _pathExists(path); + } catch (_) {} + if (_disposed || _generations[path] != generation) continue; + _handleProbeResult( + path, + generation: generation, + attempt: entry.value.attempt, + exists: exists, + ); + } + } + + await Future.wait([for (var i = 0; i < workers; i++) worker()]); + } + + void _handleProbeResult( + String path, { + required int generation, + required int attempt, + required bool exists, + }) { if (_disposed || _generations[path] != generation) return; if (exists) { @@ -258,14 +403,13 @@ class LibraryFileAvailabilityCache { _retryTimers[path] = Timer(_retryDelays[attempt], () { _retryTimers.remove(path); if (_disposed || _generations[path] != generation) return; - unawaited(_probe(path, generation: generation, attempt: attempt + 1)); + _enqueueProbe(path, generation: generation, attempt: attempt + 1); }); return; } _probingPaths.remove(path); - _cache[path] = false; - _checkedAt[path] = DateTime.now(); + _recordResult(path, false); final notifier = _notifiers[path]; if (notifier != null && notifier.value) notifier.value = false; } @@ -280,15 +424,14 @@ class LibraryFileAvailabilityCache { } } if (evictionPath == null) return; - _removeEntry(evictionPath); + _removeNotifierOnly(evictionPath); } } - void _removeEntry(String path) { + void _removeNotifierOnly(String path) { _retryTimers.remove(path)?.cancel(); + _pendingProbes.remove(path); _probingPaths.remove(path); - _cache.remove(path); - _checkedAt.remove(path); _generations.remove(path); _notifiers.remove(path)?.dispose(); } @@ -296,6 +439,9 @@ class LibraryFileAvailabilityCache { void dispose() { if (_disposed) return; _disposed = true; + _flushTimer?.cancel(); + _flushTimer = null; + _pendingProbes.clear(); for (final timer in _retryTimers.values) { timer.cancel(); }