mirror of
https://github.com/zarzet/SpotiFLAC-Mobile.git
synced 2026-11-21 20:00:49 +01:00
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.
This commit is contained in:
1 parent
4823a141e9
commit
27d2be1633
3 files changed
+237
No files matched your search
@@ -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<FileInfo?> getFileFromMemory(String key) async {
|
||||
final info = await _cache().getFileFromMemory(key);
|
||||
return info != null && await info.file.exists() ? info : null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<File> getSingleFile(
|
||||
String url, {
|
||||
String? key,
|
||||
Map<String, String>? headers,
|
||||
}) => _cache().getSingleFile(url, key: key, headers: headers);
|
||||
|
||||
@override
|
||||
@Deprecated('Prefer to use the new getFileStream method')
|
||||
Stream<FileInfo> getFile(
|
||||
String url, {
|
||||
String? key,
|
||||
Map<String, String>? headers,
|
||||
}) => getFileStream(
|
||||
url,
|
||||
key: key,
|
||||
headers: headers,
|
||||
).where((response) => response is FileInfo).cast<FileInfo>();
|
||||
|
||||
@override
|
||||
Stream<FileResponse> getFileStream(
|
||||
String url, {
|
||||
String? key,
|
||||
Map<String, String>? headers,
|
||||
bool withProgress = false,
|
||||
}) => _cache().getFileStream(
|
||||
url,
|
||||
key: key,
|
||||
headers: headers,
|
||||
withProgress: withProgress,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<FileInfo> downloadFile(
|
||||
String url, {
|
||||
String? key,
|
||||
Map<String, String>? authHeaders,
|
||||
bool force = false,
|
||||
}) => _cache().downloadFile(
|
||||
url,
|
||||
key: key,
|
||||
authHeaders: authHeaders,
|
||||
force: force,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<FileInfo?> getFileFromCache(
|
||||
String key, {
|
||||
bool ignoreMemCache = false,
|
||||
}) => _cache().getFileFromCache(key, ignoreMemCache: ignoreMemCache);
|
||||
|
||||
@override
|
||||
Future<File> 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<File> putFileStream(
|
||||
String url,
|
||||
Stream<List<int>> 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<void> removeFile(String key) => _cache().removeFile(key);
|
||||
|
||||
@override
|
||||
Future<void> emptyCache() => _cache().emptyCache();
|
||||
|
||||
/// The caches behind it belong to the app.
|
||||
@override
|
||||
Future<void> dispose() async {}
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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<MediaItemMessage>.broadcast(sync: true);
|
||||
|
||||
@override
|
||||
Future<void> configure(ConfigureRequest request) async {}
|
||||
|
||||
@override
|
||||
Future<void> setState(SetStateRequest request) async {}
|
||||
|
||||
@override
|
||||
Future<void> setQueue(SetQueueRequest request) async {}
|
||||
|
||||
@override
|
||||
Future<void> setMediaItem(SetMediaItemRequest request) async =>
|
||||
items.add(request.mediaItem);
|
||||
|
||||
@override
|
||||
Future<void> 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<MediaItemMessage> 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);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user