From 27d2be1633ac86cceb4e60dbd0f2a6cfd0079aff Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:30:13 +0700 Subject: [PATCH] perf(player): load media session art from the app cover cache audio_service was initialized without a cache manager, so it made its own DefaultCacheManager: every web cover the notification or lock screen showed was downloaded again and stored again in the temporary directory, beside the copy the app's cover cache already held, and its memory never had the cover the player had just drawn, so the session first got the song without art and again after the download. MediaSessionArtCache resolves the app's cover cache on each call once it is ready, and the default cache before that, so a session that starts before the app shell (Android Auto) behaves as before. Awaiting CoverCacheManager.initialize() in the player init instead would race the app shell's own call and could create two managers over one cover index. The cover cache's byte budget deletes files its memory cache still lists, so a memory hit whose file is gone counts as a miss and the cover is fetched again instead of reaching the OS as a dead path. Test: with the app's cover already cached, the session's media item carries that file and the server sees one request, not two; after the file is deleted under the memory entry, the session fetches it again and gets a file that exists. Same bytes, same pixels. --- lib/services/media_session_art_cache.dart | 121 ++++++++++++++++++++++ lib/services/music_player_runtime.dart | 2 + test/media_session_art_cache_test.dart | 114 ++++++++++++++++++++ 3 files changed, 237 insertions(+) create mode 100644 lib/services/media_session_art_cache.dart create mode 100644 test/media_session_art_cache_test.dart diff --git a/lib/services/media_session_art_cache.dart b/lib/services/media_session_art_cache.dart new file mode 100644 index 000000000..fec0cdae3 --- /dev/null +++ b/lib/services/media_session_art_cache.dart @@ -0,0 +1,121 @@ +import 'dart:typed_data'; + +import 'package:flutter_cache_manager/file.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'package:mornye/services/cover_cache_manager.dart'; + +/// Where the system media session finds a song's web cover: the app's cover +/// cache once it is ready, so a cover the app already fetched is neither +/// downloaded nor stored again, and the default cache until then. +class MediaSessionArtCache implements BaseCacheManager { + MediaSessionArtCache({CacheManager Function()? cache}) + : _cache = cache ?? _covers; + + final CacheManager Function() _cache; + + static CacheManager _covers() => CoverCacheManager.isInitialized + ? CoverCacheManager.instance + : DefaultCacheManager(); + + /// The cover cache's byte budget deletes files its memory still lists. + @override + Future getFileFromMemory(String key) async { + final info = await _cache().getFileFromMemory(key); + return info != null && await info.file.exists() ? info : null; + } + + @override + Future getSingleFile( + String url, { + String? key, + Map? headers, + }) => _cache().getSingleFile(url, key: key, headers: headers); + + @override + @Deprecated('Prefer to use the new getFileStream method') + Stream getFile( + String url, { + String? key, + Map? headers, + }) => getFileStream( + url, + key: key, + headers: headers, + ).where((response) => response is FileInfo).cast(); + + @override + Stream getFileStream( + String url, { + String? key, + Map? headers, + bool withProgress = false, + }) => _cache().getFileStream( + url, + key: key, + headers: headers, + withProgress: withProgress, + ); + + @override + Future downloadFile( + String url, { + String? key, + Map? authHeaders, + bool force = false, + }) => _cache().downloadFile( + url, + key: key, + authHeaders: authHeaders, + force: force, + ); + + @override + Future getFileFromCache( + String key, { + bool ignoreMemCache = false, + }) => _cache().getFileFromCache(key, ignoreMemCache: ignoreMemCache); + + @override + Future putFile( + String url, + Uint8List fileBytes, { + String? key, + String? eTag, + Duration maxAge = const Duration(days: 30), + String fileExtension = 'file', + }) => _cache().putFile( + url, + fileBytes, + key: key, + eTag: eTag, + maxAge: maxAge, + fileExtension: fileExtension, + ); + + @override + Future putFileStream( + String url, + Stream> source, { + String? key, + String? eTag, + Duration maxAge = const Duration(days: 30), + String fileExtension = 'file', + }) => _cache().putFileStream( + url, + source, + key: key, + eTag: eTag, + maxAge: maxAge, + fileExtension: fileExtension, + ); + + @override + Future removeFile(String key) => _cache().removeFile(key); + + @override + Future emptyCache() => _cache().emptyCache(); + + /// The caches behind it belong to the app. + @override + Future dispose() async {} +} diff --git a/lib/services/music_player_runtime.dart b/lib/services/music_player_runtime.dart index 58697591d..6439bc8d0 100644 --- a/lib/services/music_player_runtime.dart +++ b/lib/services/music_player_runtime.dart @@ -22,6 +22,7 @@ import 'package:mornye/services/library_database.dart'; import 'package:mornye/services/listening_statistics.dart'; import 'package:mornye/services/media_kit_playback_deck.dart'; import 'package:mornye/services/media_library_browser.dart'; +import 'package:mornye/services/media_session_art_cache.dart'; import 'package:mornye/services/media_session_desktop.dart'; import 'package:mornye/services/media_session_filter.dart'; import 'package:mornye/services/music_playback_deck.dart'; @@ -207,6 +208,7 @@ class PlaybackDependencies { final session = await AudioService.init( // The switch lets a remote device take over the system session. builder: () => SwitchAudioHandler(handler = builder()), + cacheManager: MediaSessionArtCache(), config: const AudioServiceConfig( androidNotificationChannelId: 'com.zarz.mornye.playback', androidNotificationChannelName: 'Playback', diff --git a/test/media_session_art_cache_test.dart b/test/media_session_art_cache_test.dart new file mode 100644 index 000000000..db0e20135 --- /dev/null +++ b/test/media_session_art_cache_test.dart @@ -0,0 +1,114 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:audio_service/audio_service.dart'; +import 'package:audio_service_platform_interface/audio_service_platform_interface.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/services/cover_cache_manager.dart'; +import 'package:mornye/services/media_session_art_cache.dart'; + +class _CacheBinding extends AutomatedTestWidgetsFlutterBinding { + @override + bool get overrideHttpClient => false; +} + +/// The OS end of the session, passing on the media items it is sent. +class _Os extends AudioServicePlatform { + final items = StreamController.broadcast(sync: true); + + @override + Future configure(ConfigureRequest request) async {} + + @override + Future setState(SetStateRequest request) async {} + + @override + Future setQueue(SetQueueRequest request) async {} + + @override + Future setMediaItem(SetMediaItemRequest request) async => + items.add(request.mediaItem); + + @override + Future setAndroidPlaybackInfo( + SetAndroidPlaybackInfoRequest request, + ) async {} + + @override + void setHandlerCallbacks(AudioHandlerCallbacks callbacks) {} +} + +void main() { + _CacheBinding(); + + test('the media session takes web covers from the app cover cache', () async { + final directory = await Directory.systemTemp.createTemp('session-art-'); + const channel = MethodChannel('plugins.flutter.io/path_provider'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (_) async => directory.path); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final os = _Os(); + final original = AudioServicePlatform.instance; + BaseAudioHandler? handler; + addTearDown(() async { + AudioServicePlatform.instance = original; + await handler?.playbackState.close(); + await handler?.queue.close(); + await handler?.mediaItem.close(); + await os.items.close(); + await server.close(force: true); + await CoverCacheManager.instance.dispose(); + messenger.setMockMethodCallHandler(channel, null); + await directory.delete(recursive: true); + }); + final cover = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6qVQAAAAASUVORK5CYII=', + ); + var downloads = 0; + server.listen((request) async { + downloads++; + request.response + ..headers.contentType = ContentType('image', 'png') + ..headers.set(HttpHeaders.cacheControlHeader, 'max-age=3600') + ..add(cover); + await request.response.close(); + }); + final url = 'http://127.0.0.1:${server.port}/cover.png'; + await CoverCacheManager.initialize(); + // The app shows the cover first, from its cover cache. + final shown = await CoverCacheManager.instance.getSingleFile(url); + expect(downloads, 1); + + AudioServicePlatform.instance = os; + handler = await AudioService.init( + builder: BaseAudioHandler.new, + cacheManager: MediaSessionArtCache(), + ); + Future artwork(String id) => os.items.stream + .firstWhere( + (item) => item.id == id && item.extras?['artCacheFile'] != null, + ) + .timeout(const Duration(seconds: 10)); + + final first = artwork('one'); + handler.mediaItem.add( + MediaItem(id: 'one', title: 'One', artUri: Uri.parse(url)), + ); + expect((await first).extras!['artCacheFile'], shown.path); + expect(downloads, 1); + + // The cover cache's byte budget deleted the file; its memory still + // lists it, so the session fetches it again rather than lose it. + await shown.delete(); + final second = artwork('two'); + handler.mediaItem.add( + MediaItem(id: 'two', title: 'Two', artUri: Uri.parse(url)), + ); + final path = (await second).extras!['artCacheFile'] as String; + expect(File(path).existsSync(), isTrue); + expect(downloads, 2); + }); +}