diff --git a/android/app/src/main/kotlin/com/zarz/mornye/UsbBitPerfectPlugin.kt b/android/app/src/main/kotlin/com/zarz/mornye/UsbBitPerfectPlugin.kt index 5ab62c8eb..42e88183a 100644 --- a/android/app/src/main/kotlin/com/zarz/mornye/UsbBitPerfectPlugin.kt +++ b/android/app/src/main/kotlin/com/zarz/mornye/UsbBitPerfectPlugin.kt @@ -1,6 +1,7 @@ package com.zarz.mornye import android.content.Context +import android.hardware.usb.UsbManager import android.media.AudioAttributes import android.media.AudioDeviceInfo import android.media.AudioFormat @@ -59,7 +60,26 @@ class UsbBitPerfectPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, Even 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) { + if (call.method == "outputPresent") { + // AAudio exclusive opens the phone's own output; an unreadable answer counts as present. + val phoneOutput = call.argument("direct") != true && call.argument("dapExclusive") == true + result.success(phoneOutput || runCatching { usbOutputPresent() }.getOrDefault(true)) + return + } if (call.method == "prepare") { if (useHiRes) hiRes?.command(MethodCall("stop", null)) { _, _ -> } else if (useDirect) direct?.command(MethodCall("stop", null)) { _, _ -> } diff --git a/lib/services/music_playback_deck.dart b/lib/services/music_playback_deck.dart index d49e064ec..597bf0e27 100644 --- a/lib/services/music_playback_deck.dart +++ b/lib/services/music_playback_deck.dart @@ -267,6 +267,25 @@ class AudioplayersPlaybackDeck implements PlaybackDeck { } on MissingPluginException catch (_) {} } + /// Whether the output a bit-perfect song would open is connected. True + /// when the platform cannot say. + static Future bitPerfectOutputPresent({ + required bool directUsb, + required bool dapExclusive, + }) async { + try { + return await _channel.invokeMethod('outputPresent', { + 'direct': directUsb, + 'dapExclusive': dapExclusive, + }) ?? + true; + } on PlatformException catch (_) { + return true; + } on MissingPluginException catch (_) { + return true; + } + } + static Stream? _nativeEvents; static int _nextToken = 0; final AudioPlayer _ordinary; diff --git a/lib/services/music_player_prefetch.dart b/lib/services/music_player_prefetch.dart index 4389c8956..e0e7abb65 100644 --- a/lib/services/music_player_prefetch.dart +++ b/lib/services/music_player_prefetch.dart @@ -13,6 +13,10 @@ class _MusicPrefetch { /// How many songs after the current one are kept. 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; String? _key; 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 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 lookup(PlayableMedia media) async { final cache = _cache; if (cache == null) return null; diff --git a/lib/services/music_player_service.dart b/lib/services/music_player_service.dart index 342f8429f..0b247325d 100644 --- a/lib/services/music_player_service.dart +++ b/lib/services/music_player_service.dart @@ -1911,6 +1911,36 @@ class MusicPlayerHandler extends BaseAudioHandler 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 _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 _loadIndex( int generation, PlayableMedia media, { @@ -2001,6 +2031,10 @@ class MusicPlayerHandler extends BaseAudioHandler ..fetchFor(media) ..fetchAhead(); + if (playbackLease == null) { + await _fetchWholeForUsb(media, generation); + if (!_isCurrentPlayRequest(generation, media)) return; + } var resolved = playbackLease?.path ?? await _formats.resolve(media); var usingLocalSafCopy = media.isContentUri && playbackLease == null; if (!_isCurrentPlayRequest(generation, media)) { diff --git a/lib/services/network_playback_cache.dart b/lib/services/network_playback_cache.dart index 9df8fecbf..4dd329939 100644 --- a/lib/services/network_playback_cache.dart +++ b/lib/services/network_playback_cache.dart @@ -278,6 +278,14 @@ class NetworkPlaybackCache { 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. /// A song still wanted downloads again. Future invalidate(String source) async { diff --git a/test/music_player_runtime_test.dart b/test/music_player_runtime_test.dart index aa0aec0de..e2dafba0c 100644 --- a/test/music_player_runtime_test.dart +++ b/test/music_player_runtime_test.dart @@ -2464,6 +2464,116 @@ void main() { 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(); + 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.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(); + 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.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().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.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().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 { final cache = await networkCache(); cache.want([source]); diff --git a/test/network_playback_cache_test.dart b/test/network_playback_cache_test.dart index 1b3150344..c86bfc384 100644 --- a/test/network_playback_cache_test.dart +++ b/test/network_playback_cache_test.dart @@ -194,6 +194,20 @@ void main() { 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 { final subject = cache(maxFiles: 2)..want([_a]); expect(await subject.ready(_a, _wait), isTrue);