perf(player): send the session queue only to Android, newest first

audio_service mapped and encoded the whole play queue for the platform
on every queue change, on every platform. Only the Android plugin reads
it: the darwin plugin answers setQueue with an empty result, the web
plugin and the desktop SMTC and MPRIS sessions are no-ops. With a
20,000-song Shuffle Library queue that is about 10 MB and 60 ms (host
JIT) of UI isolate work per change, plus a main-thread decode on iOS
and macOS, all of it discarded.

_observeQueue now skips the queue off Android, and on Android keeps
only the newest queue while a setQueue is in flight. That queue goes
out when the in-flight call completes or fails, at the same point the
old loop sent its next buffered change, so Android always ends on the
latest queue and its order against setMediaItem and setState is kept.
An idle change is still sent at once, with the same payload.

Host benchmark, 20,000 songs per queue: iOS, macOS and Windows go from
one 10.1 MB send (about 61 ms) per change to none; six changes during
one Android send go from six sends (60.5 MB, 383 ms) to two (20.2 MB,
128 ms). The patch is recorded in MORNYE_PATCHES.md.
This commit is contained in:
zarzet committed 2026-10-30 20:39:39 +07:00
1 parent aec7ab9539
commit 4eaa5eff0a
3 files changed
+243 -7

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:audio_service_platform_interface/audio_service_platform_interface.dart';
import 'package:audio_service_platform_interface/no_op_audio_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_test/flutter_test.dart';
class _Cache implements BaseCacheManager {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _RecordingPlatform extends NoOpAudioService {
final log = <String>[];
final queues = <List<MediaItemMessage>>[];
final items = <MediaItemMessage>[];
final _queueReplies = <Completer<void>>[];
bool holdQueue = false;
@override
Future<void> setQueue(SetQueueRequest request) {
queues.add(request.queue);
log.add('queue ${request.queue.map((item) => item.id).join(',')}');
if (!holdQueue) return Future<void>.value();
final reply = Completer<void>();
_queueReplies.add(reply);
return reply.future;
}
@override
Future<void> setMediaItem(SetMediaItemRequest request) {
items.add(request.mediaItem);
log.add('item ${request.mediaItem.id}');
return Future<void>.value();
}
@override
Future<void> setState(SetStateRequest request) {
log.add('state ${request.state.processingState.name}');
return Future<void>.value();
}
void replyQueue([Object? error]) {
final reply = _queueReplies.removeAt(0);
if (error == null) {
reply.complete();
} else {
reply.completeError(error);
}
}
void reset() {
expect(_queueReplies, isEmpty);
log.clear();
queues.clear();
items.clear();
holdQueue = false;
}
}
List<MediaItem> _songs(int count) => [
for (var index = 0; index < count; index++)
MediaItem(
id: 'song-$index',
title: 'Song $index',
artist: 'Artist',
album: 'Album',
duration: Duration(seconds: 180 + index),
extras: {'path': '/music/song-$index.flac', 'bitrate': 1411},
),
];
List<MediaItem> _queue(String id) => [MediaItem(id: id, title: 'Song $id')];
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final platform = _RecordingPlatform();
final errors = <Object>[];
late BaseAudioHandler handler;
setUpAll(() async {
AudioServicePlatform.instance = platform;
handler = await AudioService.init(
builder: BaseAudioHandler.new,
cacheManager: _Cache(),
);
AudioService.asyncError.listen(errors.add);
await pumpEventQueue();
});
setUp(() {
platform.reset();
errors.clear();
});
tearDown(() => debugDefaultTargetPlatformOverride = null);
test('Android receives the whole queue on every change', () async {
final songs = _songs(1000);
handler.queue.add(songs);
await pumpEventQueue();
handler.queue.add(songs.sublist(1));
await pumpEventQueue();
handler.mediaItem.add(songs.first);
await pumpEventQueue();
expect(platform.queues, hasLength(2));
expect(
platform.queues.first.map((item) => item.id),
songs.map((song) => song.id),
);
expect(platform.queues.last, hasLength(999));
expect(platform.queues.first.first.toMap(), platform.items.single.toMap());
expect(platform.queues.first.last.extras, {
'path': '/music/song-999.flac',
'bitrate': 1411,
});
});
for (final target in [
TargetPlatform.iOS,
TargetPlatform.macOS,
TargetPlatform.windows,
TargetPlatform.linux,
TargetPlatform.fuchsia,
]) {
test('${target.name} receives no queue', () async {
debugDefaultTargetPlatformOverride = target;
handler.queue.add(_songs(1000));
handler.mediaItem.add(_queue('current').single);
handler.queue.add(_songs(10));
await pumpEventQueue();
expect(platform.queues, isEmpty);
expect(platform.log, ['item current']);
});
}
test('a burst during a send sends only the newest queue next', () async {
platform.holdQueue = true;
handler.queue.add(_queue('q1'));
await pumpEventQueue();
for (final id in ['q2', 'q3', 'q4']) {
handler.queue.add(_queue(id));
}
await pumpEventQueue();
expect(platform.log, ['queue q1']);
platform.replyQueue();
await pumpEventQueue();
expect(platform.log, ['queue q1', 'queue q4']);
handler.queue.add(_queue('q5'));
handler.queue.add(_queue('q6'));
await pumpEventQueue();
platform.replyQueue(PlatformException(code: 'failed'));
await pumpEventQueue();
expect(platform.log, ['queue q1', 'queue q4', 'queue q6']);
expect(errors.single, isA<PlatformException>());
platform.replyQueue();
await pumpEventQueue();
expect(platform.log, hasLength(3));
handler.queue.add(_queue('q7'));
await pumpEventQueue();
expect(platform.log.last, 'queue q7');
platform.replyQueue();
await pumpEventQueue();
});
test('the newest queue keeps its place among item and state calls', () async {
platform.holdQueue = true;
handler.queue.add(_queue('q1'));
await pumpEventQueue();
handler.queue.add(_queue('q2'));
handler.mediaItem.add(_queue('m2').single);
handler.queue.add(_queue('q3'));
handler.playbackState.add(
PlaybackState(processingState: AudioProcessingState.buffering),
);
await pumpEventQueue();
platform.replyQueue();
await pumpEventQueue();
platform.replyQueue();
await pumpEventQueue();
platform.holdQueue = false;
handler.queue.add(_queue('q4'));
handler.mediaItem.add(_queue('m4').single);
await pumpEventQueue();
expect(platform.log, [
'queue q1',
'item m2',
'state buffering',
'queue q3',
'queue q4',
'item m4',
]);
});
}
+14
View File
@@ -85,6 +85,20 @@ from the upstream package are not vendored.
`lib/audio_service.dart` adds `AudioService.refreshNowPlayingInfo()`, which
calls the new `refreshNowPlayingInfo` method in AudioServicePlugin.m;
`lib/services/music_player_service.dart` in the app calls it.
- Dart: `_observeQueue` in `lib/audio_service.dart` sends the queue to the
platform only on Android, the only plugin that reads it. The darwin plugin
answers `setQueue` with `@{}` and drops it, the web plugin's `setQueue` is
a no-op, and the app's desktop sessions (SMTC, MPRIS) inherit the no-op of
`NoOpAudioService`, yet each queue change mapped and encoded every item
(about 10 MB for 20,000 songs). `preloadArtwork` still runs on every
platform. On Android an idle change is sent at once; while a `setQueue` is
in flight, later changes keep only the newest queue, which is sent as soon
as the in-flight call completes or fails, so the native queue always ends
on the latest change and keeps its place among `setMediaItem` and
`setState` calls. The payload and the full queue are unchanged. The app's
`test/audio_service_queue_platform_test.dart` covers it. On upgrade, check
whether upstream now reads the queue on another platform (then widen the
check) or coalesces queue sends itself.
Android 13+ still chooses the positions and built-in transport icons in System
UI. We preserve real play/pause/previous/next semantics for headsets, lock screen
+25 -7
View File
@@ -1113,17 +1113,35 @@ class AudioService {
}
static Future<void> _observeQueue() async {
await for (var queue in _handler.queue) {
List<MediaItem>? pendingQueue;
var sendingQueue = false;
_handler.queue.listen((queue) async {
if (_config.preloadArtwork) {
_loadAllArtwork(queue);
}
try {
await _platform.setQueue(SetQueueRequest(
queue: queue.map((item) => item._toMessage()).toList()));
} catch (e) {
_asyncError.add(e);
// Only the Android plugin reads the queue; the darwin and web plugins
// and the desktop sessions ignore it.
if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) {
return;
}
}
if (sendingQueue) {
pendingQueue = queue;
return;
}
sendingQueue = true;
List<MediaItem>? next = queue;
while (next != null) {
try {
await _platform.setQueue(SetQueueRequest(
queue: next.map((item) => item._toMessage()).toList()));
} catch (e) {
_asyncError.add(e);
}
next = pendingQueue;
pendingQueue = null;
}
sendingQueue = false;
});
}
static Future<void> _observePlaybackState() async {