diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3b8570d6f..8a14bb2b1 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -498,21 +498,21 @@ dependencies { // Native in-app audio playback, background service, system media // controls, Bluetooth/headset controls and a MediaController-backed UI. - implementation("androidx.media3:media3-exoplayer:1.2.1") - implementation("androidx.media3:media3-datasource-okhttp:1.2.1") - implementation("androidx.media3:media3-exoplayer-hls:1.2.1") + implementation("androidx.media3:media3-exoplayer:1.9.0") + implementation("androidx.media3:media3-datasource-okhttp:1.9.0") + implementation("androidx.media3:media3-exoplayer-hls:1.9.0") // Segmented provider-module path: DASH chunk source + CDM decryption. - // Pinned to the same 1.2.1 line as exoplayer/hls to avoid binary mismatch. - implementation("androidx.media3:media3-exoplayer-dash:1.2.1") + // Pinned to the same 1.9.0 line as exoplayer/hls to match 16 KB FFmpeg. + implementation("androidx.media3:media3-exoplayer-dash:1.9.0") // MediaBrowserServiceCompat/MediaSessionCompat bridge used by Android // Auto to browse the LastWave library and control the same player. implementation("androidx.media:media:1.7.0") - // GPLv3 Media3-matched FFmpeg software decoder (distribution must comply). + // GPLv3 Media3-matched 16 KB-aligned FFmpeg software decoder (distribution must comply). // The renderer factory prefers FFmpeg for every codec it supports so all // devices decode through one deterministic, OEM-bug-free path; platform // decoders remain as automatic fallbacks. - implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.2.1+1") + implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1") // NIO also backports NewPipe's URL encoder/decoder overloads below API 33. coreLibraryDesugaring("com.android.tools:desugar_jdk_libs_nio:2.0.4") diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 23173f971..d18fb5514 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -94,6 +94,10 @@ -keepclassmembers class com.lastwave.app.data.podcast.** { *; } +# Keep Media3 FFmpeg extension classes constructed directly or via reflection. +-keep class androidx.media3.decoder.ffmpeg.FfmpegAudioRenderer { *; } +-keep class androidx.media3.decoder.ffmpeg.FfmpegLibrary { *; } + # Shrink and optimize, but do not rename classes/members. LastWave is open # source, so renaming hides nothing, and the scrambled single-letter names # (a.b.c) are what Huorong's static TrojanDropper/Android.Agent heuristic diff --git a/app/src/main/java/com/lastwave/app/data/download/ModuleFlacTranscoder.kt b/app/src/main/java/com/lastwave/app/data/download/ModuleFlacTranscoder.kt index 1ad7641a6..0f200a4b0 100644 --- a/app/src/main/java/com/lastwave/app/data/download/ModuleFlacTranscoder.kt +++ b/app/src/main/java/com/lastwave/app/data/download/ModuleFlacTranscoder.kt @@ -129,6 +129,41 @@ class ModuleFlacTranscoder @Inject constructor( enableFloatOutput: Boolean, enableAudioTrackPlaybackParams: Boolean, ): androidx.media3.exoplayer.audio.AudioSink = sink + + override fun buildAudioRenderers( + context: Context, + extensionRendererMode: Int, + mediaCodecSelector: androidx.media3.exoplayer.mediacodec.MediaCodecSelector, + enableDecoderFallback: Boolean, + audioSink: androidx.media3.exoplayer.audio.AudioSink, + eventHandler: android.os.Handler, + eventListener: androidx.media3.exoplayer.audio.AudioRendererEventListener, + out: ArrayList, + ) { + com.lastwave.app.playback.FfmpegCompat.appendAudioRenderers( + context = context, + mediaCodecSelector = mediaCodecSelector, + enableDecoderFallback = enableDecoderFallback, + audioSink = audioSink, + eventHandler = eventHandler, + eventListener = eventListener, + out = out, + ) { + super.buildAudioRenderers( + context, + extensionRendererMode, + mediaCodecSelector, + enableDecoderFallback, + audioSink, + eventHandler, + eventListener, + out, + ) + } + } + }.apply { + setExtensionRendererMode(com.lastwave.app.playback.FfmpegCompat.recommendedExtensionRendererMode()) + setEnableDecoderFallback(true) } val mediaSourceFactory = DefaultMediaSourceFactory(context) .setDrmSessionManagerProvider { drmFactory.sessionManagerFor(descriptor) } diff --git a/app/src/main/java/com/lastwave/app/data/download/TrackDownloadManagerStreaming.kt b/app/src/main/java/com/lastwave/app/data/download/TrackDownloadManagerStreaming.kt index fb38c56cf..cc54718e4 100644 --- a/app/src/main/java/com/lastwave/app/data/download/TrackDownloadManagerStreaming.kt +++ b/app/src/main/java/com/lastwave/app/data/download/TrackDownloadManagerStreaming.kt @@ -863,30 +863,7 @@ internal fun TrackDownloadManager.hasExpectedContainer(file: File, extension: St } }.getOrDefault(false) - /** - * Mirrors playback's spatial check (`MusicPlayer.isSpatialAudioSupportedOnDevice`): - * hardware decoder, bundled FFmpeg decoder, or Android S_V2+ Spatializer. - */ -internal fun TrackDownloadManager.isAtmosCapableDevice(): Boolean = runCatching { - val decoder = MediaCodecList(MediaCodecList.ALL_CODECS).codecInfos.any { info -> - !info.isEncoder && info.supportedTypes.any { type -> - type.equals("audio/eac3-joc", ignoreCase = true) || - type.equals("audio/eac3", ignoreCase = true) || - type.equals("audio/ac3", ignoreCase = true) - } - } - val ffmpeg = com.lastwave.app.playback.FfmpegCompat.isUsable && runCatching { - androidx.media3.decoder.ffmpeg.FfmpegLibrary.isAvailable() && - androidx.media3.decoder.ffmpeg.FfmpegLibrary.supportsFormat(androidx.media3.common.MimeTypes.AUDIO_E_AC3) - }.getOrDefault(false) - if (decoder || ffmpeg) return@runCatching true - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2) { - val am = context.getSystemService(AudioManager::class.java) - val spatializer = am?.spatializer - if (spatializer != null && (spatializer.isAvailable || spatializer.isEnabled)) { - return@runCatching true - } - } - false - }.getOrDefault(false) + /** Mirrors playback's spatial check (`MusicPlayer.isSpatialAudioSupportedOnDevice`). */ +internal fun TrackDownloadManager.isAtmosCapableDevice(): Boolean = + com.lastwave.app.playback.FfmpegCompat.isAtmosCapable() diff --git a/app/src/main/java/com/lastwave/app/playback/DirectTrackStream.kt b/app/src/main/java/com/lastwave/app/playback/DirectTrackStream.kt index dbacdd834..481a04366 100644 --- a/app/src/main/java/com/lastwave/app/playback/DirectTrackStream.kt +++ b/app/src/main/java/com/lastwave/app/playback/DirectTrackStream.kt @@ -21,6 +21,7 @@ package com.lastwave.app.playback import android.media.AudioAttributes +import android.media.AudioDeviceInfo import android.media.AudioFormat import android.media.AudioTrack import android.media.PlaybackParams @@ -47,7 +48,10 @@ import java.nio.ByteOrder * track accepts them. [probeDirect] runs that test before playback starts. */ @RequiresApi(Build.VERSION_CODES.S) -class DirectTrackStream(private val attributes: AudioAttributes) { +class DirectTrackStream( + private val attributes: AudioAttributes, + private val usbBitPerfect: UsbBitPerfectOutput? = null, +) { private var track: AudioTrack? = null var encoding: Int = -1 @@ -56,6 +60,8 @@ class DirectTrackStream(private val attributes: AudioAttributes) { private set var channelCount: Int = 0 private set + var isBitPerfectMixerActive: Boolean = false + private set private var bytesPerFrame = 0 /** Converted bytes AudioTrack has not taken yet (never more than one input buffer). */ @@ -79,7 +85,13 @@ class DirectTrackStream(private val attributes: AudioAttributes) { } } - fun open(rateHz: Int, channels: Int, wireEncoding: Int): Boolean { + fun open( + rateHz: Int, + channels: Int, + wireEncoding: Int, + preferredUsbDevice: AudioDeviceInfo? = null, + requestBitPerfectMixer: Boolean = false, + ): Boolean { release() val androidEncoding = androidEncodingOf(wireEncoding) ?: return false val mask = when (channels) { @@ -93,9 +105,20 @@ class DirectTrackStream(private val attributes: AudioAttributes) { .setEncoding(androidEncoding) .setChannelMask(mask) .build() + if (usbBitPerfect != null) { + usbBitPerfect.setAttributes(attributes) + usbBitPerfect.setDevice(preferredUsbDevice) + usbBitPerfect.setFormat(if (requestBitPerfectMixer) format else null) + usbBitPerfect.setEnabled(requestBitPerfectMixer && preferredUsbDevice != null) + } + val bitPerfectGranted = requestBitPerfectMixer && usbBitPerfect?.isConfigured() == true + val frameBytes = InternalDirectStream.bytesPerSample(wireEncoding) * channels val minBytes = AudioTrack.getMinBufferSize(rateHz, mask, androidEncoding) - if (minBytes <= 0) return false + if (minBytes <= 0) { + usbBitPerfect?.setEnabled(false) + return false + } // ~500 ms: a music player, not a game. Large buffers also keep the // track off the FAST mixer path, which would skew the direct test. val size = maxOf(minBytes * 4, rateHz / 2 * frameBytes) @@ -108,13 +131,18 @@ class DirectTrackStream(private val attributes: AudioAttributes) { .build() if (created.state != AudioTrack.STATE_INITIALIZED) { created.release() + usbBitPerfect?.setEnabled(false) return false } + if (preferredUsbDevice != null) { + runCatching { created.preferredDevice = preferredUsbDevice } + } track = created encoding = wireEncoding sampleRateHz = rateHz channelCount = channels bytesPerFrame = frameBytes + isBitPerfectMixerActive = bitPerfectGranted dead = false routedDeviceId = null runCatching { created.addOnRoutingChangedListener(routingListener, Handler(Looper.getMainLooper())) } @@ -133,6 +161,7 @@ class DirectTrackStream(private val attributes: AudioAttributes) { * is mixed. Null = inconclusive. Must run before [play]. */ fun probeDirect(): Boolean? { + if (isBitPerfectMixerActive) return true val target = track ?: return null return try { target.playbackParams = PlaybackParams().setSpeed(1.01f).setPitch(1.0f) @@ -221,12 +250,14 @@ class DirectTrackStream(private val attributes: AudioAttributes) { val target = track track = null pending = null + isBitPerfectMixerActive = false if (target != null) { runCatching { target.removeOnRoutingChangedListener(routingListener) } runCatching { target.pause() } runCatching { target.flush() } runCatching { target.release() } } + usbBitPerfect?.setEnabled(false) resetCounters() } diff --git a/app/src/main/java/com/lastwave/app/playback/ExclusiveUsbOutput.kt b/app/src/main/java/com/lastwave/app/playback/ExclusiveUsbOutput.kt index 11b485cbc..6d8ea9890 100644 --- a/app/src/main/java/com/lastwave/app/playback/ExclusiveUsbOutput.kt +++ b/app/src/main/java/com/lastwave/app/playback/ExclusiveUsbOutput.kt @@ -104,6 +104,8 @@ class ExclusiveUsbOutput @Inject constructor( * the next successful start so a stale reason never shows. */ @Volatile var lastFailureReason: String? = null private set + @Volatile private var lastFailureDefinitive = false + @Volatile private var lastClockWatchdogMs = 0L @Volatile private var lastAppliedListening = Float.NaN private var volumeProbed = false @Volatile private var lastNonMaxListeningGain = Float.NaN @@ -162,6 +164,19 @@ class ExclusiveUsbOutput @Inject constructor( fun isWanted(): Boolean = wanted + fun canOpen(): Boolean { + val manager = appContext.getSystemService(Context.USB_SERVICE) as? UsbManager ?: return false + val device = manager.deviceList.values.firstOrNull { dev -> + (0 until dev.interfaceCount).any { + dev.getInterface(it).interfaceClass == UsbConstants.USB_CLASS_AUDIO + } + } ?: return false + if (!manager.hasPermission(device)) return false + return blockReasonFor(device.vendorId, device.productId) == null + } + + fun wasLastFailureDefinitive(): Boolean = lastFailureDefinitive + /** * Software (PCM-scaled) volume instead of the DAC's hardware Feature Unit. * Switching to software parks the hardware level at 0 dB first so the two @@ -253,9 +268,12 @@ class ExclusiveUsbOutput @Inject constructor( * on explicit seek/stop. */ fun setPaused(value: Boolean) { + val wasPaused = paused paused = value if (value) { lastWriteElapsedMs = 0L + } else if (wasPaused && active) { + verifyClockWatchdog(force = true) } synchronized(pcmLock) { pcmLock.notifyAll() @@ -334,8 +352,9 @@ class ExclusiveUsbOutput @Inject constructor( if (!wanted) return false if (format.sampleMimeType != MimeTypes.AUDIO_RAW || format.sampleRate <= 0 || - format.channelCount !in 1..2 + format.channelCount !in 1..MAX_CHANNELS ) { + lastFailureDefinitive = true return false } val targetRate = rateOverrideHz?.takeIf { it > 0 } ?: format.sampleRate @@ -412,7 +431,7 @@ class ExclusiveUsbOutput @Inject constructor( QueuedPcm(null, bytes, encoding, size) } synchronized(pcmLock) { - if (paused || writerStop) return false + if (writerStop) return false pcmQueue.addLast(chunk) queuedBytes += size pcmLock.notifyAll() @@ -465,6 +484,7 @@ class ExclusiveUsbOutput @Inject constructor( */ fun restartIfStopped(): Boolean { val running = stream ?: return false + if (!active) return false if (running.isAlive) return false if (!running.start()) return false synchronized(stateLock) { @@ -537,33 +557,48 @@ class ExclusiveUsbOutput @Inject constructor( } ?: return failLocked("no USB audio device") if (!manager.hasPermission(usbDevice)) return failLocked("USB permission missing") blockReasonFor(usbDevice.vendorId, usbDevice.productId)?.let { reason -> - return failLocked("disabled for this DAC after a failed test ($reason) — turn USB Exclusive off and on to retry") + return failLocked( + "disabled for this DAC after a failed test ($reason) — turn USB Exclusive off and on to retry", + definitive = true, + ) } - currentDeviceKey = "${usbDevice.vendorId}:${usbDevice.productId}" + val deviceKey = "${usbDevice.vendorId}:${usbDevice.productId}" val bits = if (sourceBits > 0) sourceBits else (if (floatSource) 24 else 16) val reuse = stream if (reuse != null && reuse.isAlive && + currentDeviceKey == deviceKey && configuredRateHz == sampleRate && + activeChannels == channelCount && active && sourceEncoding == pcmEncoding && useFloatWrite == floatSource ) { - currentFallbackNegotiated = rateOverrideHz != null - synchronized(stateLock) { - paused = false - startMediaTimeNeedsInit = true - mediaTimeBaseFrames = reuse.framesWritten - ensureVolumeObserverLocked() - syncListeningGainLocked() + val reported = runCatching { usbAudio.readSampleRate() }.getOrDefault(-1) + if (reported <= 0 || reported == sampleRate) { + if (reported > 0) { + lastHardwareRate = reported + clockMatched = rateOverrideHz == null + } + currentFallbackNegotiated = rateOverrideHz != null + lastClockWatchdogMs = SystemClock.elapsedRealtime() + synchronized(stateLock) { + paused = false + startMediaTimeNeedsInit = true + mediaTimeBaseFrames = reuse.framesWritten + ensureVolumeObserverLocked() + syncListeningGainLocked() + } + return true } - return true + Log.w(TAG, "reuse rejected: DAC clock is ${reported}Hz, track needs ${sampleRate}Hz") } stopStreamLocked() usbAudio.closeDevice() connection = null + currentDeviceKey = deviceKey val info = usbAudio.openDevice(usbDevice) ?: return failLocked("openDevice failed" + (usbAudio.lastOpenError?.let { ": $it" } ?: "")) val hwRates = usbAudio.querySupportedSampleRates() @@ -599,15 +634,15 @@ class ExclusiveUsbOutput @Inject constructor( // applied with 8 extra bits instead of re-quantizing to 16 bits, // which raised the noise floor into audible hiss on sensitive IEMs. val requestBits = if (effectiveBits in 1..16) 24 else effectiveBits - var (alt, wireBits) = usbAudio.findAltSetting(requestBits, effectiveRate) + var (alt, wireBits) = usbAudio.findAltSetting(requestBits, effectiveRate, channelCount) var rateSetBefore = usbAudio.setSampleRate(effectiveRate) if (!usbAudio.setAltSetting(alt)) { - val fallbackAlt = usbAudio.findAltSetting(24, effectiveRate) + val fallbackAlt = usbAudio.findAltSetting(24, effectiveRate, channelCount) if (fallbackAlt.first != alt && usbAudio.setAltSetting(fallbackAlt.first)) { alt = fallbackAlt.first wireBits = fallbackAlt.second } else { - return failLocked("setAltSetting $alt failed") + return failLocked("setAltSetting $alt failed", definitive = true) } } var reported = usbAudio.readSampleRate() @@ -615,6 +650,12 @@ class ExclusiveUsbOutput @Inject constructor( rateSetBefore = usbAudio.setSampleRate(effectiveRate) reported = usbAudio.readSampleRate() } + var settleTries = 0 + while (reported > 0 && reported != effectiveRate && settleTries < CLOCK_SETTLE_TRIES) { + Thread.sleep(CLOCK_SETTLE_STEP_MS) + reported = usbAudio.readSampleRate() + settleTries++ + } // If the DAC's internal clock still rejected or clamped the requested rate // (e.g. reported 44.1 / 48 / 96 kHz when asked for 88.2 / 176.4 / 352.8 kHz), @@ -642,7 +683,7 @@ class ExclusiveUsbOutput @Inject constructor( effectiveFloatSource = true effectiveEncoding = C.ENCODING_PCM_FLOAT autoNegotiatedFallback = true - val updatedAlt = usbAudio.findAltSetting(effectiveBits, effectiveRate) + val updatedAlt = usbAudio.findAltSetting(effectiveBits, effectiveRate, channelCount) if (updatedAlt.first != alt) { if (usbAudio.setAltSetting(updatedAlt.first)) { alt = updatedAlt.first @@ -670,7 +711,7 @@ class ExclusiveUsbOutput @Inject constructor( it.direction == UsbConstants.USB_DIR_OUT } } - if (selectedOut == null) return failLocked("alt $alt has no isochronous OUT endpoint") + if (selectedOut == null) return failLocked("alt $alt has no isochronous OUT endpoint", definitive = true) val selectedFeedback = selected?.let { iface -> (0 until iface.endpointCount).map { iface.getEndpoint(it) } .firstOrNull { @@ -715,6 +756,8 @@ class ExclusiveUsbOutput @Inject constructor( currentFallbackNegotiated = autoNegotiatedFallback active = true lastFailureReason = null + lastFailureDefinitive = false + lastClockWatchdogMs = SystemClock.elapsedRealtime() paused = false startMediaTimeNeedsInit = true startMediaTimeUs = 0L @@ -723,7 +766,7 @@ class ExclusiveUsbOutput @Inject constructor( lastHardwareRate = reported clockMatched = reported == effectiveRate && !autoNegotiatedFallback } else { - clockMatched = rateSetBefore && !autoNegotiatedFallback + clockMatched = rateSetBefore && usbAudio.lastRateWriteTrusted && !autoNegotiatedFallback } clockRechecked = true if (!forceSoftwareVolume) { @@ -971,6 +1014,7 @@ class ExclusiveUsbOutput @Inject constructor( continue } if (!target.isAlive) break + if (!verifyClockWatchdog(force = false)) break writingInProgress = true lastWriteElapsedMs = SystemClock.elapsedRealtime() try { @@ -1068,9 +1112,30 @@ class ExclusiveUsbOutput @Inject constructor( val byteSize: Int, ) - private fun failLocked(reason: String): Boolean { + private fun verifyClockWatchdog(force: Boolean): Boolean { + val expected = configuredRateHz + if (!active || expected <= 0) return true + val now = SystemClock.elapsedRealtime() + if (!force && now - lastClockWatchdogMs < CLOCK_WATCHDOG_MS) return true + lastClockWatchdogMs = now + val reported = runCatching { usbAudio.readSampleRate() }.getOrDefault(-1) + if (reported > 0 && reported != expected) { + Log.w(TAG, "DAC clock drifted: expected=${expected}Hz reported=${reported}Hz; stopping exclusive stream") + lastFailureReason = "DAC clock drifted to ${reported}Hz" + lastFailureDefinitive = true + clockMatched = false + active = false + writerStop = true + runCatching { stream?.stop() } + return false + } + return true + } + + private fun failLocked(reason: String, definitive: Boolean = false): Boolean { Log.w(TAG, "Exclusive USB fail-open: $reason") lastFailureReason = reason + lastFailureDefinitive = definitive teardownLocked(closeDevice = true) return false } @@ -1084,10 +1149,14 @@ class ExclusiveUsbOutput @Inject constructor( const val PLL_SETTLE_MS = 50L const val CLOCK_VALID_TRIES = 40 const val CLOCK_VALID_STEP_MS = 5L + const val CLOCK_WATCHDOG_MS = 5_000L + const val CLOCK_SETTLE_TRIES = 10 + const val CLOCK_SETTLE_STEP_MS = 20L const val RAW_PCM16 = 2 const val RAW_PCM24 = 0x15 const val RAW_PCM32 = 0x16 const val MAX_QUEUED_BYTES = 512 * 1024 + const val MAX_CHANNELS = 8 const val MAX_SPARE_CHUNKS = 4 val FLUSH_MARKER = QueuedPcm(null, null, -1, 0) val IDLE_MARKER = QueuedPcm(null, null, -2, 0) diff --git a/app/src/main/java/com/lastwave/app/playback/FfmpegCompat.kt b/app/src/main/java/com/lastwave/app/playback/FfmpegCompat.kt index 2b371794a..6464442e2 100644 --- a/app/src/main/java/com/lastwave/app/playback/FfmpegCompat.kt +++ b/app/src/main/java/com/lastwave/app/playback/FfmpegCompat.kt @@ -1,27 +1,155 @@ package com.lastwave.app.playback -import android.system.Os -import android.system.OsConstants +import android.content.Context +import android.media.MediaCodecList +import android.os.Handler +import androidx.annotation.OptIn +import androidx.media3.common.C +import androidx.media3.common.Format +import androidx.media3.common.MimeTypes +import androidx.media3.common.util.UnstableApi +import androidx.media3.decoder.ffmpeg.FfmpegAudioRenderer +import androidx.media3.decoder.ffmpeg.FfmpegLibrary +import androidx.media3.exoplayer.DefaultRenderersFactory +import androidx.media3.exoplayer.Renderer +import androidx.media3.exoplayer.RendererCapabilities +import androidx.media3.exoplayer.audio.AudioRendererEventListener +import androidx.media3.exoplayer.audio.AudioSink +import androidx.media3.exoplayer.audio.MediaCodecAudioRenderer +import androidx.media3.exoplayer.mediacodec.MediaCodecSelector /** - * Whether the bundled FFmpeg decoder may be loaded on this device. - * - * libffmpegJNI.so in org.jellyfin.media3:media3-ffmpeg-decoder:1.2.1+1 is the - * only native library in the APK aligned to 4 KB pages; everything else is - * 16 KB-aligned. On a 16 KB-page kernel (Android 15+ hardware) it can only run - * under the platform's page-size compatibility mode, and playback sessions there - * died with SIGSEGV/SEGV_ACCERR seconds after the decoder started. Those - * devices use the platform decoders instead (Opus, AAC, FLAC, MP3 and Vorbis - * are all built into Android). - * - * Remove this gate once the FFmpeg extension is upgraded to a 16 KB-aligned - * build (that needs the matching Media3 version). + * Shared availability, capability, and audio-renderer wiring for the bundled + * 16 KB-aligned Media3 FFmpeg decoder (`1.9.0+1`). */ +@OptIn(UnstableApi::class) object FfmpegCompat { - private const val LEGACY_PAGE_SIZE = 4096L + + private val PLATFORM_ATMOS_MIMES = setOf( + "audio/eac3-joc", + "audio/ac4", + "audio/mha1", + "audio/mhm1", + ) val isUsable: Boolean by lazy { - val pageSize = runCatching { Os.sysconf(OsConstants._SC_PAGESIZE) }.getOrDefault(LEGACY_PAGE_SIZE) - pageSize <= LEGACY_PAGE_SIZE + runCatching { FfmpegLibrary.isAvailable() }.getOrDefault(false) + } + + fun recommendedExtensionRendererMode(): Int = + if (isUsable) DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER + else DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF + + fun supportsMime(mimeType: String): Boolean = + isUsable && runCatching { FfmpegLibrary.supportsFormat(mimeType) }.getOrDefault(false) + + /** + * Genuine spatial/Atmos hardware decoders (`audio/eac3-joc`, `ac4`, MPEG-H). + * Plain `audio/eac3`/`audio/ac3` codecs are often video-passthrough blocks that + * fail music JOC manifests unless FFmpeg handles the E-AC-3 core. + */ + fun hasPlatformAtmosDecoder(): Boolean = runCatching { + val codecList = MediaCodecList(MediaCodecList.ALL_CODECS) + codecList.codecInfos.any { info -> + !info.isEncoder && info.supportedTypes.any { type -> + type.lowercase() in PLATFORM_ATMOS_MIMES + } + } + }.getOrDefault(false) + + fun isAtmosCapable(): Boolean = + isAtmosCapable( + hasPlatformAtmos = hasPlatformAtmosDecoder(), + ffmpegEac3 = supportsMime(MimeTypes.AUDIO_E_AC3), + ) + + internal fun isAtmosCapable(hasPlatformAtmos: Boolean, ffmpegEac3: Boolean): Boolean = + hasPlatformAtmos || ffmpegEac3 + + internal fun shouldUsePlatformSpatialRenderer( + mime: String, + hasPlatformAtmos: Boolean = hasPlatformAtmosDecoder(), + ffmpegEac3: Boolean = supportsMime(MimeTypes.AUDIO_E_AC3), + ): Boolean { + val lower = mime.lowercase() + val isSpatial = lower in PLATFORM_ATMOS_MIMES || + lower.contains("eac3-joc") || + lower.contains("ac4") || + lower.contains("mha1") || + lower.contains("mhm1") + if (isSpatial) return true + val isLegacyDolby = lower.contains("eac3") || lower.contains("ec-3") || + lower.contains("ac-3") || lower.contains("ac3") + if (!isLegacyDolby) return false + // Only let platform MediaCodec claim legacy AC-3/E-AC-3 ahead of FFmpeg + // when genuine Atmos HAL exists or FFmpeg isn't available to handle it. + return hasPlatformAtmos || !ffmpegEac3 + } + + /** + * Registers renderers in a deterministic order across main playback, silent + * probe players, and transcoding: genuine spatial MediaCodec (when eligible), + * then FFmpeg software decoding (guaranteed single instance when usable), + * then standard MediaCodec fallbacks from [superBuild]. + */ + fun appendAudioRenderers( + context: Context, + mediaCodecSelector: MediaCodecSelector, + enableDecoderFallback: Boolean, + audioSink: AudioSink, + eventHandler: Handler, + eventListener: AudioRendererEventListener, + out: ArrayList, + onConfigureSpatialMediaFormat: ((android.media.MediaFormat, Format) -> Unit)? = null, + superBuild: () -> Unit, + ) { + val spatialRenderer = object : MediaCodecAudioRenderer( + context, + mediaCodecSelector, + enableDecoderFallback, + eventHandler, + eventListener, + audioSink, + ) { + override fun supportsFormat( + selector: MediaCodecSelector, + format: Format, + ): Int { + val mime = format.sampleMimeType?.lowercase().orEmpty() + if (!shouldUsePlatformSpatialRenderer(mime)) { + return RendererCapabilities.create(C.FORMAT_UNSUPPORTED_TYPE) + } + return super.supportsFormat(selector, format) + } + + override fun getMediaFormat( + format: Format, + codecMimeType: String, + codecMaxInputSize: Int, + codecOperatingRate: Float, + ): android.media.MediaFormat { + val mediaFormat = super.getMediaFormat( + format, + codecMimeType, + codecMaxInputSize, + codecOperatingRate, + ) + onConfigureSpatialMediaFormat?.invoke(mediaFormat, format) + return mediaFormat + } + } + out.add(spatialRenderer) + val beforeSuper = out.size + superBuild() + + if (isUsable && out.none { it is FfmpegAudioRenderer }) { + runCatching { + FfmpegAudioRenderer(eventHandler, eventListener, audioSink) + }.getOrNull()?.let { ffmpegRenderer -> + // Insert right after the spatial gate and ahead of standard + // MediaCodecAudioRenderer added by superBuild. + out.add(beforeSuper, ffmpegRenderer) + } + } } } diff --git a/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt b/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt index 6caba375a..d4bcb43cc 100644 --- a/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt +++ b/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt @@ -1815,83 +1815,30 @@ class MusicPlayer @Inject constructor( eventListener: AudioRendererEventListener, out: ArrayList, ) { - // Hardware/platform Dolby Atmos & Spatial audio MediaCodec renderer: - // Placed ahead of FFmpeg so Android's native Dolby Atmos HAL and Spatializer - // decode E-AC-3 JOC with hardware dialogue normalization, full volume - // (no -8 dB FFmpeg downmix attenuation), and system spatial virtualization. - // Standard codecs (FLAC, Opus, AAC, MP3, Vorbis) return FORMAT_UNSUPPORTED_TYPE - // here so FFmpeg retains priority for them. - val dolbySpatialRenderer = object : MediaCodecAudioRenderer( - context, - mediaCodecSelector, - enableDecoderFallback, - eventHandler, - eventListener, - audioSink, + FfmpegCompat.appendAudioRenderers( + context = context, + mediaCodecSelector = mediaCodecSelector, + enableDecoderFallback = enableDecoderFallback, + audioSink = audioSink, + eventHandler = eventHandler, + eventListener = eventListener, + out = out, + onConfigureSpatialMediaFormat = ::configureDolbySpatialMediaFormat, ) { - override fun supportsFormat( - mediaCodecSelector: MediaCodecSelector, - format: androidx.media3.common.Format, - ): Int { - val mime = format.sampleMimeType?.lowercase().orEmpty() - val isDolbyOrSpatial = mime.contains("eac3") || mime.contains("ec-3") || - mime.contains("ac-3") || mime.contains("ac3") || mime.contains("ac4") || - mime.contains("mha1") || mime.contains("mhm1") - if (!isDolbyOrSpatial) { - return RendererCapabilities.create(C.FORMAT_UNSUPPORTED_TYPE) - } - return super.supportsFormat(mediaCodecSelector, format) - } - - override fun getMediaFormat( - format: androidx.media3.common.Format, - codecMimeType: String, - codecMaxInputSize: Int, - codecOperatingRate: Float, - ): MediaFormat { - val mediaFormat = super.getMediaFormat( - format, - codecMimeType, - codecMaxInputSize, - codecOperatingRate, - ) - configureDolbySpatialMediaFormat(mediaFormat, format) - return mediaFormat - } - } - out.add(dolbySpatialRenderer) - - super.buildAudioRenderers( - context, - extensionRendererMode, - mediaCodecSelector, - enableDecoderFallback, - audioSink, - eventHandler, - eventListener, - out, - ) - // Explicit software decoder fallback for MediaTek / ColorOS - if (FfmpegCompat.isUsable) try { - // Direct dependency (org.jellyfin.media3:media3-ffmpeg-decoder): - // construct it typed instead of via reflection. - out.add( - androidx.media3.decoder.ffmpeg.FfmpegAudioRenderer(eventHandler, eventListener, audioSink), + super.buildAudioRenderers( + context, + extensionRendererMode, + mediaCodecSelector, + enableDecoderFallback, + audioSink, + eventHandler, + eventListener, + out, ) - } catch (_: Throwable) { } } }.apply { - // FFmpeg-first decoding, the Poweramp/VLC model: every codec the - // bundled GPL build supports (FLAC 24/96-192, Opus, AAC, MP3, - // Vorbis) decodes through the same battle-tested software path on - // every device, eliminating per-OEM platform codec bugs that - // surface as noise/distortion. setEnableDecoderFallback keeps the - // platform decoder for anything FFmpeg rejects. - setExtensionRendererMode( - if (FfmpegCompat.isUsable) DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER - else DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF, - ) + setExtensionRendererMode(FfmpegCompat.recommendedExtensionRendererMode()) setEnableDecoderFallback(true) setEnableAudioTrackPlaybackParams(false) setMediaCodecSelector(accurateAudioMediaCodecSelector) @@ -8003,61 +7950,30 @@ class MusicPlayer @Inject constructor( eventListener: AudioRendererEventListener, out: ArrayList, ) { - val immersiveRenderer = object : MediaCodecAudioRenderer( - context, - mediaCodecSelector, - enableDecoderFallback, - eventHandler, - eventListener, - audioSink, + FfmpegCompat.appendAudioRenderers( + context = context, + mediaCodecSelector = mediaCodecSelector, + enableDecoderFallback = enableDecoderFallback, + audioSink = audioSink, + eventHandler = eventHandler, + eventListener = eventListener, + out = out, + onConfigureSpatialMediaFormat = ::configureDolbySpatialMediaFormat, ) { - override fun supportsFormat( - mediaCodecSelector: MediaCodecSelector, - format: androidx.media3.common.Format, - ): Int { - val mime = format.sampleMimeType?.lowercase().orEmpty() - val isImmersive = mime.contains("eac3") || mime.contains("ec-3") || - mime.contains("ac-3") || mime.contains("ac3") || mime.contains("ac4") || - mime.contains("mha1") || mime.contains("mhm1") - if (!isImmersive) { - return RendererCapabilities.create(C.FORMAT_UNSUPPORTED_TYPE) - } - return super.supportsFormat(mediaCodecSelector, format) - } - - override fun getMediaFormat( - format: androidx.media3.common.Format, - codecMimeType: String, - codecMaxInputSize: Int, - codecOperatingRate: Float, - ): MediaFormat { - val mediaFormat = super.getMediaFormat( - format, - codecMimeType, - codecMaxInputSize, - codecOperatingRate, - ) - configureDolbySpatialMediaFormat(mediaFormat, format) - return mediaFormat - } + super.buildAudioRenderers( + context, + extensionRendererMode, + mediaCodecSelector, + enableDecoderFallback, + audioSink, + eventHandler, + eventListener, + out, + ) } - out.add(immersiveRenderer) - super.buildAudioRenderers( - context, - extensionRendererMode, - mediaCodecSelector, - enableDecoderFallback, - audioSink, - eventHandler, - eventListener, - out, - ) } }.apply { - setExtensionRendererMode( - if (FfmpegCompat.isUsable) DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER - else DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF, - ) + setExtensionRendererMode(FfmpegCompat.recommendedExtensionRendererMode()) setEnableDecoderFallback(true) setMediaCodecSelector(accurateAudioMediaCodecSelector) } diff --git a/app/src/main/java/com/lastwave/app/playback/MusicPlayerUsb.kt b/app/src/main/java/com/lastwave/app/playback/MusicPlayerUsb.kt index b36d512f5..b962b751f 100644 --- a/app/src/main/java/com/lastwave/app/playback/MusicPlayerUsb.kt +++ b/app/src/main/java/com/lastwave/app/playback/MusicPlayerUsb.kt @@ -268,42 +268,14 @@ internal fun MusicPlayer.recomputeUsbExclusivePref() { usbExclusivePrefEnabled = bitPerfectEnabled && usbExclusiveRawPref } - /** True only for genuine Atmos decode: an E-AC-3 JOC decoder. A plain - * `audio/eac3`/`ac3` decoder (common, video-passthrough silicon) cannot - * render an Atmos music stream — treating it as capable used to request - * spatial manifests that ExoPlayer then choked on (3003 → retry loop → - * "Playback interrupted") instead of dropping to stereo. */ private val isAtmosDecoderAvailable: Boolean by lazy { - val platform = runCatching { - val codecList = MediaCodecList(MediaCodecList.ALL_CODECS) - codecList.codecInfos.any { info -> - !info.isEncoder && info.supportedTypes.any { type -> - type.equals("audio/eac3-joc", ignoreCase = true) || - type.equals("audio/eac3", ignoreCase = true) || - type.equals("audio/ac3", ignoreCase = true) - } - } - }.getOrDefault(false) - // Bundled FFmpeg decodes the E-AC-3 core of JOC streams on any device. - val ffmpeg = FfmpegCompat.isUsable && runCatching { - androidx.media3.decoder.ffmpeg.FfmpegLibrary.isAvailable() && - androidx.media3.decoder.ffmpeg.FfmpegLibrary.supportsFormat(MimeTypes.AUDIO_E_AC3) - }.getOrDefault(false) + val platform = FfmpegCompat.hasPlatformAtmosDecoder() + val ffmpeg = FfmpegCompat.supportsMime(MimeTypes.AUDIO_E_AC3) android.util.Log.i("MusicPlayer", "[ATMOS] decoder availability platform=$platform ffmpeg=$ffmpeg") platform || ffmpeg } -fun MusicPlayer.isSpatialAudioSupportedOnDevice(): Boolean { - if (isAtmosDecoderAvailable) return true - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2) { - val am = audioManager ?: return false - val spatializer = am.spatializer - if (spatializer.isAvailable || spatializer.isEnabled) { - return true - } - } - return false - } +fun MusicPlayer.isSpatialAudioSupportedOnDevice(): Boolean = isAtmosDecoderAvailable @androidx.annotation.RequiresApi(Build.VERSION_CODES.S_V2) internal object SpatializerHelper { diff --git a/app/src/main/java/com/lastwave/app/playback/NativeProcessingAudioSink.kt b/app/src/main/java/com/lastwave/app/playback/NativeProcessingAudioSink.kt index f822b0d21..34469b49d 100644 --- a/app/src/main/java/com/lastwave/app/playback/NativeProcessingAudioSink.kt +++ b/app/src/main/java/com/lastwave/app/playback/NativeProcessingAudioSink.kt @@ -1339,11 +1339,12 @@ class NativeProcessingAudioSink( val session = exclusiveUsb ?: return false if (format.sampleMimeType != MimeTypes.AUDIO_RAW || format.sampleRate <= 0 || - format.channelCount !in 1..2 || + format.channelCount !in 1..8 || format.pcmEncoding !in SUPPORTED_ENCODINGS ) { return false } + if (!session.canOpen()) return false // Release AudioTrack before claiming the USB interface. While the // mixer still owns the DAC, libusb cannot detach snd-usb-audio and // exclusive start fails closed onto the shared 48 kHz track. diff --git a/app/src/test/java/com/lastwave/app/playback/FfmpegCompatTest.kt b/app/src/test/java/com/lastwave/app/playback/FfmpegCompatTest.kt new file mode 100644 index 000000000..ede4d30ca --- /dev/null +++ b/app/src/test/java/com/lastwave/app/playback/FfmpegCompatTest.kt @@ -0,0 +1,64 @@ +package com.lastwave.app.playback + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class FfmpegCompatTest { + + @Test + fun `atmos capability requires genuine platform JOC or FFmpeg E-AC-3 decoder`() { + assertThat(FfmpegCompat.isAtmosCapable(hasPlatformAtmos = false, ffmpegEac3 = false)).isFalse() + assertThat(FfmpegCompat.isAtmosCapable(hasPlatformAtmos = true, ffmpegEac3 = false)).isTrue() + assertThat(FfmpegCompat.isAtmosCapable(hasPlatformAtmos = false, ffmpegEac3 = true)).isTrue() + } + + @Test + fun `legacy eac3 and ac3 defer to FFmpeg when no platform Atmos HAL exists`() { + assertThat( + FfmpegCompat.shouldUsePlatformSpatialRenderer( + mime = "audio/eac3", + hasPlatformAtmos = false, + ffmpegEac3 = true, + ), + ).isFalse() + assertThat( + FfmpegCompat.shouldUsePlatformSpatialRenderer( + mime = "audio/ac3", + hasPlatformAtmos = false, + ffmpegEac3 = true, + ), + ).isFalse() + } + + @Test + fun `genuine spatial mimes use platform renderer and legacy eac3 uses platform when HAL present or FFmpeg absent`() { + assertThat( + FfmpegCompat.shouldUsePlatformSpatialRenderer( + mime = "audio/eac3-joc", + hasPlatformAtmos = false, + ffmpegEac3 = true, + ), + ).isTrue() + assertThat( + FfmpegCompat.shouldUsePlatformSpatialRenderer( + mime = "audio/eac3", + hasPlatformAtmos = true, + ffmpegEac3 = true, + ), + ).isTrue() + assertThat( + FfmpegCompat.shouldUsePlatformSpatialRenderer( + mime = "audio/eac3", + hasPlatformAtmos = false, + ffmpegEac3 = false, + ), + ).isTrue() + assertThat( + FfmpegCompat.shouldUsePlatformSpatialRenderer( + mime = "audio/flac", + hasPlatformAtmos = true, + ffmpegEac3 = true, + ), + ).isFalse() + } +} diff --git a/audio/decent-usb-audio-driver/src/main/kotlin/com/decent/usbaudio/UsbAudioDevice.kt b/audio/decent-usb-audio-driver/src/main/kotlin/com/decent/usbaudio/UsbAudioDevice.kt index a03634e4a..5e6e1fa5d 100644 --- a/audio/decent-usb-audio-driver/src/main/kotlin/com/decent/usbaudio/UsbAudioDevice.kt +++ b/audio/decent-usb-audio-driver/src/main/kotlin/com/decent/usbaudio/UsbAudioDevice.kt @@ -50,6 +50,9 @@ class UsbAudioDevice private constructor(private val context: Context) { /** Per playback alt: sample rates from the UAC1 Format Type I descriptor (empty = not stated). */ private var parsedAltRates: Map = emptyMap() + private var parsedAltChannels: Map = emptyMap() + @Volatile var lastRateWriteTrusted: Boolean = false + private set private class AltRates(val discrete: List, val min: Int, val max: Int) { fun accepts(rate: Int): Boolean = @@ -605,6 +608,7 @@ class UsbAudioDevice private constructor(private val context: Context) { val raw = conn.rawDescriptors ?: return Pair(1, 16) val altSettings = mutableListOf>() val altRates = HashMap() + val altChannels = HashMap() var i = 0 var currentAlt = 0 @@ -630,18 +634,22 @@ class UsbAudioDevice private constructor(private val context: Context) { if (inAudioStreaming) currentAlt = bAlternateSetting } - // CS_INTERFACE (0x24) in AudioStreaming — Format Type I (subtype 0x02) if (inAudioStreaming && bDescriptorType == 0x24 && bLength >= 6) { val bDescriptorSubtype = raw[i + 2].toInt() and 0xFF - if (bDescriptorSubtype == 0x02) { + if (bDescriptorSubtype == 0x01 && uacVersion != 100 && currentAlt > 0 && bLength >= 11) { + val nrCh = raw[i + 10].toInt() and 0xFF + if (nrCh in 1..16) altChannels[currentAlt] = nrCh + } else if (bDescriptorSubtype == 0x02) { + if (uacVersion == 100 && currentAlt > 0) { + val nrCh = raw[i + 4].toInt() and 0xFF + if (nrCh in 1..16) altChannels[currentAlt] = nrCh + } val bSubslotSize: Int val bBitResolution: Int if (uacVersion == 100) { - // UAC 1.0: bSubframeSize is at offset 5, bBitResolution at offset 6 bSubslotSize = if (bLength >= 7) raw[i + 5].toInt() and 0xFF else 2 bBitResolution = if (bLength >= 7) raw[i + 6].toInt() and 0xFF else 16 } else { - // UAC 2.0/3.0: bSubslotSize is at offset 4, bBitResolution at offset 5 bSubslotSize = raw[i + 4].toInt() and 0xFF bBitResolution = raw[i + 5].toInt() and 0xFF } @@ -663,7 +671,7 @@ class UsbAudioDevice private constructor(private val context: Context) { } altRates[currentAlt] = AltRates(discrete, lo, hi) } - trace("alt=$currentAlt bits=$bBitResolution container=$containerBits rates=${altRates[currentAlt] ?: "-"}") + trace("alt=$currentAlt bits=$bBitResolution container=$containerBits ch=${altChannels[currentAlt] ?: "-"} rates=${altRates[currentAlt] ?: "-"}") if (currentAlt > 0) { altSettings.add(Pair(currentAlt, containerBits)) @@ -680,6 +688,7 @@ class UsbAudioDevice private constructor(private val context: Context) { parsedAltSettings = altSettings parsedAltRates = altRates + parsedAltChannels = altChannels Log.i(TAG, "parseBestAltSetting: best alt=$bestAlt bits=$bestBits, all=$altSettings") return Pair(bestAlt, bestBits) } @@ -759,21 +768,31 @@ class UsbAudioDevice private constructor(private val context: Context) { * expose different alts for different rate ranges; streaming a rate the * selected alt does not support plays garbage. */ - fun findAltSetting(targetBitDepth: Int, rateHz: Int): Pair { + fun findAltSetting(targetBitDepth: Int, rateHz: Int, channelCount: Int = 2): Pair { + val channelFiltered = if (parsedAltChannels.isNotEmpty() && channelCount > 0) { + parsedAltSettings.filter { (alt, _) -> (parsedAltChannels[alt] ?: channelCount) == channelCount } + .ifEmpty { parsedAltSettings } + } else { + parsedAltSettings + } val rated = parsedAltRates - if (rated.isNotEmpty() && rateHz > 0) { - val usable = parsedAltSettings.filter { (alt, _) -> rated[alt]?.accepts(rateHz) ?: true } - if (usable.isNotEmpty()) { - val pick = usable.firstOrNull { it.second == targetBitDepth } - ?: usable.filter { it.second > targetBitDepth }.minByOrNull { it.second } - ?: usable.maxByOrNull { it.second }!! - trace("findAltSetting(bits=$targetBitDepth, rate=$rateHz) -> alt=${pick.first} wireBits=${pick.second}") - return pick - } - trace("findAltSetting: no alt states $rateHz Hz; falling back to bit depth only") + val usable = if (rated.isNotEmpty() && rateHz > 0) { + channelFiltered.filter { (alt, _) -> rated[alt]?.accepts(rateHz) ?: true } + .ifEmpty { + trace("findAltSetting: no alt states $rateHz Hz for ${channelCount}ch; falling back") + channelFiltered + } + } else { + channelFiltered + } + val pick = if (usable.isNotEmpty()) { + usable.firstOrNull { it.second == targetBitDepth } + ?: usable.filter { it.second > targetBitDepth }.minByOrNull { it.second } + ?: usable.maxByOrNull { it.second }!! + } else { + findAltSettingForBitDepth(targetBitDepth) } - val pick = findAltSettingForBitDepth(targetBitDepth) - trace("findAltSetting(bits=$targetBitDepth, rate=$rateHz) -> alt=${pick.first} wireBits=${pick.second}") + trace("findAltSetting(bits=$targetBitDepth, rate=$rateHz, ch=$channelCount) -> alt=${pick.first} wireBits=${pick.second}") return pick } @@ -825,6 +844,8 @@ class UsbAudioDevice private constructor(private val context: Context) { parsedClockSelectorId = -1 parsedClockSelectorPins = emptyList() activeClockSourceId = -1 + parsedAltChannels = emptyMap() + lastRateWriteTrusted = false val conn = connection val fd = conn?.fileDescriptor ?: -1 claimedControlInterface?.let { iface -> @@ -1013,11 +1034,13 @@ class UsbAudioDevice private constructor(private val context: Context) { */ fun setSampleRate(sampleRateHz: Int): Boolean { val conn = connection ?: return false + lastRateWriteTrusted = false if (currentUacVersion == 100) { // UAC1 has no Clock Source entities. Blasting UAC2 SET_CUR at // guessed entity IDs can hit a Feature/Mixer unit instead and // never sets the rate. UAC1 sets it on the streaming endpoint. val ok = setUac1EndpointRate(conn, sampleRateHz) + lastRateWriteTrusted = ok trace("setSampleRate($sampleRateHz) UAC1 endpoint: ${if (ok) "OK" else "FAILED"}") return ok } @@ -1075,9 +1098,12 @@ class UsbAudioDevice private constructor(private val context: Context) { data.size, CONTROL_TIMEOUT_MS // timeout ms ) - if (ret >= 0) { + if (ret == data.size) { activeClockSourceId = csId - Log.i(TAG, "setSampleRate($sampleRateHz Hz): SUCCESS with clockSourceId=0x${csId.toString(16)} (wIndex=0x${wIndex.toString(16)}, ret=$ret)") + lastRateWriteTrusted = csId in parsedClockSourceIds || + csId in playbackClockSourceIds || + clockSourceRateMap[csId]?.contains(sampleRateHz) == true + Log.i(TAG, "setSampleRate($sampleRateHz Hz): SUCCESS with clockSourceId=0x${csId.toString(16)} (wIndex=0x${wIndex.toString(16)}, ret=$ret, trusted=$lastRateWriteTrusted)") return true } } @@ -1099,7 +1125,8 @@ class UsbAudioDevice private constructor(private val context: Context) { uac1Data.size, CONTROL_TIMEOUT_MS, ) - if (ret >= 0) { + if (ret == uac1Data.size) { + lastRateWriteTrusted = true Log.i(TAG, "setSampleRate($sampleRateHz Hz): SUCCESS via UAC1 endpoint 0x${epOut.toString(16)}") return true } @@ -1198,7 +1225,7 @@ class UsbAudioDevice private constructor(private val context: Context) { ) // bmRequestType 0x22 = Host-to-Device | Class | Endpoint, SET_CUR (0x01), // wValue = SAMPLING_FREQ_CONTROL (0x01) << 8, wIndex = endpoint address. - return conn.controlTransfer(0x22, 0x01, 0x0100, epOut, data, data.size, CONTROL_TIMEOUT_MS) >= 0 + return conn.controlTransfer(0x22, 0x01, 0x0100, epOut, data, data.size, CONTROL_TIMEOUT_MS) == data.size } private fun readUac1EndpointRate(conn: UsbDeviceConnection): Int {