fix(usb): hand the DAC back at the level it connected with when playback ends

Direct USB lowers a DAC to at most -40 dB when it opens it and never wrote a
level back, so once the app let go of the DAC, Android's mixer played every
other app through a DAC left that low: quiet until it was unplugged.

When the playback session ends (the player is stopped, or the engine goes
away), the app now pauses, writes back the level the DAC had when the app
first opened it after it was attached, and lets go of it. It only undoes its
own lowering: a DAC that reads higher already is left alone.

Not between two songs. There a song can follow through Android's mixer
(a stream, a format the output refuses), and with the level back up it would
play 40 dB louder than the one before. That case stays quiet as before, and
a session that ends without the DAC open forgets the level instead of
writing a stale one later. A killed app cannot write anything.

Not run on a DAC.
This commit is contained in:
zarzet committed 2026-11-19 18:08:02 +07:00
1 parent 09ff115ef7
commit 4ed523ac03
7 files changed
+113 -2

No files matched your search

@@ -80,6 +80,13 @@ class UsbBitPerfectPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, Even
result.success(phoneOutput || runCatching { usbOutputPresent() }.getOrDefault(true))
return
}
if (call.method == "endSession") {
// Only Direct USB changes the DAC's own level.
val playback = direct
if (playback == null) result.success(null)
else playback.command(call) { _, _ -> main.post { result.success(null) } }
return
}
if (call.method == "prepare") {
if (useHiRes) hiRes?.command(MethodCall("stop", null)) { _, _ -> }
else if (useDirect) direct?.command(MethodCall("stop", null)) { _, _ -> }
@@ -211,6 +211,14 @@ internal object UsbDirectFormats {
return output
}
/**
* The level to write back when playback ends on a DAC that connected at
* [original] dB and now reads [current] dB, or null to leave it: the app
* only undoes its own lowering, it never turns a DAC down further.
*/
fun levelToHandBack(original: Double?, current: Double): Double? =
original?.takeIf { it > current }
/** A new track reopens the DAC within this long of closing the last one. */
const val TRACK_CHANGE_WINDOW_MS = 10_000L
@@ -57,6 +57,9 @@ internal class UsbDirectPlayback(private val context: Context, private val emit:
// app last let go of that DAC: a reopen right after is a track change.
private val deviceVolumes = mutableMapOf<Int, Double>()
private val deviceReleases = mutableMapOf<Int, Long>()
// The level each DAC had before the app first lowered it, written back
// when playback ends so other apps do not play through a lowered DAC.
private val deviceOriginals = mutableMapOf<Int, Double>()
// The rate each DAC played a song rate at, so a rate it refused once is
// not asked of it again for every song.
private val deviceRates = mutableMapOf<Int, MutableMap<Int, Int>>()
@@ -81,6 +84,7 @@ internal class UsbDirectPlayback(private val context: Context, private val emit:
worker.post {
deviceVolumes.remove(device.deviceId)
deviceReleases.remove(device.deviceId)
deviceOriginals.remove(device.deviceId)
deviceRates.remove(device.deviceId)
if (device.deviceId == deviceId) fail("USB disconnected")
}
@@ -111,7 +115,7 @@ internal class UsbDirectPlayback(private val context: Context, private val emit:
done(null, null)
return
}
if (call.method == "prepare" || call.method == "stop") {
if (call.method == "prepare" || call.method == "stop" || call.method == "endSession") {
revision++
permission?.done?.invoke(mapOf("reason" to "cancelled"), null)
permission = null
@@ -149,6 +153,7 @@ internal class UsbDirectPlayback(private val context: Context, private val emit:
worker.post {
try {
val value: Any? = when (call.method) {
"endSession" -> { handBack(); null }
"resume" -> { resume(); null }
"pause" -> { pause(); null }
"seek" -> { seek((call.argument<Number>("position")?.toLong() ?: 0) * 1000); null }
@@ -338,6 +343,7 @@ internal class UsbDirectPlayback(private val context: Context, private val emit:
val volumeTrace = mutableMapOf<String, Any>("connectedDb" to connected.restoreLimitDb)
if (connected.available) {
val id = request.device.deviceId
deviceOriginals.putIfAbsent(id, connected.restoreLimitDb)
val since = deviceReleases[id]?.let { android.os.SystemClock.elapsedRealtime() - it }
since?.let { volumeTrace["sinceReleaseMs"] = it }
deviceVolumes[id]?.let {
@@ -557,11 +563,36 @@ internal class UsbDirectPlayback(private val context: Context, private val emit:
writtenFrames = 0
}
/**
* Ends the playback session: the DAC goes back to the level it connected
* with and is let go. Never between two songs, where the next one could
* play through Android's mixer at that higher level.
*/
private fun handBack() {
val audio = output
val original = deviceId?.let { deviceOriginals[it] }
// A session that ends without the DAC open learns its level afresh.
deviceOriginals.clear()
if (audio != null && !failed) {
runCatching {
// Nothing is in flight when the level rises.
pause()
val now = audio.volume()
val level = if (now.available) UsbDirectFormats.levelToHandBack(original, now.currentDb) else null
if (level != null) {
val set = audio.setVolume(level)
android.util.Log.i("UsbDirect", "DAC handed back at ${set.currentDb} dB (played at ${now.currentDb} dB)")
}
}.onFailure { android.util.Log.w("UsbDirect", "DAC level not handed back: ${it.message}") }
}
closeSource()
}
fun dispose() {
revision++
permission?.done?.invoke(mapOf("reason" to "cancelled"), null)
permission = null
context.unregisterReceiver(receiver)
worker.post { closeSource(); writeBuffer = ByteArray(0); thread.quitSafely() }
worker.post { handBack(); writeBuffer = ByteArray(0); thread.quitSafely() }
}
}
@@ -244,4 +244,14 @@ class UsbDirectFormatsTest {
// A DAC that connects louder still gets the remembered level.
assertEquals(-18.0, UsbDirectFormats.restoredVolumeDb(-18.0, 0.0, null), 0.0)
}
@Test
fun handsADacBackAtTheLevelItConnectedWith() {
// The app lowered it to play; other apps get the level they had.
assertEquals(0.0, UsbDirectFormats.levelToHandBack(0.0, -40.0)!!, 0.0)
// Never lower than it plays now, and nothing without a known level.
assertNull(UsbDirectFormats.levelToHandBack(-52.0, -40.0))
assertNull(UsbDirectFormats.levelToHandBack(-40.0, -40.0))
assertNull(UsbDirectFormats.levelToHandBack(null, -40.0))
}
}
+11
View File
@@ -267,6 +267,17 @@ class AudioplayersPlaybackDeck implements PlaybackDeck {
} on MissingPluginException catch (_) {}
}
/// Hands a Direct USB DAC back at the level it connected with and lets go
/// of it. Only when playback ends: Direct USB lowers that level to play,
/// and no song may follow through Android's mixer at the higher one.
static Future<void> endUsbSession() async {
try {
await _channel.invokeMethod<void>('endSession');
} on PlatformException catch (_) {
// The level stays where playback left it.
} on MissingPluginException catch (_) {}
}
/// Whether the output a bit-perfect song would open is connected. True
/// when the platform cannot say.
static Future<bool> bitPerfectOutputPresent({
+5
View File
@@ -2642,6 +2642,11 @@ class MusicPlayerHandler extends BaseAudioHandler
if (generation != _playRequestGeneration || _disposed) return;
resumeMedia = _media[_index].toJson();
}
if (_dependencies.isAndroid &&
_settings.usbBitPerfect &&
_settings.usbDirect) {
await AudioplayersPlaybackDeck.endUsbSession();
}
await _player.stop();
if (generation != _playRequestGeneration || _disposed) return;
_sourceReady = false;
+39
View File
@@ -2604,6 +2604,45 @@ void main() {
expect(decks.single.sources, ['stream http://127.0.0.1:1/song.flac']);
cache.want([]);
});
for (final direct in [true, false]) {
test('stopping hands a Direct USB DAC back: $direct', () async {
final calls = <String>[];
messenger.setMockMethodCallHandler(usb, (call) async {
calls.add(call.method);
return call.method == 'outputPresent' ? false : null;
});
addTearDown(() => messenger.setMockMethodCallHandler(usb, null));
final temp = await Directory.systemTemp.createTemp('player-usb-');
addTearDown(() => temp.delete(recursive: true));
final local = await File('${temp.path}/local.flac').writeAsBytes([4]);
final handler = await _runtime(
settings: AppSettings(
pauseOnMute: false,
usbBitPerfect: true,
usbDirect: direct,
),
isAndroid: true,
).initialize();
await handler.setQueueAndPlay([
PlayableMedia(
id: 'local-song',
source: local.path,
title: 'Local song',
artist: 'Artist',
),
]);
// A song change lets go of the DAC without touching its level.
expect(calls, isNot(contains('endSession')));
await handler.stop();
expect(
calls.where((call) => call == 'endSession'),
hasLength(direct ? 1 : 0),
);
});
}
});
test('a saved offline copy plays before a prefetched one', () async {