fix(usb): fetch a network song whole before it plays, so it keeps the USB output

The USB output opens whole local files only. A network song (NAS, server or
a computer through Link) without a copy in the prefetch cache streamed, and
a stream plays through Android's mixer: no exclusive access, and at whatever
level the DAC was left on. The cache only holds the next two songs and starts
after three seconds of play, so a tapped or skipped-to song, and any large
song still downloading when its turn came, lost the output. A tester's log
shows exactly that: "USB output not used: this song streams" after each
skip, on songs of every sample rate.

With USB bit-perfect on and its output connected, such a song now downloads
ahead of its neighbours and starts from the copy. It streams as before when
the copy cannot be kept (too large, no file extension), the download fails,
60 seconds pass, or no output is connected, which the new outputPresent
query answers so playing without a DAC does not wait. A newer play request
ends the wait at once. Waits of half a second or more, and every fallback,
are logged.
This commit is contained in:
zarzet committed 2026-11-19 17:33:57 +07:00
1 parent 0e41ff595d
commit a4605cbdfc
7 files changed
+236

No files matched your search

@@ -1,6 +1,7 @@
package com.zarz.mornye package com.zarz.mornye
import android.content.Context import android.content.Context
import android.hardware.usb.UsbManager
import android.media.AudioAttributes import android.media.AudioAttributes
import android.media.AudioDeviceInfo import android.media.AudioDeviceInfo
import android.media.AudioFormat import android.media.AudioFormat
@@ -59,7 +60,26 @@ class UsbBitPerfectPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, Even
spatialAudio.setStreamHandler(SpatialAudioEvents(appContext).also { spatialAudioEvents = it }) spatialAudio.setStreamHandler(SpatialAudioEvents(appContext).also { spatialAudioEvents = it })
} }
/** Whether a USB audio output is attached, by either view Android offers. */
private fun usbOutputPresent(): Boolean {
val audio = appContext.getSystemService(AudioManager::class.java)
if (audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS).any {
it.type == AudioDeviceInfo.TYPE_USB_DEVICE || it.type == AudioDeviceInfo.TYPE_USB_HEADSET
}) return true
return appContext.getSystemService(UsbManager::class.java).deviceList.values.any { device ->
(0 until device.interfaceCount).any {
device.getInterface(it).interfaceClass == 1 && device.getInterface(it).interfaceSubclass == 2
}
}
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "outputPresent") {
// AAudio exclusive opens the phone's own output; an unreadable answer counts as present.
val phoneOutput = call.argument<Boolean>("direct") != true && call.argument<Boolean>("dapExclusive") == true
result.success(phoneOutput || runCatching { usbOutputPresent() }.getOrDefault(true))
return
}
if (call.method == "prepare") { if (call.method == "prepare") {
if (useHiRes) hiRes?.command(MethodCall("stop", null)) { _, _ -> } if (useHiRes) hiRes?.command(MethodCall("stop", null)) { _, _ -> }
else if (useDirect) direct?.command(MethodCall("stop", null)) { _, _ -> } else if (useDirect) direct?.command(MethodCall("stop", null)) { _, _ -> }
+19
View File
@@ -267,6 +267,25 @@ class AudioplayersPlaybackDeck implements PlaybackDeck {
} on MissingPluginException catch (_) {} } on MissingPluginException catch (_) {}
} }
/// Whether the output a bit-perfect song would open is connected. True
/// when the platform cannot say.
static Future<bool> bitPerfectOutputPresent({
required bool directUsb,
required bool dapExclusive,
}) async {
try {
return await _channel.invokeMethod<bool>('outputPresent', {
'direct': directUsb,
'dapExclusive': dapExclusive,
}) ??
true;
} on PlatformException catch (_) {
return true;
} on MissingPluginException catch (_) {
return true;
}
}
static Stream<dynamic>? _nativeEvents; static Stream<dynamic>? _nativeEvents;
static int _nextToken = 0; static int _nextToken = 0;
final AudioPlayer _ordinary; final AudioPlayer _ordinary;
+31
View File
@@ -13,6 +13,10 @@ class _MusicPrefetch {
/// How many songs after the current one are kept. /// How many songs after the current one are kept.
static const ahead = 2; static const ahead = 2;
/// How long a song may take to arrive whole before it streams instead.
static const wholeWithin = Duration(seconds: 60);
static const _wholePoll = Duration(milliseconds: 200);
final MusicPlayerHandler handler; final MusicPlayerHandler handler;
String? _key; String? _key;
int _revision = 0; int _revision = 0;
@@ -83,6 +87,33 @@ class _MusicPrefetch {
} }
} }
/// Downloads [media] ahead of its neighbours and waits for the whole copy
/// while [current] holds. False when it has to stream instead: the copy
/// cannot be kept, its download failed, or [within] passed.
Future<bool> whole(
PlayableMedia media,
bool Function() current, {
Duration within = wholeWithin,
}) async {
final cache = _cache;
if (cache == null || !media.source.startsWith('network://')) return false;
final source = media.source;
try {
if (await cache.lookup(source) != null) return true;
if (!current()) return false;
// Drops a pending neighbour update; the next position asks again.
_revision++;
_key = null;
cache.want([source]);
final watch = Stopwatch()..start();
while (current() && watch.elapsed < within) {
if (await cache.ready(source, _wholePoll)) return true;
if (!cache.arriving(source)) return false;
}
} catch (_) {}
return false;
}
Future<String?> lookup(PlayableMedia media) async { Future<String?> lookup(PlayableMedia media) async {
final cache = _cache; final cache = _cache;
if (cache == null) return null; if (cache == null) return null;
+34
View File
@@ -1911,6 +1911,36 @@ class MusicPlayerHandler extends BaseAudioHandler
return path; return path;
} }
/// The USB output plays whole files only. With it on and its output
/// connected, a network song without a copy downloads before it starts
/// instead of streaming through Android's mixer.
Future<void> _fetchWholeForUsb(PlayableMedia media, int generation) async {
if (!_settings.usbBitPerfect ||
!_dependencies.isAndroid ||
!media.source.startsWith('network://')) {
return;
}
if (!await AudioplayersPlaybackDeck.bitPerfectOutputPresent(
directUsb: _settings.usbDirect,
dapExclusive: _settings.dapExclusive,
)) {
return;
}
if (!_isCurrentPlayRequest(generation, media)) return;
final watch = Stopwatch()..start();
final whole = await _prefetch.whole(
media,
() => _isCurrentPlayRequest(generation, media),
);
if (!_isCurrentPlayRequest(generation, media)) return;
final waited = watch.elapsedMilliseconds;
if (!whole) {
_log.w('USB output: no whole copy of this network song ($waited ms)');
} else if (waited >= 500) {
_log.i('USB output: fetched this network song whole ($waited ms)');
}
}
Future<void> _loadIndex( Future<void> _loadIndex(
int generation, int generation,
PlayableMedia media, { PlayableMedia media, {
@@ -2001,6 +2031,10 @@ class MusicPlayerHandler extends BaseAudioHandler
..fetchFor(media) ..fetchFor(media)
..fetchAhead(); ..fetchAhead();
if (playbackLease == null) {
await _fetchWholeForUsb(media, generation);
if (!_isCurrentPlayRequest(generation, media)) return;
}
var resolved = playbackLease?.path ?? await _formats.resolve(media); var resolved = playbackLease?.path ?? await _formats.resolve(media);
var usingLocalSafCopy = media.isContentUri && playbackLease == null; var usingLocalSafCopy = media.isContentUri && playbackLease == null;
if (!_isCurrentPlayRequest(generation, media)) { if (!_isCurrentPlayRequest(generation, media)) {
+8
View File
@@ -278,6 +278,14 @@ class NetworkPlaybackCache {
return waiter.future.timeout(within, onTimeout: () => false); return waiter.future.timeout(within, onTimeout: () => false);
} }
/// Whether [source] is wanted and its copy can still arrive: not stored
/// yet, and its download has not failed recently.
bool arriving(String source) =>
!_unavailable &&
_wanted.contains(source) &&
!_entries.containsKey(source) &&
!_failedRecently(source);
/// Forgets the copy of [source], as after its file was edited or deleted. /// Forgets the copy of [source], as after its file was edited or deleted.
/// A song still wanted downloads again. /// A song still wanted downloads again.
Future<void> invalidate(String source) async { Future<void> invalidate(String source) async {
+110
View File
@@ -2464,6 +2464,116 @@ void main() {
cache.want([]); cache.want([]);
}); });
group('with the USB output on', () {
const usb = MethodChannel('com.zarz.mornye/usb_pcm');
const settings = AppSettings(pauseOnMute: false, usbBitPerfect: true);
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
void outputPresent(bool present) {
messenger.setMockMethodCallHandler(
usb,
(call) async => call.method == 'outputPresent' ? present : null,
);
addTearDown(() => messenger.setMockMethodCallHandler(usb, null));
}
test('a song still downloading waits for its whole copy', () async {
outputPresent(true);
final release = Completer<void>();
final cache = await networkCache(release: release.future);
final decks = <_Deck>[];
final handler = await _runtime(
settings: settings,
isAndroid: true,
decks: decks,
networkCache: cache,
resolveNetworkSource: (_) async => 'http://127.0.0.1:1/song.flac',
).initialize();
final playing = handler.setQueueAndPlay([song]);
await Future<void>.delayed(const Duration(milliseconds: 300));
expect(decks.single.sources, isEmpty);
release.complete();
await playing;
expect(cache.owns(decks.single.sources.single), isTrue);
});
test('a song whose download fails streams', () async {
outputPresent(true);
final release = Completer<void>();
final cache = await networkCache(release: release.future);
final decks = <_Deck>[];
final handler = await _runtime(
settings: settings,
isAndroid: true,
decks: decks,
networkCache: cache,
resolveNetworkSource: (_) async => 'http://127.0.0.1:1/song.flac',
).initialize();
final playing = handler.setQueueAndPlay([song]);
await Future<void>.delayed(const Duration(milliseconds: 100));
release.completeError(StateError('server gone'));
await playing;
expect(decks.single.sources, ['stream http://127.0.0.1:1/song.flac']);
});
test('a newer song does not wait for the one before it', () async {
outputPresent(true);
final cache = await networkCache(release: Completer<void>().future);
final temp = await Directory.systemTemp.createTemp('player-local-');
addTearDown(() => temp.delete(recursive: true));
final local = await File('${temp.path}/local.flac').writeAsBytes([4]);
final decks = <_Deck>[];
final handler = await _runtime(
settings: settings,
isAndroid: true,
decks: decks,
networkCache: cache,
resolveNetworkSource: (_) async => 'http://127.0.0.1:1/song.flac',
).initialize();
unawaited(handler.setQueueAndPlay([song]));
await Future<void>.delayed(const Duration(milliseconds: 100));
await handler
.setQueueAndPlay([
PlayableMedia(
id: 'local-song',
source: local.path,
title: 'Local song',
artist: 'Artist',
),
])
.timeout(const Duration(seconds: 5));
expect(decks.single.sources, [local.path]);
cache.want([]);
});
test('without a connected output the song streams at once', () async {
outputPresent(false);
final cache = await networkCache(release: Completer<void>().future);
final decks = <_Deck>[];
final handler = await _runtime(
settings: settings,
isAndroid: true,
decks: decks,
networkCache: cache,
resolveNetworkSource: (_) async => 'http://127.0.0.1:1/song.flac',
).initialize();
await handler
.setQueueAndPlay([song])
.timeout(const Duration(seconds: 5));
expect(decks.single.sources, ['stream http://127.0.0.1:1/song.flac']);
cache.want([]);
});
});
test('a saved offline copy plays before a prefetched one', () async { test('a saved offline copy plays before a prefetched one', () async {
final cache = await networkCache(); final cache = await networkCache();
cache.want([source]); cache.want([source]);
+14
View File
@@ -194,6 +194,20 @@ void main() {
expect(await files(), isNot(contains(endsWith('.part')))); expect(await files(), isNot(contains(endsWith('.part'))));
}); });
test('a copy is arriving only while wanted and not yet stored', () async {
final release = server.hold(_a);
final subject = cache();
expect(subject.arriving(_a), isFalse);
subject.want([_a]);
await server.startedDownloading(_a);
expect(subject.arriving(_a), isTrue);
release.complete();
expect(await subject.ready(_a, _wait), isTrue);
expect(subject.arriving(_a), isFalse);
});
test('the least recently used copies go first, never a wanted one', () async { test('the least recently used copies go first, never a wanted one', () async {
final subject = cache(maxFiles: 2)..want([_a]); final subject = cache(maxFiles: 2)..want([_a]);
expect(await subject.ready(_a, _wait), isTrue); expect(await subject.ready(_a, _wait), isTrue);