Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

FFmpeg extension support, audio output preference

David Nashashaa7a4781d570
diff --git a/README.md b/README.md
index 66d46d5b..63f3baf8 100644
--- a/README.md
+++ b/README.md
@@ -101,6 +101,7 @@ Built for Android TV first, StreamVault focuses on the things generic IPTV apps
- App-managed default recording folder with optional custom storage selection
- In-app playback for completed recordings with a visible on-player recording indicator during active capture
- Playback troubleshooting controls for decoder mode, media session behavior, and timeout tuning
+- Bundled Media3 FFmpeg audio fallback for unsupported audio codecs such as AC-3, E-AC-3, DTS, MP2, and TrueHD, with diagnostics and expert compatibility controls
### Movies And Series
@@ -170,6 +171,7 @@ Requirements:
- Android Studio
- Android SDK
- JDK 17 or another Gradle-supported JDK 17 runtime
+- Android NDK only if you want to rebuild the bundled Media3 FFmpeg extension locally
Useful commands:
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 279877f9..b79a86d2 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -53,6 +53,9 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
buildConfigField("String", "OFFICIAL_APPLICATION_ID", "\"com.streamvault.app\"")
buildConfigField("String", "OFFICIAL_SIGNING_CERT_SHA256", "\"$officialSigningCertSha256\"")
+ ndk {
+ abiFilters += listOf("arm64-v8a", "armeabi-v7a")
+ }
}
signingConfigs {
@@ -113,6 +116,7 @@ dependencies {
implementation(project(":domain"))
implementation(project(":data"))
implementation(project(":player"))
+ implementation(files("../player/libs/media3-decoder-ffmpeg-1.9.2.aar"))
// Compose BOM
val composeBom = platform(libs.compose.bom)
diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
index 5f95d7b8..379227a6 100644
--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
@@ -16,8 +16,10 @@ import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.OkHttpXtreamApiService
import com.streamvault.data.remote.xtream.XtreamUrlFactory
import com.streamvault.data.parser.XmltvParser
+import com.streamvault.player.AudioCompatibilityMemoryStore
import com.streamvault.player.Media3PlayerEngine
import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlaybackSupportSnapshotStore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -113,8 +115,16 @@ object NetworkModule {
fun provideMainPlayerEngine(
@ApplicationContext context: Context,
okHttpClient: OkHttpClient,
- playbackCompatibilityRepository: com.streamvault.domain.repository.PlaybackCompatibilityRepository
- ): PlayerEngine = Media3PlayerEngine(context, okHttpClient, playbackCompatibilityRepository)
+ playbackCompatibilityRepository: com.streamvault.domain.repository.PlaybackCompatibilityRepository,
+ audioCompatibilityMemoryStore: AudioCompatibilityMemoryStore,
+ playbackSupportSnapshotStore: PlaybackSupportSnapshotStore
+ ): PlayerEngine = Media3PlayerEngine(
+ context,
+ okHttpClient,
+ playbackCompatibilityRepository,
+ audioCompatibilityMemoryStore,
+ playbackSupportSnapshotStore
+ )
/**
* Factory binding for preview and multiview playback.
@@ -125,8 +135,16 @@ object NetworkModule {
fun provideAuxiliaryPlayerEngine(
@ApplicationContext context: Context,
okHttpClient: OkHttpClient,
- playbackCompatibilityRepository: com.streamvault.domain.repository.PlaybackCompatibilityRepository
- ): PlayerEngine = Media3PlayerEngine(context, okHttpClient, playbackCompatibilityRepository).apply {
+ playbackCompatibilityRepository: com.streamvault.domain.repository.PlaybackCompatibilityRepository,
+ audioCompatibilityMemoryStore: AudioCompatibilityMemoryStore,
+ playbackSupportSnapshotStore: PlaybackSupportSnapshotStore
+ ): PlayerEngine = Media3PlayerEngine(
+ context,
+ okHttpClient,
+ playbackCompatibilityRepository,
+ audioCompatibilityMemoryStore,
+ playbackSupportSnapshotStore
+ ).apply {
enableMediaSession = false
bypassAudioFocus = true
}
diff --git a/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt b/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt
index 9575928e..06003d2d 100644
--- a/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt
+++ b/app/src/main/java/com/streamvault/app/diagnostics/CrashReportStore.kt
@@ -26,6 +26,7 @@ object CrashReportStore {
const val MIME_TYPE_TEXT = "text/plain"
private const val CRASH_DIR = "diagnostics/crash"
private const val LATEST_FILE_NAME = "latest-crash.txt"
+ private const val PLAYBACK_SUPPORT_FILE_NAME = "latest-playback-support.txt"
private const val MAX_REPORT_CHARS = 64_000
private val installed = AtomicBoolean(false)
private val writingCrash = AtomicBoolean(false)
@@ -115,9 +116,22 @@ object CrashReportStore {
appendLine(memorySnapshot())
appendLine()
appendLine("Files Dir Free MB: ${bytesToMb(context.filesDir.freeSpace)}")
+ latestPlaybackSupport(context)?.let { playbackSupport ->
+ appendLine()
+ appendLine("Latest Playback Support:")
+ appendLine(playbackSupport)
+ }
}.take(MAX_REPORT_CHARS)
}
+ private fun latestPlaybackSupport(context: Context): String? {
+ val file = File(context.filesDir, "$CRASH_DIR/$PLAYBACK_SUPPORT_FILE_NAME")
+ if (!file.isFile || file.length() <= 0L) return null
+ return runCatching { file.readText(Charsets.UTF_8).take(MAX_REPORT_CHARS / 2) }.getOrNull()
+ ?.takeIf { it.isNotBlank() }
+ ?.let(::sanitize)
+ }
+
private fun Throwable.stackTraceString(): String {
val writer = StringWriter()
printStackTrace(PrintWriter(writer))
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt
index 01430939..594db131 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt
@@ -11,7 +11,7 @@ internal fun resolveTimeshiftStreamInfo(
streamInfoOverride: StreamInfo?,
currentResolvedStreamInfo: StreamInfo?,
currentResolvedPlaybackUrl: String,
- currentStreamUrl: String,
+ currentStreamUrl: String?,
playbackTitle: String,
currentTitle: String
): StreamInfo? {
@@ -36,20 +36,22 @@ internal fun resolveTimeshiftStreamInfo(
internal fun resolvePlaybackIdentityUrl(
currentResolvedPlaybackUrl: String,
- currentStreamUrl: String
-): String = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
+ currentStreamUrl: String?
+): String = currentResolvedPlaybackUrl.safeTrimmedOrNull()
+ ?: currentStreamUrl.safeTrimmedOrNull()
+ ?: ""
internal fun resolvePlaybackProbeCacheKey(
- currentStreamUrl: String,
+ currentStreamUrl: String?,
url: String
-): String = currentStreamUrl.takeIf { it.isNotBlank() } ?: url
+): String = currentStreamUrl.safeTrimmedOrNull() ?: url
internal fun matchesActivePlaybackSession(
requestVersion: Long,
activeRequestVersion: Long,
expectedLogicalUrl: String? = null,
currentResolvedPlaybackUrl: String,
- currentStreamUrl: String
+ currentStreamUrl: String?
): Boolean {
if (requestVersion != activeRequestVersion) return false
val expectedUrl = expectedLogicalUrl?.takeIf { it.isNotBlank() } ?: return true
@@ -57,5 +59,5 @@ internal fun matchesActivePlaybackSession(
currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
currentStreamUrl = currentStreamUrl
)
- return activeUrl.isBlank() || activeUrl == expectedUrl || currentStreamUrl == expectedUrl
-}
\ No newline at end of file
+ return activeUrl.isBlank() || activeUrl == expectedUrl || currentStreamUrl.safeTrimmedOrNull() == expectedUrl
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index a347e73b..837baf89 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -623,6 +623,20 @@ class PlayerViewModel @Inject constructor(
}
}
}
+ viewModelScope.launch {
+ preferencesRepository.playerAudioOutputPreference
+ .combine(activePlayerEngineFlow) { preference, engine -> engine to preference }
+ .collect { (engine, preference) ->
+ engine.setAudioOutputPreference(preference)
+ }
+ }
+ viewModelScope.launch {
+ preferencesRepository.playerCompatibilityMemoryEnabled
+ .combine(activePlayerEngineFlow) { enabled, engine -> engine to enabled }
+ .collect { (engine, enabled) ->
+ engine.setCompatibilityMemoryEnabled(enabled)
+ }
+ }
viewModelScope.launch {
preferencesRepository.playerSurfaceMode
.combine(activePlayerEngineFlow) { mode, engine -> engine to mode }
@@ -638,6 +652,11 @@ class PlayerViewModel @Inject constructor(
_playerDiagnostics.update {
it.copy(
activeDecoderName = stats.videoDecoderName,
+ activeAudioDecoderName = stats.audioDecoderName,
+ ffmpegAvailable = stats.ffmpegAvailable,
+ ffmpegVersion = stats.ffmpegVersion,
+ audioOutputPath = stats.audioOutputPath,
+ compatibilityDecisionSource = stats.compatibilityDecisionSource,
activeDecoderPolicy = stats.activeDecoderPolicy,
renderSurfaceType = stats.renderSurfaceType,
videoStallCount = stats.videoStallCount,
@@ -1057,6 +1076,13 @@ class PlayerViewModel @Inject constructor(
url = session.streamInfo.url
)
)
+ // Re-prime the adopted engine against the fullscreen surface path.
+ // Preview-to-fullscreen handoff can temporarily leave the reused live
+ // player with an audio-only pipeline until the new render view binds.
+ // Refreshing the current live media source makes the handoff more
+ // robust without re-resolving provider URLs or abandoning the adopted
+ // engine instance.
+ playerEngine.renewStreamUrl(session.streamInfo)
playerEngine.play()
startTokenRenewalMonitoring(session.streamInfo.expirationTime)
maybeStartLiveTimeshift(session.streamInfo)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt
index e5c2c1e3..114c7f77 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt
@@ -44,6 +44,11 @@ data class PlayerDiagnosticsUiState(
val providerSourceLabel: String = "",
val decoderMode: DecoderMode = DecoderMode.AUTO,
val activeDecoderName: String = "Unknown",
+ val activeAudioDecoderName: String = "Unknown",
+ val ffmpegAvailable: Boolean = false,
+ val ffmpegVersion: String? = null,
+ val audioOutputPath: String = "UNKNOWN",
+ val compatibilityDecisionSource: String = "DEFAULT",
val activeDecoderPolicy: String = "AUTO",
val renderSurfaceType: String = "SURFACE_VIEW",
val videoStallCount: Int = 0,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
index f6039590..85ffdcbb 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
@@ -754,6 +754,26 @@ fun DiagnosticsOverlay(
}
PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_audio))
PlayerMetaRow(stringResource(R.string.player_diagnostics_audio_codec), stats.audioCodec)
+ PlayerMetaRow(
+ stringResource(R.string.player_diagnostics_audio_decoder),
+ diagnostics.activeAudioDecoderName
+ )
+ PlayerMetaRow(
+ stringResource(R.string.player_diagnostics_audio_output_path),
+ diagnostics.audioOutputPath
+ )
+ PlayerMetaRow(
+ stringResource(R.string.player_diagnostics_ffmpeg),
+ if (diagnostics.ffmpegAvailable) {
+ diagnostics.ffmpegVersion?.let { "Available ($it)" } ?: "Available"
+ } else {
+ "Unavailable"
+ }
+ )
+ PlayerMetaRow(
+ stringResource(R.string.player_diagnostics_compatibility_source),
+ diagnostics.compatibilityDecisionSource
+ )
val avSyncPathLabel = when {
!diagnostics.audioVideoSyncEnabled -> stringResource(R.string.player_diagnostics_av_sync_stock)
diagnostics.audioVideoSyncSinkActive -> stringResource(R.string.player_diagnostics_av_sync_custom)
@@ -761,6 +781,13 @@ fun DiagnosticsOverlay(
}
PlayerMetaRow(stringResource(R.string.player_diagnostics_av_sync), avSyncPathLabel)
PlayerMetaRow(stringResource(R.string.player_diagnostics_av_offset), formatOffsetLabel(diagnostics.audioVideoOffsetMs))
+ if (diagnostics.compatibilityDecisionSource != "DEFAULT") {
+ PlayerMetaRow(
+ stringResource(R.string.player_diagnostics_compatibility_note),
+ stringResource(R.string.player_diagnostics_compatibility_note_value),
+ maxLines = 3
+ )
+ }
PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_recovery))
diagnostics.lastFailureReason?.let { reason ->
PlayerMetaRow(stringResource(R.string.player_diagnostics_last_failure), reason, maxLines = 3)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt
index 2e9dadc0..d06c0cda 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt
@@ -55,6 +55,7 @@ internal fun SettingsContentPane(
viewModel = viewModel,
timeshiftDepthLabel = screenLabels.timeshiftDepthLabel,
decoderModeLabel = screenLabels.decoderModeLabel,
+ audioOutputPreferenceLabel = screenLabels.audioOutputPreferenceLabel,
surfaceModeLabel = screenLabels.surfaceModeLabel,
playbackSpeedLabel = screenLabels.playbackSpeedLabel,
defaultStopTimerLabel = screenLabels.defaultStopTimerLabel,
@@ -75,6 +76,7 @@ internal fun SettingsContentPane(
speedTestRecommendationLabel = screenLabels.speedTestRecommendationLabel,
onShowTimeshiftDepthDialogChange = { dialogState.showTimeshiftDepthDialog = it },
onShowDecoderModeDialogChange = { dialogState.showDecoderModeDialog = it },
+ onShowAudioOutputPreferenceDialogChange = { dialogState.showAudioOutputPreferenceDialog = it },
onShowSurfaceModeDialogChange = { dialogState.showSurfaceModeDialog = it },
onShowPlaybackSpeedDialogChange = { dialogState.showPlaybackSpeedDialog = it },
onShowDefaultStopTimerDialogChange = { dialogState.showDefaultStopTimerDialog = it },
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt
index 940e16f1..7f1948af 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt
@@ -10,6 +10,7 @@ import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.ChannelNumberingMode
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.DecoderMode
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.GroupedChannelLabelMode
import com.streamvault.domain.model.LiveChannelGroupingMode
import com.streamvault.domain.model.LiveVariantPreferenceMode
@@ -142,6 +143,15 @@ internal fun formatDecoderModeLabel(mode: DecoderMode, context: android.content.
}
}
+internal fun formatAudioOutputPreferenceLabel(
+ preference: AudioOutputPreference,
+ context: android.content.Context
+): String = when (preference) {
+ AudioOutputPreference.AUTO -> context.getString(R.string.settings_audio_output_auto)
+ AudioOutputPreference.PREFER_PASSTHROUGH -> context.getString(R.string.settings_audio_output_prefer_passthrough)
+ AudioOutputPreference.DISABLE_PASSTHROUGH -> context.getString(R.string.settings_audio_output_disable_passthrough)
+}
+
internal fun formatSurfaceModeLabel(
mode: PlayerSurfaceMode,
context: android.content.Context
@@ -308,4 +318,4 @@ internal fun LiveVariantPreferenceMode.descriptionResId(): Int = when (this) {
LiveVariantPreferenceMode.OBSERVED_ONLY -> R.string.settings_live_variant_preference_observed_only_desc
LiveVariantPreferenceMode.BALANCED -> R.string.settings_live_variant_preference_balanced_desc
LiveVariantPreferenceMode.STABILITY_FIRST -> R.string.settings_live_variant_preference_stability_first_desc
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt
index 437dbd99..e3c2cd21 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt
@@ -29,6 +29,7 @@ internal fun LazyListScope.settingsPlaybackSection(
viewModel: SettingsViewModel,
timeshiftDepthLabel: String,
decoderModeLabel: String,
+ audioOutputPreferenceLabel: String,
surfaceModeLabel: String,
playbackSpeedLabel: String,
defaultStopTimerLabel: String,
@@ -49,6 +50,7 @@ internal fun LazyListScope.settingsPlaybackSection(
speedTestRecommendationLabel: String,
onShowTimeshiftDepthDialogChange: (Boolean) -> Unit,
onShowDecoderModeDialogChange: (Boolean) -> Unit,
+ onShowAudioOutputPreferenceDialogChange: (Boolean) -> Unit,
onShowSurfaceModeDialogChange: (Boolean) -> Unit,
onShowPlaybackSpeedDialogChange: (Boolean) -> Unit,
onShowDefaultStopTimerDialogChange: (Boolean) -> Unit,
@@ -201,6 +203,43 @@ internal fun LazyListScope.settingsPlaybackSection(
value = decoderModeLabel,
onClick = { onShowDecoderModeDialogChange(true) }
)
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_audio_output_mode),
+ value = audioOutputPreferenceLabel,
+ onClick = { onShowAudioOutputPreferenceDialogChange(true) }
+ )
+ TvClickableSurface(
+ onClick = {
+ viewModel.setPlayerCompatibilityMemoryEnabled(!uiState.playerCompatibilityMemoryEnabled)
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.Transparent,
+ focusedContainerColor = Primary.copy(alpha = 0.15f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = stringResource(R.string.settings_ffmpeg_compatibility_memory), style = MaterialTheme.typography.bodyMedium, color = OnSurface)
+ Text(text = stringResource(R.string.settings_ffmpeg_compatibility_memory_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))
+ }
+ Switch(
+ checked = uiState.playerCompatibilityMemoryEnabled,
+ onCheckedChange = { viewModel.setPlayerCompatibilityMemoryEnabled(it) }
+ )
+ }
+ }
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_ffmpeg_compatibility_clear),
+ value = stringResource(R.string.settings_ffmpeg_compatibility_clear_value),
+ onClick = viewModel::clearLearnedPlaybackCompatibility
+ )
ClickableSettingsRow(
label = stringResource(R.string.settings_surface_mode),
value = surfaceModeLabel,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt
index c5d7cdc0..9afd79cc 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt
@@ -6,6 +6,7 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.res.stringResource
import com.streamvault.app.R
import com.streamvault.domain.model.AppTimeFormat
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.PlayerSurfaceMode
@@ -22,6 +23,8 @@ internal fun SettingsPlayerPreferenceDialogs(
onShowAudioVideoOffsetDialogChange: (Boolean) -> Unit,
showDecoderModeDialog: Boolean,
onShowDecoderModeDialogChange: (Boolean) -> Unit,
+ showAudioOutputPreferenceDialog: Boolean,
+ onShowAudioOutputPreferenceDialogChange: (Boolean) -> Unit,
showSurfaceModeDialog: Boolean,
onShowSurfaceModeDialogChange: (Boolean) -> Unit,
showTimeshiftDepthDialog: Boolean,
@@ -118,6 +121,32 @@ internal fun SettingsPlayerPreferenceDialogs(
}
}
+ if (showAudioOutputPreferenceDialog) {
+ val outputOptions = remember(context) {
+ listOf(
+ AudioOutputPreference.AUTO to context.getString(R.string.settings_audio_output_auto),
+ AudioOutputPreference.PREFER_PASSTHROUGH to context.getString(R.string.settings_audio_output_prefer_passthrough),
+ AudioOutputPreference.DISABLE_PASSTHROUGH to context.getString(R.string.settings_audio_output_disable_passthrough)
+ )
+ }
+ PremiumSelectionDialog(
+ title = stringResource(R.string.settings_audio_output_mode),
+ onDismiss = { onShowAudioOutputPreferenceDialogChange(false) }
+ ) {
+ outputOptions.forEachIndexed { index, option ->
+ LevelOption(
+ level = index,
+ text = option.second,
+ currentLevel = if (uiState.playerAudioOutputPreference == option.first) index else -1,
+ onSelect = {
+ viewModel.setPlayerAudioOutputPreference(option.first)
+ onShowAudioOutputPreferenceDialogChange(false)
+ }
+ )
+ }
+ }
+ }
+
if (showSurfaceModeDialog) {
val surfaceOptions = remember(context) {
listOf(
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceDialogs.kt
index 274e7dcc..039bbaa4 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceDialogs.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceDialogs.kt
@@ -26,6 +26,8 @@ internal fun SettingsPreferenceDialogs(
onShowAudioVideoOffsetDialogChange: (Boolean) -> Unit,
showDecoderModeDialog: Boolean,
onShowDecoderModeDialogChange: (Boolean) -> Unit,
+ showAudioOutputPreferenceDialog: Boolean,
+ onShowAudioOutputPreferenceDialogChange: (Boolean) -> Unit,
showSurfaceModeDialog: Boolean,
onShowSurfaceModeDialogChange: (Boolean) -> Unit,
showTimeshiftDepthDialog: Boolean,
@@ -73,6 +75,8 @@ internal fun SettingsPreferenceDialogs(
onShowAudioVideoOffsetDialogChange = onShowAudioVideoOffsetDialogChange,
showDecoderModeDialog = showDecoderModeDialog,
onShowDecoderModeDialogChange = onShowDecoderModeDialogChange,
+ showAudioOutputPreferenceDialog = showAudioOutputPreferenceDialog,
+ onShowAudioOutputPreferenceDialogChange = onShowAudioOutputPreferenceDialogChange,
showSurfaceModeDialog = showSurfaceModeDialog,
onShowSurfaceModeDialogChange = onShowSurfaceModeDialogChange,
showTimeshiftDepthDialog = showTimeshiftDepthDialog,
@@ -259,4 +263,4 @@ internal fun SettingsPreferenceDialogs(
)
}
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt
index 49c8871e..52da05cb 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt
@@ -6,6 +6,7 @@ import com.streamvault.app.ui.model.LiveTvChannelMode
import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityMode
import com.streamvault.app.ui.model.VodViewMode
import com.streamvault.domain.model.AppTimeFormat
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ChannelNumberingMode
import com.streamvault.domain.model.DecoderMode
@@ -40,6 +41,8 @@ internal data class SettingsPreferenceSnapshot(
val preferredAudioLanguage: String,
val playerMediaSessionEnabled: Boolean,
val playerDecoderMode: DecoderMode,
+ val playerAudioOutputPreference: AudioOutputPreference,
+ val playerCompatibilityMemoryEnabled: Boolean,
val playerSurfaceMode: PlayerSurfaceMode,
val playerPlaybackSpeed: Float,
val playerAudioVideoSyncEnabled: Boolean,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt
index f9e850df..e3441921 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt
@@ -12,6 +12,8 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferenc
preferredAudioLanguage = snapshot.preferredAudioLanguage,
playerMediaSessionEnabled = snapshot.playerMediaSessionEnabled,
playerDecoderMode = snapshot.playerDecoderMode,
+ playerAudioOutputPreference = snapshot.playerAudioOutputPreference,
+ playerCompatibilityMemoryEnabled = snapshot.playerCompatibilityMemoryEnabled,
playerSurfaceMode = snapshot.playerSurfaceMode,
playerPlaybackSpeed = snapshot.playerPlaybackSpeed,
playerAudioVideoSyncEnabled = snapshot.playerAudioVideoSyncEnabled,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt
index d5120bf2..e25b3160 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt
@@ -24,6 +24,7 @@ internal class SettingsScreenDialogState(
private val showPlaybackSpeedDialogState: MutableState<Boolean>,
private val showAudioVideoOffsetDialogState: MutableState<Boolean>,
private val showDecoderModeDialogState: MutableState<Boolean>,
+ private val showAudioOutputPreferenceDialogState: MutableState<Boolean>,
private val showSurfaceModeDialogState: MutableState<Boolean>,
private val showTimeshiftDepthDialogState: MutableState<Boolean>,
private val showDefaultStopTimerDialogState: MutableState<Boolean>,
@@ -76,6 +77,7 @@ internal class SettingsScreenDialogState(
var showPlaybackSpeedDialog by showPlaybackSpeedDialogState
var showAudioVideoOffsetDialog by showAudioVideoOffsetDialogState
var showDecoderModeDialog by showDecoderModeDialogState
+ var showAudioOutputPreferenceDialog by showAudioOutputPreferenceDialogState
var showSurfaceModeDialog by showSurfaceModeDialogState
var showTimeshiftDepthDialog by showTimeshiftDepthDialogState
var showDefaultStopTimerDialog by showDefaultStopTimerDialogState
@@ -196,6 +198,7 @@ internal fun rememberSettingsScreenDialogState(): SettingsScreenDialogState {
val showPlaybackSpeedDialogState = rememberSaveable { mutableStateOf(false) }
val showAudioVideoOffsetDialogState = rememberSaveable { mutableStateOf(false) }
val showDecoderModeDialogState = rememberSaveable { mutableStateOf(false) }
+ val showAudioOutputPreferenceDialogState = rememberSaveable { mutableStateOf(false) }
val showSurfaceModeDialogState = rememberSaveable { mutableStateOf(false) }
val showTimeshiftDepthDialogState = rememberSaveable { mutableStateOf(false) }
val showDefaultStopTimerDialogState = rememberSaveable { mutableStateOf(false) }
@@ -257,6 +260,7 @@ internal fun rememberSettingsScreenDialogState(): SettingsScreenDialogState {
showPlaybackSpeedDialogState = showPlaybackSpeedDialogState,
showAudioVideoOffsetDialogState = showAudioVideoOffsetDialogState,
showDecoderModeDialogState = showDecoderModeDialogState,
+ showAudioOutputPreferenceDialogState = showAudioOutputPreferenceDialogState,
showSurfaceModeDialogState = showSurfaceModeDialogState,
showTimeshiftDepthDialogState = showTimeshiftDepthDialogState,
showDefaultStopTimerDialogState = showDefaultStopTimerDialogState,
@@ -294,4 +298,4 @@ internal fun rememberSettingsScreenDialogState(): SettingsScreenDialogState {
pendingProtectionLevelState = pendingProtectionLevelState,
pendingDeleteProviderIdState = pendingDeleteProviderIdState
)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt
index e3e11e83..2e5bfd1b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt
@@ -125,6 +125,8 @@ internal fun SettingsScreenDialogs(
onShowAudioVideoOffsetDialogChange = { dialogState.showAudioVideoOffsetDialog = it },
showDecoderModeDialog = dialogState.showDecoderModeDialog,
onShowDecoderModeDialogChange = { dialogState.showDecoderModeDialog = it },
+ showAudioOutputPreferenceDialog = dialogState.showAudioOutputPreferenceDialog,
+ onShowAudioOutputPreferenceDialogChange = { dialogState.showAudioOutputPreferenceDialog = it },
showSurfaceModeDialog = dialogState.showSurfaceModeDialog,
onShowSurfaceModeDialogChange = { dialogState.showSurfaceModeDialog = it },
showTimeshiftDepthDialog = dialogState.showTimeshiftDepthDialog,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenState.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenState.kt
index b9b2bcb4..38cd1c2c 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenState.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenState.kt
@@ -9,6 +9,7 @@ import com.streamvault.app.R
import com.streamvault.app.ui.time.createDateTimeFormat
import com.streamvault.app.util.OfficialBuildStatus
import com.streamvault.domain.model.AppTimeFormat
+import com.streamvault.domain.model.AudioOutputPreference
internal data class SettingsScreenLabels(
val buildVerificationLabel: String,
@@ -18,6 +19,7 @@ internal data class SettingsScreenLabels(
val playbackSpeedLabel: String,
val audioVideoOffsetLabel: String,
val decoderModeLabel: String,
+ val audioOutputPreferenceLabel: String,
val surfaceModeLabel: String,
val controlsTimeoutLabel: String,
val liveOverlayTimeoutLabel: String,
@@ -66,6 +68,9 @@ internal fun rememberSettingsScreenLabels(
val decoderModeLabel = remember(uiState.playerDecoderMode, context) {
formatDecoderModeLabel(uiState.playerDecoderMode, context)
}
+ val audioOutputPreferenceLabel = remember(uiState.playerAudioOutputPreference, context) {
+ formatAudioOutputPreferenceLabel(uiState.playerAudioOutputPreference, context)
+ }
val surfaceModeLabel = remember(uiState.playerSurfaceMode, context) {
formatSurfaceModeLabel(uiState.playerSurfaceMode, context)
}
@@ -147,6 +152,7 @@ internal fun rememberSettingsScreenLabels(
playbackSpeedLabel = playbackSpeedLabel,
audioVideoOffsetLabel = audioVideoOffsetLabel,
decoderModeLabel = decoderModeLabel,
+ audioOutputPreferenceLabel = audioOutputPreferenceLabel,
surfaceModeLabel = surfaceModeLabel,
controlsTimeoutLabel = controlsTimeoutLabel,
liveOverlayTimeoutLabel = liveOverlayTimeoutLabel,
@@ -204,4 +210,4 @@ private fun formatTimeshiftDepthLabel(
15 -> context.getString(R.string.settings_live_timeshift_depth_15)
60 -> context.getString(R.string.settings_live_timeshift_depth_60)
else -> context.getString(R.string.settings_live_timeshift_depth_30)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt
index de262a1f..0c5c0b17 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt
@@ -7,6 +7,7 @@ import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityMode
import com.streamvault.app.ui.model.VodViewMode
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.model.AppTimeFormat
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.ChannelNumberingMode
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.GroupedChannelLabelMode
@@ -39,6 +40,8 @@ internal fun observeSettingsPreferenceSnapshot(
preferredAudioLanguage = "auto",
playerMediaSessionEnabled = true,
playerDecoderMode = DecoderMode.AUTO,
+ playerAudioOutputPreference = AudioOutputPreference.AUTO,
+ playerCompatibilityMemoryEnabled = true,
playerSurfaceMode = com.streamvault.domain.model.PlayerSurfaceMode.AUTO,
playerPlaybackSpeed = 1f,
playerAudioVideoSyncEnabled = false,
@@ -102,6 +105,10 @@ internal fun observeSettingsPreferenceSnapshot(
snapshot.copy(playerMediaSessionEnabled = mediaSessionEnabled)
}.combine(preferencesRepository.playerDecoderMode) { snapshot, decoderMode ->
snapshot.copy(playerDecoderMode = decoderMode)
+ }.combine(preferencesRepository.playerAudioOutputPreference) { snapshot, audioOutputPreference ->
+ snapshot.copy(playerAudioOutputPreference = audioOutputPreference)
+ }.combine(preferencesRepository.playerCompatibilityMemoryEnabled) { snapshot, enabled ->
+ snapshot.copy(playerCompatibilityMemoryEnabled = enabled)
}.combine(preferencesRepository.playerSurfaceMode) { snapshot, surfaceMode ->
snapshot.copy(playerSurfaceMode = surfaceMode)
}.combine(preferencesRepository.playerPlaybackSpeed) { snapshot, playerPlaybackSpeed ->
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt
index c0fd94ed..c7e7e00c 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt
@@ -7,6 +7,7 @@ import com.streamvault.domain.manager.BackupImportPlan
import com.streamvault.domain.manager.BackupPreview
import com.streamvault.domain.model.ActiveLiveSource
import com.streamvault.domain.model.AppTimeFormat
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.ChannelNumberingMode
@@ -55,6 +56,8 @@ data class SettingsUiState(
val preferredAudioLanguage: String = "auto",
val playerMediaSessionEnabled: Boolean = true,
val playerDecoderMode: DecoderMode = DecoderMode.AUTO,
+ val playerAudioOutputPreference: AudioOutputPreference = AudioOutputPreference.AUTO,
+ val playerCompatibilityMemoryEnabled: Boolean = true,
val playerSurfaceMode: PlayerSurfaceMode = PlayerSurfaceMode.AUTO,
val playerPlaybackSpeed: Float = 1f,
val playerAudioVideoSyncEnabled: Boolean = false,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
index 694596e6..343923a6 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
@@ -38,6 +38,7 @@ import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.ActiveLiveSource
import com.streamvault.domain.model.CombinedM3uProfile
import com.streamvault.domain.model.GroupedChannelLabelMode
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.LiveChannelGroupingMode
import com.streamvault.domain.model.LiveVariantPreferenceMode
import com.streamvault.domain.model.ProviderStatus
@@ -66,6 +67,7 @@ import com.streamvault.domain.usecase.GetCustomCategories
import com.streamvault.domain.usecase.SyncProvider
import com.streamvault.domain.usecase.SyncProviderCommand
import com.streamvault.domain.usecase.SyncProviderResult
+import com.streamvault.player.AudioCompatibilityMemoryStore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
@@ -102,7 +104,8 @@ class SettingsViewModel @Inject constructor(
private val epgSourceRepository: com.streamvault.domain.repository.EpgSourceRepository,
private val gitHubReleaseChecker: GitHubReleaseChecker,
private val appUpdateInstaller: AppUpdateInstaller,
- private val getCustomCategories: GetCustomCategories
+ private val getCustomCategories: GetCustomCategories,
+ private val audioCompatibilityMemoryStore: AudioCompatibilityMemoryStore
) : ViewModel() {
private val appContext = application
private val exportBackup = ExportBackup(backupManager)
@@ -663,6 +666,25 @@ class SettingsViewModel @Inject constructor(
}
}
+ fun setPlayerAudioOutputPreference(preference: AudioOutputPreference) {
+ viewModelScope.launch {
+ preferencesRepository.setPlayerAudioOutputPreference(preference)
+ }
+ }
+
+ fun setPlayerCompatibilityMemoryEnabled(enabled: Boolean) {
+ viewModelScope.launch {
+ preferencesRepository.setPlayerCompatibilityMemoryEnabled(enabled)
+ }
+ }
+
+ fun clearLearnedPlaybackCompatibility() {
+ audioCompatibilityMemoryStore.clear()
+ _uiState.update {
+ it.copy(userMessage = appContext.getString(R.string.settings_ffmpeg_compatibility_cleared))
+ }
+ }
+
fun setPlayerSurfaceMode(mode: com.streamvault.domain.model.PlayerSurfaceMode) {
viewModelScope.launch {
preferencesRepository.setPlayerSurfaceMode(mode)
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index fdf19d48..4e961308 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -491,6 +491,15 @@
<string name="settings_decoder_hardware">Hardware Only</string>
<string name="settings_decoder_software">Prefer Software Decoder</string>
<string name="settings_decoder_compatibility">Compatibility Mode</string>
+ <string name="settings_audio_output_mode">Audio Output</string>
+ <string name="settings_audio_output_auto">Auto</string>
+ <string name="settings_audio_output_prefer_passthrough">Prefer passthrough</string>
+ <string name="settings_audio_output_disable_passthrough">Disable passthrough</string>
+ <string name="settings_ffmpeg_compatibility_memory">Remember compatibility fixes</string>
+ <string name="settings_ffmpeg_compatibility_memory_subtitle">Reuse successful FFmpeg-backed audio fixes for this device and stream in future sessions.</string>
+ <string name="settings_ffmpeg_compatibility_clear">Clear learned compatibility data</string>
+ <string name="settings_ffmpeg_compatibility_clear_value">Reset</string>
+ <string name="settings_ffmpeg_compatibility_cleared">Learned playback compatibility data cleared.</string>
<string name="settings_surface_mode">Video Surface</string>
<string name="settings_surface_auto">Auto</string>
<string name="settings_surface_surface_view">SurfaceView</string>
@@ -1091,6 +1100,12 @@
<string name="player_diagnostics_resolution">Resolution</string>
<string name="player_diagnostics_video_codec">Video Codec</string>
<string name="player_diagnostics_audio_codec">Audio Codec</string>
+ <string name="player_diagnostics_audio_decoder">Audio Decoder</string>
+ <string name="player_diagnostics_audio_output_path">Audio Path</string>
+ <string name="player_diagnostics_ffmpeg">FFmpeg</string>
+ <string name="player_diagnostics_compatibility_source">Compatibility Source</string>
+ <string name="player_diagnostics_compatibility_note">Compatibility Note</string>
+ <string name="player_diagnostics_compatibility_note_value">Playback may be using a learned or compatibility-assisted audio path for this stream.</string>
<string name="player_diagnostics_av_offset">A/V Offset</string>
<string name="player_diagnostics_av_sync">A/V Sync</string>
<string name="player_diagnostics_av_sync_stock">Off (stock audio path)</string>
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index e6bb747b..b25ca1db 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -85,6 +85,8 @@ class BackupManagerImpl @Inject constructor(
"liveTvQuickFilterVisibility" to (preferencesRepository.liveTvQuickFilterVisibility.first() ?: "always"),
"playerMediaSessionEnabled" to preferencesRepository.playerMediaSessionEnabled.first().toString(),
"playerDecoderMode" to preferencesRepository.playerDecoderMode.first().name,
+ "playerAudioOutputPreference" to preferencesRepository.playerAudioOutputPreference.first().name,
+ "playerCompatibilityMemoryEnabled" to preferencesRepository.playerCompatibilityMemoryEnabled.first().toString(),
"playerSurfaceMode" to preferencesRepository.playerSurfaceMode.first().name,
"playerPlaybackSpeed" to preferencesRepository.playerPlaybackSpeed.first().toString(),
"playerAudioVideoSyncEnabled" to preferencesRepository.playerAudioVideoSyncEnabled.first().toString(),
@@ -503,6 +505,15 @@ class BackupManagerImpl @Inject constructor(
preferencesRepository.setPlayerDecoderMode(decoderMode)
}
}
+ prefs["playerAudioOutputPreference"]?.takeIf { it.isNotBlank() }?.let { savedPreference ->
+ val preference = com.streamvault.domain.model.AudioOutputPreference.entries
+ .firstOrNull { entry -> entry.name == savedPreference }
+ if (preference != null) {
+ preferencesRepository.setPlayerAudioOutputPreference(preference)
+ }
+ }
+ prefs["playerCompatibilityMemoryEnabled"]?.toBooleanStrictOrNull()
+ ?.let { preferencesRepository.setPlayerCompatibilityMemoryEnabled(it) }
prefs["playerSurfaceMode"]?.takeIf { it.isNotBlank() }?.let { savedMode ->
val surfaceMode = com.streamvault.domain.model.PlayerSurfaceMode.entries
.firstOrNull { entry -> entry.name == savedMode }
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index d53b3bd0..425ddb42 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -17,6 +17,7 @@ import androidx.datastore.preferences.preferencesDataStore
import com.streamvault.data.local.dao.ChannelPreferenceDao
import com.streamvault.data.local.dao.SearchHistoryDao
import com.streamvault.domain.model.GroupedChannelLabelMode
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.ChannelNumberingMode
import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.ContentType
@@ -117,6 +118,8 @@ class PreferencesRepository @Inject constructor(
val PLAYER_MUTED = booleanPreferencesKey("player_muted")
val PLAYER_MEDIA_SESSION_ENABLED = booleanPreferencesKey("player_media_session_enabled")
val PLAYER_DECODER_MODE = stringPreferencesKey("player_decoder_mode")
+ val PLAYER_AUDIO_OUTPUT_PREFERENCE = stringPreferencesKey("player_audio_output_preference")
+ val PLAYER_COMPATIBILITY_MEMORY_ENABLED = booleanPreferencesKey("player_compatibility_memory_enabled")
val PLAYER_SURFACE_MODE = stringPreferencesKey("player_surface_mode")
val PLAYER_PLAYBACK_SPEED = stringPreferencesKey("player_playback_speed")
val PLAYER_AUDIO_VIDEO_SYNC_ENABLED = booleanPreferencesKey("player_av_sync_enabled")
@@ -274,6 +277,16 @@ class PreferencesRepository @Inject constructor(
?: PlayerSurfaceMode.AUTO
}
+ val playerAudioOutputPreference: Flow<AudioOutputPreference> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.PLAYER_AUDIO_OUTPUT_PREFERENCE]
+ ?.let { saved -> AudioOutputPreference.entries.firstOrNull { it.name == saved } }
+ ?: AudioOutputPreference.AUTO
+ }
+
+ val playerCompatibilityMemoryEnabled: Flow<Boolean> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.PLAYER_COMPATIBILITY_MEMORY_ENABLED] ?: true
+ }
+
val playerPlaybackSpeed: Flow<Float> = context.dataStore.data.map { preferences ->
preferences[PreferencesKeys.PLAYER_PLAYBACK_SPEED]
?.toFloatOrNull()
@@ -763,6 +776,18 @@ class PreferencesRepository @Inject constructor(
}
}
+ suspend fun setPlayerAudioOutputPreference(preference: AudioOutputPreference) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.PLAYER_AUDIO_OUTPUT_PREFERENCE] = preference.name
+ }
+ }
+
+ suspend fun setPlayerCompatibilityMemoryEnabled(enabled: Boolean) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.PLAYER_COMPATIBILITY_MEMORY_ENABLED] = enabled
+ }
+ }
+
suspend fun setPlayerSurfaceMode(mode: PlayerSurfaceMode) {
context.dataStore.edit { preferences ->
preferences[PreferencesKeys.PLAYER_SURFACE_MODE] = mode.name
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index e0fcb209..ddfbe764 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -2,6 +2,17 @@
All notable product changes are recorded in this document.
+## [1.0.11] - 2026-05-12
+
+### Added
+
+- Added bundled Media3 FFmpeg audio decoder support for `AC-3`, `E-AC-3`, `DTS`, `MP2`, and `TrueHD` playback fallback.
+- Added automatic one-time software retry for streams with unsupported audio codecs when FFmpeg support is available.
+- Added audio decoder name to player diagnostics so FFmpeg-backed playback can be confirmed from the overlay.
+- Added FFmpeg artifact verification in the player build, plus bundled provenance and LGPL notice docs.
+- Added expert playback settings for audio output policy and persistent compatibility memory.
+- Added richer playback diagnostics for FFmpeg availability/version, audio path classification, and compatibility decision source.
+
## [1.0.10] - 2026-05-11
### Added
diff --git a/docs/FFMPEG-LGPL-NOTICE.md b/docs/FFMPEG-LGPL-NOTICE.md
new file mode 100644
index 00000000..0645186d
--- /dev/null
+++ b/docs/FFMPEG-LGPL-NOTICE.md
@@ -0,0 +1,11 @@
+# FFmpeg LGPL Notice
+
+StreamVault distributes a bundled Media3 FFmpeg audio decoder artifact built for LGPL-compatible use.
+
+Distribution rules for this repo:
+
+- Do not enable GPL or nonfree FFmpeg components in the bundled artifact.
+- Keep the build provenance recorded in `player/libs/media3-decoder-ffmpeg-1.9.2.properties`.
+- Preserve rebuild instructions so recipients can replace or relink the shipped decoder artifact if required by the applicable LGPL obligations.
+
+Operationally, this repo treats the FFmpeg AAR as a versioned bundled dependency rather than rebuilding it in CI.
diff --git a/docs/FFMPEG.md b/docs/FFMPEG.md
new file mode 100644
index 00000000..bdd9942d
--- /dev/null
+++ b/docs/FFMPEG.md
@@ -0,0 +1,23 @@
+# FFmpeg Integration
+
+StreamVault bundles the Media3 FFmpeg audio decoder artifact for unsupported IPTV audio codecs.
+
+Current product scope:
+
+- Audio fallback only
+- Media3 version: `1.9.2`
+- Supported ABIs: `arm64-v8a`, `armeabi-v7a`
+- Enabled decoders: `ac3`, `eac3`, `dca`, `mp2`, `truehd`
+- License target: LGPL-compatible build only
+
+Important product notes:
+
+- Local FFmpeg fallback improves playback on this device only; Cast receivers may still use different codec support.
+- Recordings keep their source codecs. Successful in-app playback does not guarantee the same file will play everywhere else.
+
+Refresh procedure:
+
+1. Rebuild the AndroidX FFmpeg decoder against Media3 `1.9.2`.
+2. Replace `player/libs/media3-decoder-ffmpeg-1.9.2.aar`.
+3. Update `player/libs/media3-decoder-ffmpeg-1.9.2.properties` if provenance changes.
+4. Run `:player:verifyLocalFfmpegArtifact` and the player/app test builds.
diff --git a/domain/src/main/java/com/streamvault/domain/model/AudioOutputPreference.kt b/domain/src/main/java/com/streamvault/domain/model/AudioOutputPreference.kt
new file mode 100644
index 00000000..e3b83a4b
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/AudioOutputPreference.kt
@@ -0,0 +1,7 @@
+package com.streamvault.domain.model
+
+enum class AudioOutputPreference {
+ AUTO,
+ PREFER_PASSTHROUGH,
+ DISABLE_PASSTHROUGH
+}
diff --git a/player/build.gradle.kts b/player/build.gradle.kts
index 50905605..06af058f 100644
--- a/player/build.gradle.kts
+++ b/player/build.gradle.kts
@@ -1,3 +1,5 @@
+import java.util.Properties
+
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
@@ -34,6 +36,55 @@ kover {
}
}
+val ffmpegAarFile = layout.projectDirectory.file("libs/media3-decoder-ffmpeg-1.9.2.aar").asFile
+val ffmpegManifestFile = layout.projectDirectory.file("libs/media3-decoder-ffmpeg-1.9.2.properties").asFile
+
+val verifyLocalFfmpegArtifact by tasks.registering {
+ group = "verification"
+ description = "Verifies the bundled Media3 FFmpeg artifact, metadata, and supported ABIs."
+
+ inputs.file(ffmpegAarFile)
+ inputs.file(ffmpegManifestFile)
+
+ doLast {
+ check(ffmpegAarFile.isFile) {
+ "Required FFmpeg artifact missing: ${ffmpegAarFile.absolutePath}"
+ }
+ check(ffmpegManifestFile.isFile) {
+ "Required FFmpeg manifest missing: ${ffmpegManifestFile.absolutePath}"
+ }
+
+ val manifest = Properties().apply {
+ ffmpegManifestFile.inputStream().use(::load)
+ }
+ check(manifest.getProperty("media3Version") == "1.9.2") {
+ "FFmpeg manifest media3Version must be 1.9.2"
+ }
+
+ val aarEntries = zipTree(ffmpegAarFile).files.map { it.invariantSeparatorsPath }
+ listOf("jni/arm64-v8a/", "jni/armeabi-v7a/").forEach { abiPrefix ->
+ check(aarEntries.any { it.contains(abiPrefix) && it.endsWith(".so") }) {
+ "FFmpeg artifact is missing native libraries under $abiPrefix"
+ }
+ }
+
+ val classesJar = zipTree(ffmpegAarFile).matching { include("classes.jar") }.singleFile
+ val classEntries = zipTree(classesJar).files.map { it.invariantSeparatorsPath }
+ listOf(
+ "androidx/media3/decoder/ffmpeg/FfmpegLibrary.class",
+ "androidx/media3/decoder/ffmpeg/FfmpegAudioRenderer.class"
+ ).forEach { requiredClass ->
+ check(classEntries.any { it.endsWith(requiredClass) }) {
+ "FFmpeg artifact is missing required class $requiredClass"
+ }
+ }
+ }
+}
+
+tasks.named("preBuild").configure {
+ dependsOn(verifyLocalFfmpegArtifact)
+}
+
dependencies {
implementation(project(":domain"))
diff --git a/player/libs/README.md b/player/libs/README.md
new file mode 100644
index 00000000..647371b8
--- /dev/null
+++ b/player/libs/README.md
@@ -0,0 +1,23 @@
+# Media3 FFmpeg Extension Artifact
+
+This directory holds the bundled Media3 FFmpeg decoder artifact used by StreamVault builds.
+
+Bundled artifact:
+
+- `media3-decoder-ffmpeg-1.9.2.aar`
+
+Build provenance for the checked-in artifact:
+
+- Upstream source: `androidx/media` `release` branch
+- Upstream commit used here: `5fb3064497`
+- Media3 version match: `1.9.2`
+- FFmpeg recommendation from upstream README: `release/6.0`
+- Supported ABIs: `arm64-v8a`, `armeabi-v7a`
+- Enabled decoders: `ac3`, `eac3`, `dca`, `mp2`, `truehd`
+- License target: LGPL-compatible build only; do not enable GPL/nonfree codecs
+
+Refresh procedure:
+
+1. Rebuild the AndroidX FFmpeg decoder against the exact Media3 version used by this repo.
+2. Verify the packaged AAR contains the Java decoder classes plus native `ffmpegJNI` libraries for the supported ABIs.
+3. Replace the local artifact in this directory, update the adjacent `.properties` manifest if needed, and rerun `:player:verifyLocalFfmpegArtifact` plus the player unit tests and an app build.
diff --git a/player/libs/media3-decoder-ffmpeg-1.9.2.aar b/player/libs/media3-decoder-ffmpeg-1.9.2.aar
new file mode 100644
index 00000000..108fb889
Binary files /dev/null and b/player/libs/media3-decoder-ffmpeg-1.9.2.aar differ
diff --git a/player/libs/media3-decoder-ffmpeg-1.9.2.properties b/player/libs/media3-decoder-ffmpeg-1.9.2.properties
new file mode 100644
index 00000000..d8ffcc30
--- /dev/null
+++ b/player/libs/media3-decoder-ffmpeg-1.9.2.properties
@@ -0,0 +1,7 @@
+media3Version=1.9.2
+androidxCommit=5fb3064497
+androidxBranch=release
+ffmpegBranch=release/6.0
+enabledDecoders=ac3,eac3,dca,mp2,truehd
+supportedAbis=arm64-v8a,armeabi-v7a
+licenseMode=LGPL-compatible
diff --git a/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.kt b/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.kt
new file mode 100644
index 00000000..b774e471
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/AudioCompatibilityMemoryStore.kt
@@ -0,0 +1,80 @@
+package com.streamvault.player
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.os.Build
+import dagger.hilt.android.qualifiers.ApplicationContext
+import javax.inject.Inject
+import javax.inject.Singleton
+
+data class LearnedAudioCompatibility(
+ val mediaId: String,
+ val streamType: String,
+ val audioMimeTypes: List<String>,
+ val decision: String,
+ val detail: String?,
+ val updatedAtMs: Long
+)
+
+@Singleton
+class AudioCompatibilityMemoryStore @Inject constructor(
+ @ApplicationContext context: Context
+) {
+ private val preferences: SharedPreferences =
+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
+
+ fun lookup(mediaId: String, streamType: String): LearnedAudioCompatibility? {
+ val encoded = preferences.getString(key(mediaId, streamType), null) ?: return null
+ val parts = encoded.split(FIELD_SEPARATOR)
+ if (parts.size < 4) return null
+ return LearnedAudioCompatibility(
+ mediaId = mediaId,
+ streamType = streamType,
+ audioMimeTypes = parts[0]
+ .split(LIST_SEPARATOR)
+ .map(String::trim)
+ .filter(String::isNotEmpty),
+ decision = parts[1],
+ detail = parts[2].takeIf(String::isNotBlank),
+ updatedAtMs = parts[3].toLongOrNull() ?: 0L
+ )
+ }
+
+ fun rememberSoftwareAudioFallback(
+ mediaId: String,
+ streamType: String,
+ audioMimeTypes: List<String>,
+ detail: String?
+ ) {
+ val normalizedMimeTypes = audioMimeTypes
+ .map(String::trim)
+ .filter(String::isNotEmpty)
+ .distinct()
+ preferences.edit()
+ .putString(
+ key(mediaId, streamType),
+ listOf(
+ normalizedMimeTypes.joinToString(LIST_SEPARATOR.toString()),
+ DECISION_SOFTWARE_FFMPEG,
+ detail.orEmpty().replace(FIELD_SEPARATOR.toString(), " "),
+ System.currentTimeMillis().toString()
+ ).joinToString(FIELD_SEPARATOR.toString())
+ )
+ .apply()
+ }
+
+ fun clear() {
+ preferences.edit().clear().apply()
+ }
+
+ private fun key(mediaId: String, streamType: String): String {
+ return "${Build.FINGERPRINT}|${Build.MODEL}|$streamType|$mediaId"
+ }
+
+ companion object {
+ private const val PREFS_NAME = "audio_compatibility_memory"
+ private const val FIELD_SEPARATOR = '|'
+ private const val LIST_SEPARATOR = ','
+ const val DECISION_SOFTWARE_FFMPEG = "software-ffmpeg"
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index 2baf01f4..ff5164db 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -27,6 +27,7 @@ import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
import androidx.media3.exoplayer.video.VideoRendererEventListener
import androidx.media3.session.MediaSession
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.PlaybackCompatibilityKey
import com.streamvault.domain.model.PlaybackCompatibilityRecord
@@ -43,10 +44,12 @@ import com.streamvault.player.playback.PlaybackCodecSelector
import com.streamvault.player.playback.PlaybackCompatibilityProfile
import com.streamvault.player.playback.PlaybackBufferPolicies
import com.streamvault.player.playback.PlaybackErrorCategory
+import com.streamvault.player.playback.FfmpegAudioFallbackRequest
+import com.streamvault.player.playback.FfmpegExtensionSupport
import com.streamvault.player.playback.PlaybackLogSanitizer
+import com.streamvault.player.playback.PlaybackPreparationPlan
+import com.streamvault.player.playback.PlaybackRendererPlan
import com.streamvault.player.playback.PlaybackRetryContext
-import com.streamvault.player.playback.buildPlaybackPreparationPlan
-import com.streamvault.player.playback.buildPlaybackRendererPlan
import com.streamvault.player.playback.PlayerDataSourceFactoryProvider
import com.streamvault.player.playback.PlayerErrorClassifier
import com.streamvault.player.playback.PlayerMediaSourceFactory
@@ -88,7 +91,9 @@ import okhttp3.OkHttpClient
class Media3PlayerEngine @Inject constructor(
@param:ApplicationContext private val context: Context,
private val okHttpClient: OkHttpClient,
- private val playbackCompatibilityRepository: PlaybackCompatibilityRepository
+ private val playbackCompatibilityRepository: PlaybackCompatibilityRepository,
+ private val audioCompatibilityMemoryStore: AudioCompatibilityMemoryStore,
+ private val playbackSupportSnapshotStore: PlaybackSupportSnapshotStore
) : PlayerEngine {
companion object {
@@ -146,6 +151,12 @@ class Media3PlayerEngine @Inject constructor(
private var knownBadDecoderNames: Set<String> = emptySet()
private var knownBadSurfaceTypes: Set<String> = emptySet()
private var selectedVideoDecoderName: String = "Unknown"
+ private var selectedAudioDecoderName: String = "Unknown"
+ private var audioOutputPreference: AudioOutputPreference = AudioOutputPreference.AUTO
+ private var compatibilityMemoryEnabled: Boolean = true
+ private var audioOutputPath: String = "UNKNOWN"
+ private var compatibilityDecisionSource: String = "DEFAULT"
+ private var pendingLearnedAudioFallback: PendingLearnedAudioFallback? = null
private var videoStallCount = 0
private var videoStallRecoveryAttempt = 0
private var videoStallSafeRecoveryPerformed = false
@@ -164,6 +175,7 @@ class Media3PlayerEngine @Inject constructor(
private var retryGeneration = 0L
private var currentBufferIsLive: Boolean? = null
private var audioCodecUnsupportedReported = false
+ private var lastSupportErrorMessage: String? = null
private val _playbackState = MutableStateFlow(PlaybackState.IDLE)
override val playbackState: StateFlow<PlaybackState> = _playbackState.asStateFlow()
@@ -211,6 +223,8 @@ class Media3PlayerEngine @Inject constructor(
private val subtitleStyleController = SubtitleStyleController()
private val viewBinder = PlayerViewBinder(subtitleStyleController)
private val trackController = PlayerTrackController(context)
+ private val ffmpegExtensionSupport = FfmpegExtensionSupport()
+ private var ffmpegAvailability = ffmpegExtensionSupport.availability()
override val availableAudioTracks: StateFlow<List<PlayerTrack>> = trackController.availableAudioTracks
override val availableSubtitleTracks: StateFlow<List<PlayerTrack>> = trackController.availableSubtitleTracks
override val availableVideoTracks: StateFlow<List<PlayerTrack>> = trackController.availableVideoTracks
@@ -253,6 +267,13 @@ class Media3PlayerEngine @Inject constructor(
private var pendingTimeshiftAutoPlay: Boolean = false
private var lastAudioRendererRecoveryAtMs: Long = 0L
+ private data class PendingLearnedAudioFallback(
+ val mediaId: String,
+ val streamType: String,
+ val audioMimeTypes: List<String>,
+ val detail: String?
+ )
+
init {
startEngineCollectors()
}
@@ -279,11 +300,17 @@ class Media3PlayerEngine @Inject constructor(
lastVideoFrameAgoMs = videoStallDetector.lastVideoFrameAgoMs(),
videoStallCount = videoStallCount,
videoDecoderName = selectedVideoDecoderName,
+ audioDecoderName = selectedAudioDecoderName,
+ ffmpegAvailable = ffmpegAvailability.available,
+ ffmpegVersion = ffmpegAvailability.version,
+ audioOutputPath = audioOutputPath,
+ compatibilityDecisionSource = compatibilityDecisionSource,
activeDecoderPolicy = activeDecoderPolicy.name,
renderSurfaceType = _renderSurfaceType.value.name,
audioVideoSyncEnabled = _audioVideoSyncEnabled.value,
audioVideoSyncSinkActive = audioVideoSyncSinkActive
)
+ playbackSupportSnapshotStore.write(buildPlaybackSupportSnapshot())
if (shouldFallbackTextureViewBeforeFirstFrame(stats)) {
fallbackTextureViewSurface("NO_FIRST_FRAME")
continue
@@ -463,6 +490,27 @@ class Media3PlayerEngine @Inject constructor(
audioVideoOffsetUs.set(effectiveOffset * 1_000L)
}
+ override fun setAudioOutputPreference(preference: AudioOutputPreference) {
+ if (audioOutputPreference == preference) return
+ audioOutputPreference = preference
+ val streamInfo = lastStreamInfo ?: return
+ val player = exoPlayer ?: return
+ prepareInternal(
+ streamInfo = streamInfo,
+ preserveRetryState = true,
+ seekPositionMs = player.currentPosition.takeIf { it > 0L },
+ autoPlay = player.playWhenReady
+ )
+ }
+
+ override fun setCompatibilityMemoryEnabled(enabled: Boolean) {
+ compatibilityMemoryEnabled = enabled
+ }
+
+ override fun clearLearnedPlaybackCompatibility() {
+ audioCompatibilityMemoryStore.clear()
+ }
+
@MainThread
override fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig) {
if (ensureNotDisposed("startLiveTimeshift")) return
@@ -683,6 +731,7 @@ class Media3PlayerEngine @Inject constructor(
statsCollector.reset()
videoStallDetector.reset()
selectedVideoDecoderName = "Unknown"
+ selectedAudioDecoderName = "Unknown"
videoStallCount = 0
videoStallRecoveryAttempt = 0
recoveryDecoderPolicyOverride = null
@@ -736,6 +785,8 @@ class Media3PlayerEngine @Inject constructor(
playbackStarted = false
prepareStartMs = System.currentTimeMillis()
audioCodecUnsupportedReported = false
+ pendingLearnedAudioFallback = null
+ lastSupportErrorMessage = null
_error.tryEmit(null)
_mediaTitle.value = null
trackController.resetSelections()
@@ -746,6 +797,9 @@ class Media3PlayerEngine @Inject constructor(
videoStallSafeRecoveryPerformed = false
}
selectedVideoDecoderName = "Unknown"
+ selectedAudioDecoderName = "Unknown"
+ ffmpegAvailability = ffmpegExtensionSupport.availability()
+ audioOutputPath = resolveStartupAudioOutputPath()
val playbackPlan = buildPlaybackPreparationPlan(
streamInfo = streamInfo,
@@ -759,7 +813,21 @@ class Media3PlayerEngine @Inject constructor(
if (!preserveRetryState) {
recoveryDecoderPolicyOverride = null
}
- val preferredDecoderMode = decoderPreferencePolicy.preferredMode(requestedDecoderMode, mediaId)
+ val learnedAudioCompatibility = if (requestedDecoderMode == DecoderMode.AUTO && compatibilityMemoryEnabled) {
+ audioCompatibilityMemoryStore.lookup(mediaId, currentResolvedStreamType.name)
+ } else {
+ null
+ }
+ val preferredDecoderMode = when {
+ requestedDecoderMode != DecoderMode.AUTO -> decoderPreferencePolicy.preferredMode(requestedDecoderMode, mediaId)
+ learnedAudioCompatibility?.decision == AudioCompatibilityMemoryStore.DECISION_SOFTWARE_FFMPEG -> DecoderMode.SOFTWARE
+ else -> decoderPreferencePolicy.preferredMode(requestedDecoderMode, mediaId)
+ }
+ compatibilityDecisionSource = when {
+ requestedDecoderMode != DecoderMode.AUTO -> "USER_SELECTED"
+ learnedAudioCompatibility != null -> "LEARNED_AUDIO_FALLBACK"
+ else -> "DEFAULT"
+ }
val nextDecoderPolicy = recoveryDecoderPolicyOverride ?: resolveActiveDecoderPolicy(
policyModeFor(requestedDecoderMode, preferredDecoderMode)
)
@@ -781,7 +849,7 @@ class Media3PlayerEngine @Inject constructor(
Log.i(
TAG,
- "prepare resolvedStreamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile decoderPreference=$activeDecoderMode activePolicy=$activeDecoderPolicy surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ "prepare resolvedStreamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile decoderPreference=$activeDecoderMode activePolicy=$activeDecoderPolicy audioOutputPreference=$audioOutputPreference compatibilitySource=$compatibilityDecisionSource surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
)
try {
@@ -901,6 +969,7 @@ class Media3PlayerEngine @Inject constructor(
private fun buildRenderersFactory(): DefaultRenderersFactory {
+ logFfmpegAvailability()
val decoderPolicy = activeDecoderPolicy
val badDecoderNames = knownBadDecoderNames
val requestedMode = requestedDecoderMode
@@ -1030,6 +1099,21 @@ class Media3PlayerEngine @Inject constructor(
refreshKnownBadCompatibilityRecords()
}
+ override fun onAudioDecoderInitialized(
+ eventTime: AnalyticsListener.EventTime,
+ decoderName: String,
+ initializedTimestampMs: Long,
+ initializationDurationMs: Long
+ ) {
+ selectedAudioDecoderName = decoderName
+ audioOutputPath = classifyAudioOutputPath(decoderName)
+ _playerStats.value = _playerStats.value.copy(
+ audioDecoderName = decoderName,
+ audioOutputPath = audioOutputPath
+ )
+ Log.i(TAG, "audio-decoder name=$decoderName policy=$activeDecoderPolicy outputPath=$audioOutputPath")
+ }
+
override fun onAudioInputFormatChanged(
eventTime: AnalyticsListener.EventTime,
format: Format,
@@ -1171,16 +1255,20 @@ class Media3PlayerEngine @Inject constructor(
it.mediaTrackGroup.type == C.TRACK_TYPE_AUDIO && it.length > 0
}
if (hasAudioGroups && trackController.availableAudioTracks.value.isEmpty()) {
+ val mimeTypes = audioMimeTypes(tracks)
+ if (tryFfmpegAudioFallback("audio-track-missing", mimeTypes, detail = null)) {
+ return
+ }
audioCodecUnsupportedReported = true
- val mimeTypes = tracks.groups
- .filter { it.mediaTrackGroup.type == C.TRACK_TYPE_AUDIO }
- .flatMap { g -> (0 until g.length).mapNotNull { g.mediaTrackGroup.getFormat(it).sampleMimeType } }
- .distinct()
- .joinToString()
- Log.w(TAG, "audio-codec-unsupported mimeTypes=$mimeTypes target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url.orEmpty())}")
+ val mimeTypeLabel = mimeTypes.joinToString()
+ Log.w(
+ TAG,
+ "audio-codec-unsupported mimeTypes=$mimeTypeLabel target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url.orEmpty())}"
+ )
+ lastSupportErrorMessage = "No compatible audio decoder for this stream ($mimeTypeLabel)."
_error.tryEmit(
PlayerError.DecoderError(
- "No compatible audio decoder for this stream ($mimeTypes). " +
+ "No compatible audio decoder for this stream ($mimeTypeLabel). " +
"The audio codec is not supported on this device."
)
)
@@ -1256,8 +1344,19 @@ class Media3PlayerEngine @Inject constructor(
playbackStarted = true
Log.i(
TAG,
- "$reason streamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url)}"
+ "$reason streamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile audioPath=$audioOutputPath compatibilitySource=$compatibilityDecisionSource target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url)}"
)
+ pendingLearnedAudioFallback?.let { learned ->
+ if (compatibilityMemoryEnabled && activeDecoderMode == DecoderMode.SOFTWARE) {
+ audioCompatibilityMemoryStore.rememberSoftwareAudioFallback(
+ mediaId = learned.mediaId,
+ streamType = learned.streamType,
+ audioMimeTypes = learned.audioMimeTypes,
+ detail = learned.detail
+ )
+ }
+ pendingLearnedAudioFallback = null
+ }
recordCompatibilitySuccess()
refreshKnownBadCompatibilityRecords()
}
@@ -1530,16 +1629,29 @@ class Media3PlayerEngine @Inject constructor(
private fun handleAudioRendererIssue(error: Exception, source: String) {
val streamInfo = lastStreamInfo
if (streamInfo == null) {
+ lastSupportErrorMessage = error.message ?: "Audio playback failed."
_error.tryEmit(PlayerError.DecoderError(error.message ?: "Audio playback failed."))
return
}
+ if (
+ source == "audio-codec" &&
+ tryFfmpegAudioFallback(
+ trigger = "audio-renderer-$source",
+ mimeTypes = audioMimeTypes(),
+ detail = error.message
+ )
+ ) {
+ return
+ }
+
val now = System.currentTimeMillis()
if (now - lastAudioRendererRecoveryAtMs < AUDIO_RENDERER_RECOVERY_COOLDOWN_MS) {
Log.e(
TAG,
"audio-renderer-failed source=$source target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
)
+ lastSupportErrorMessage = error.message ?: "Audio playback failed for this stream."
_error.tryEmit(
PlayerError.DecoderError(
error.message ?: "Audio playback failed for this stream."
@@ -1569,6 +1681,181 @@ class Media3PlayerEngine @Inject constructor(
)
}
+ private fun tryFfmpegAudioFallback(
+ trigger: String,
+ mimeTypes: List<String>,
+ detail: String?
+ ): Boolean {
+ val streamInfo = lastStreamInfo ?: return false
+ val mediaId = lastMediaId ?: return false
+ val availability = ffmpegExtensionSupport.availability()
+ ffmpegAvailability = availability
+ if (!availability.available) {
+ compatibilityDecisionSource = "FFMPEG_UNAVAILABLE"
+ Log.w(
+ TAG,
+ "ffmpeg-audio-fallback unavailable trigger=$trigger target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
+ return false
+ }
+ val supportedMimeTypes = ffmpegExtensionSupport.supportedAudioMimeTypes(mimeTypes)
+ val effectiveSupportedMimeTypes = if (mimeTypes.isEmpty()) listOf("<unknown>") else supportedMimeTypes
+ if (mimeTypes.isNotEmpty() && supportedMimeTypes.isEmpty()) {
+ compatibilityDecisionSource = "FFMPEG_UNSUPPORTED_AUDIO"
+ Log.w(
+ TAG,
+ "ffmpeg-audio-fallback unsupported trigger=$trigger mimeTypes=${mimeTypes.joinToString()} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
+ return false
+ }
+ val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(requestedDecoderMode, mediaId)
+ if (
+ !shouldAttemptFfmpegAudioFallback(
+ FfmpegAudioFallbackRequest(
+ requestedMode = requestedDecoderMode,
+ extensionAvailable = availability.available,
+ supportedMimeTypes = effectiveSupportedMimeTypes,
+ fallbackMode = fallbackMode
+ )
+ )
+ ) {
+ return false
+ }
+ compatibilityDecisionSource = "FFMPEG_RETRY:$trigger"
+ pendingLearnedAudioFallback = PendingLearnedAudioFallback(
+ mediaId = mediaId,
+ streamType = currentResolvedStreamType.name,
+ audioMimeTypes = supportedMimeTypes,
+ detail = detail
+ )
+ audioOutputPath = "FFMPEG_RETRY_PENDING"
+
+ val wasPlaying = exoPlayer?.playWhenReady ?: true
+ val seekPosition = exoPlayer?.currentPosition
+ ?.takeIf { currentResolvedStreamType == ResolvedStreamType.PROGRESSIVE && it > 0L }
+ Log.w(
+ TAG,
+ "ffmpeg-audio-fallback retry trigger=$trigger supportedMimeTypes=${effectiveSupportedMimeTypes.joinToString()} version=${availability.version ?: "unknown"} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} detail=${PlaybackLogSanitizer.sanitizeMessage(detail)}"
+ )
+
+ retryJob?.cancel()
+ retryJob = null
+ _retryStatus.value = null
+ prepareInternal(
+ streamInfo = streamInfo,
+ preserveRetryState = false,
+ seekPositionMs = seekPosition,
+ autoPlay = wasPlaying
+ )
+ return true
+ }
+
+ private fun audioMimeTypes(
+ tracks: androidx.media3.common.Tracks? = exoPlayer?.currentTracks
+ ): List<String> {
+ val fromTracks = tracks?.groups
+ ?.filter { it.mediaTrackGroup.type == C.TRACK_TYPE_AUDIO }
+ ?.flatMap { group ->
+ (0 until group.length).mapNotNull { index ->
+ group.mediaTrackGroup.getFormat(index).sampleMimeType
+ }
+ }
+ ?.distinct()
+ .orEmpty()
+ if (fromTracks.isNotEmpty()) return fromTracks
+ val codec = _playerStats.value.audioCodec
+ return codec.takeUnless { it.isBlank() || it.equals("Unknown", ignoreCase = true) }
+ ?.let(::listOf)
+ .orEmpty()
+ }
+
+ private fun logFfmpegAvailability() {
+ val availability = ffmpegAvailability
+ Log.i(
+ TAG,
+ "ffmpeg-extension available=${availability.available} version=${availability.version ?: "unavailable"}"
+ )
+ }
+
+ private fun buildPlaybackSupportSnapshot(): String = buildString {
+ appendLine("StreamVault Playback Support Snapshot")
+ appendLine("requestedDecoderMode=$requestedDecoderMode")
+ appendLine("activeDecoderMode=$activeDecoderMode")
+ appendLine("activeDecoderPolicy=$activeDecoderPolicy")
+ appendLine("audioOutputPreference=$audioOutputPreference")
+ appendLine("compatibilityDecisionSource=$compatibilityDecisionSource")
+ appendLine("ffmpegAvailable=${ffmpegAvailability.available}")
+ appendLine("ffmpegVersion=${ffmpegAvailability.version ?: "unavailable"}")
+ appendLine("audioOutputPath=$audioOutputPath")
+ appendLine("videoDecoderName=$selectedVideoDecoderName")
+ appendLine("audioDecoderName=$selectedAudioDecoderName")
+ appendLine("videoCodec=${_playerStats.value.videoCodec}")
+ appendLine("audioCodec=${_playerStats.value.audioCodec}")
+ appendLine("streamType=$currentResolvedStreamType")
+ appendLine("target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url)}")
+ appendLine("lastError=${PlaybackLogSanitizer.sanitizeMessage(lastSupportErrorMessage)}")
+ }
+
+ private fun resolveStartupAudioOutputPath(): String = when {
+ audioOutputPreference == AudioOutputPreference.PREFER_PASSTHROUGH -> "PASSTHROUGH_PREFERRED"
+ audioOutputPreference == AudioOutputPreference.DISABLE_PASSTHROUGH -> "PASSTHROUGH_DISABLED"
+ activeDecoderMode == DecoderMode.SOFTWARE -> "SOFTWARE_PREFERRED"
+ else -> "AUTO"
+ }
+
+ private fun classifyAudioOutputPath(decoderName: String): String {
+ val normalized = decoderName.lowercase()
+ return when {
+ "ffmpeg" in normalized -> "FFMPEG_SOFTWARE"
+ activeDecoderMode == DecoderMode.SOFTWARE -> "PLATFORM_SOFTWARE"
+ else -> "PLATFORM_DECODER"
+ }
+ }
+
+ private fun buildPlaybackPreparationPlan(
+ streamInfo: StreamInfo,
+ preload: Boolean,
+ playbackStarted: () -> Boolean
+ ): PlaybackPreparationPlan {
+ val resolvedStreamType = StreamTypeResolver.resolve(streamInfo)
+ val timeoutProfile = PlayerTimeoutProfile.resolve(streamInfo, resolvedStreamType, preload = preload)
+ val retryContext = PlaybackRetryContext(resolvedStreamType, timeoutProfile)
+ return PlaybackPreparationPlan(
+ resolvedStreamType = resolvedStreamType,
+ timeoutProfile = timeoutProfile,
+ retryContext = retryContext,
+ retryPolicy = PlayerRetryPolicy(retryContext) { playbackStarted() }
+ )
+ }
+
+ private fun buildPlaybackRendererPlan(
+ requestedMode: DecoderMode,
+ decoderPolicy: ActiveDecoderPolicy,
+ useAudioVideoSyncSink: Boolean,
+ useVideoRendererWorkaround: Boolean
+ ): PlaybackRendererPlan {
+ val useManagedCodecSelector = requestedMode != DecoderMode.AUTO && decoderPolicy != ActiveDecoderPolicy.AUTO
+ val useEffectiveVideoRendererWorkaround = useVideoRendererWorkaround && requestedMode != DecoderMode.AUTO
+ val renderPath = buildList {
+ if (useAudioVideoSyncSink) add("av-sync-sink")
+ if (useEffectiveVideoRendererWorkaround) add("decoder-reuse-workaround")
+ if (useManagedCodecSelector) add("managed-codec-selector")
+ }.ifEmpty { listOf("stock-media3") }.joinToString("+")
+ return PlaybackRendererPlan(
+ useAudioVideoSyncSink = useAudioVideoSyncSink,
+ useVideoRendererWorkaround = useEffectiveVideoRendererWorkaround,
+ useManagedCodecSelector = useManagedCodecSelector,
+ renderPath = renderPath
+ )
+ }
+
+ private fun shouldAttemptFfmpegAudioFallback(request: FfmpegAudioFallbackRequest): Boolean {
+ if (request.requestedMode != DecoderMode.AUTO) return false
+ if (!request.extensionAvailable) return false
+ if (request.fallbackMode != DecoderMode.SOFTWARE) return false
+ return request.supportedMimeTypes.isNotEmpty()
+ }
+
private fun handlePlaybackSetupFailure(
error: Exception,
streamInfo: StreamInfo,
@@ -1599,6 +1886,7 @@ class Media3PlayerEngine @Inject constructor(
recreatePlayer()
_retryStatus.value = null
+ lastSupportErrorMessage = error.message
_error.tryEmit(PlayerError.fromException(error))
_playbackState.value = PlaybackState.ERROR
}
@@ -1614,6 +1902,7 @@ class Media3PlayerEngine @Inject constructor(
if (streamInfo == null || mediaId == null || retryPolicy == null || retryContext == null) {
_retryStatus.value = null
+ lastSupportErrorMessage = error.message
_error.tryEmit(PlayerError.fromException(error))
_playbackState.value = PlaybackState.ERROR
return
@@ -1684,6 +1973,7 @@ class Media3PlayerEngine @Inject constructor(
TAG,
"fatal-error category=$category target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
)
+ lastSupportErrorMessage = error.message
_error.tryEmit(PlayerError.fromException(error))
_playbackState.value = PlaybackState.ERROR
}
diff --git a/player/src/main/java/com/streamvault/player/PlaybackSupportSnapshotStore.kt b/player/src/main/java/com/streamvault/player/PlaybackSupportSnapshotStore.kt
new file mode 100644
index 00000000..5ec15eb3
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/PlaybackSupportSnapshotStore.kt
@@ -0,0 +1,22 @@
+package com.streamvault.player
+
+import android.content.Context
+import dagger.hilt.android.qualifiers.ApplicationContext
+import java.io.File
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class PlaybackSupportSnapshotStore @Inject constructor(
+ @ApplicationContext context: Context
+) {
+ private val reportFile: File = File(context.filesDir, "diagnostics/crash/latest-playback-support.txt").also {
+ it.parentFile?.mkdirs()
+ }
+
+ fun write(report: String) {
+ runCatching {
+ reportFile.writeText(report, Charsets.UTF_8)
+ }
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index 6052660b..0e28e069 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -2,6 +2,7 @@ package com.streamvault.player
import android.content.Context
import android.view.View
+import com.streamvault.domain.model.AudioOutputPreference
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.PlayerSurfaceMode
import com.streamvault.domain.model.DrmScheme
@@ -74,6 +75,9 @@ interface PlayerEngine {
fun setPlaybackSpeed(speed: Float)
fun setAudioVideoSyncEnabled(enabled: Boolean)
fun setAudioVideoOffsetMs(offsetMs: Int)
+ fun setAudioOutputPreference(preference: AudioOutputPreference)
+ fun setCompatibilityMemoryEnabled(enabled: Boolean)
+ fun clearLearnedPlaybackCompatibility()
fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig)
fun stopLiveTimeshift()
fun seekToLiveEdge()
@@ -144,6 +148,11 @@ data class PlayerStats(
val videoCodec: String = "Unknown",
val audioCodec: String = "Unknown",
val videoDecoderName: String = "Unknown",
+ val audioDecoderName: String = "Unknown",
+ val ffmpegAvailable: Boolean = false,
+ val ffmpegVersion: String? = null,
+ val audioOutputPath: String = "UNKNOWN",
+ val compatibilityDecisionSource: String = "DEFAULT",
val activeDecoderPolicy: String = "AUTO",
val renderSurfaceType: String = "SURFACE_VIEW",
val audioVideoSyncEnabled: Boolean = false,
@@ -158,7 +167,52 @@ data class PlayerStats(
val bufferedDurationMs: Long = 0,
val rebufferCount: Int = 0,
val ttffMs: Long = 0
-)
+) {
+ @Suppress("LongParameterList")
+ constructor(
+ videoCodec: String,
+ audioCodec: String,
+ videoDecoderName: String,
+ audioDecoderName: String,
+ activeDecoderPolicy: String,
+ renderSurfaceType: String,
+ audioVideoSyncEnabled: Boolean,
+ audioVideoSyncSinkActive: Boolean,
+ videoStallCount: Int,
+ lastVideoFrameAgoMs: Long,
+ videoBitrate: Int,
+ droppedFrames: Int,
+ width: Int,
+ height: Int,
+ bandwidthEstimate: Long,
+ bufferedDurationMs: Long,
+ rebufferCount: Int,
+ ttffMs: Long
+ ) : this(
+ videoCodec = videoCodec,
+ audioCodec = audioCodec,
+ videoDecoderName = videoDecoderName,
+ audioDecoderName = audioDecoderName,
+ ffmpegAvailable = false,
+ ffmpegVersion = null,
+ audioOutputPath = "UNKNOWN",
+ compatibilityDecisionSource = "DEFAULT",
+ activeDecoderPolicy = activeDecoderPolicy,
+ renderSurfaceType = renderSurfaceType,
+ audioVideoSyncEnabled = audioVideoSyncEnabled,
+ audioVideoSyncSinkActive = audioVideoSyncSinkActive,
+ videoStallCount = videoStallCount,
+ lastVideoFrameAgoMs = lastVideoFrameAgoMs,
+ videoBitrate = videoBitrate,
+ droppedFrames = droppedFrames,
+ width = width,
+ height = height,
+ bandwidthEstimate = bandwidthEstimate,
+ bufferedDurationMs = bufferedDurationMs,
+ rebufferCount = rebufferCount,
+ ttffMs = ttffMs
+ )
+}
sealed class PlayerError(val message: String) {
class NetworkError(message: String) : PlayerError(message)
diff --git a/player/src/main/java/com/streamvault/player/playback/FfmpegExtensionSupport.kt b/player/src/main/java/com/streamvault/player/playback/FfmpegExtensionSupport.kt
new file mode 100644
index 00000000..fc9a0132
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/FfmpegExtensionSupport.kt
@@ -0,0 +1,76 @@
+package com.streamvault.player.playback
+
+import androidx.annotation.VisibleForTesting
+import androidx.media3.common.util.UnstableApi
+import com.streamvault.domain.model.DecoderMode
+
+internal data class FfmpegExtensionAvailability(
+ val available: Boolean,
+ val version: String?
+)
+
+internal data class FfmpegAudioFallbackRequest(
+ val requestedMode: DecoderMode,
+ val extensionAvailable: Boolean,
+ val supportedMimeTypes: List<String>,
+ val fallbackMode: DecoderMode?
+)
+
+internal fun shouldAttemptFfmpegAudioFallback(request: FfmpegAudioFallbackRequest): Boolean {
+ if (request.requestedMode != DecoderMode.AUTO) return false
+ if (!request.extensionAvailable) return false
+ if (request.fallbackMode != DecoderMode.SOFTWARE) return false
+ return request.supportedMimeTypes.isNotEmpty()
+}
+
+@UnstableApi
+internal class FfmpegExtensionSupport(
+ private val reflectiveLibrary: ReflectiveFfmpegLibrary = ReflectiveFfmpegLibrary()
+) {
+ fun availability(): FfmpegExtensionAvailability = reflectiveLibrary.availability()
+
+ fun supportsFormat(mimeType: String?): Boolean = reflectiveLibrary.supportsFormat(mimeType)
+
+ fun supportedAudioMimeTypes(mimeTypes: Collection<String>): List<String> =
+ mimeTypes
+ .map(String::trim)
+ .filter(String::isNotEmpty)
+ .distinct()
+ .filter(::supportsFormat)
+}
+
+@UnstableApi
+internal class ReflectiveFfmpegLibrary(
+ @VisibleForTesting
+ internal val libraryClassProvider: () -> Class<*>? = {
+ runCatching { Class.forName(FFMPEG_LIBRARY_CLASS_NAME) }.getOrNull()
+ }
+) {
+ fun availability(): FfmpegExtensionAvailability {
+ val libraryClass = libraryClassProvider() ?: return FfmpegExtensionAvailability(false, null)
+ val available = invokeBooleanStatic(libraryClass, "isAvailable") ?: return FfmpegExtensionAvailability(false, null)
+ val version = if (available) invokeStringStatic(libraryClass, "getVersion") else null
+ return FfmpegExtensionAvailability(available = available, version = version)
+ }
+
+ fun supportsFormat(mimeType: String?): Boolean {
+ if (mimeType.isNullOrBlank()) return false
+ val libraryClass = libraryClassProvider() ?: return false
+ return invokeBooleanStatic(libraryClass, "supportsFormat", mimeType.trim()) ?: false
+ }
+
+ private fun invokeBooleanStatic(clazz: Class<*>, methodName: String, vararg args: Any): Boolean? =
+ runCatching {
+ val parameterTypes = args.map { it::class.java }.toTypedArray()
+ clazz.getMethod(methodName, *parameterTypes).invoke(null, *args) as? Boolean
+ }.getOrNull()
+
+ private fun invokeStringStatic(clazz: Class<*>, methodName: String): String? =
+ runCatching {
+ clazz.getMethod(methodName).invoke(null) as? String
+ }.getOrNull()
+
+ private companion object {
+ private const val FFMPEG_LIBRARY_CLASS_NAME = "androidx.media3.decoder.ffmpeg.FfmpegLibrary"
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/FfmpegAudioFallbackPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/FfmpegAudioFallbackPolicyTest.kt
new file mode 100644
index 00000000..a2dd7921
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/FfmpegAudioFallbackPolicyTest.kt
@@ -0,0 +1,73 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.DecoderMode
+import org.junit.Test
+
+class FfmpegAudioFallbackPolicyTest {
+
+ @Test
+ fun `auto with supported mime and available extension retries once in software`() {
+ assertThat(
+ shouldAttemptFfmpegAudioFallback(
+ FfmpegAudioFallbackRequest(
+ requestedMode = DecoderMode.AUTO,
+ extensionAvailable = true,
+ supportedMimeTypes = listOf("audio/ac3"),
+ fallbackMode = DecoderMode.SOFTWARE
+ )
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `fallback is skipped when extension is unavailable`() {
+ assertThat(
+ shouldAttemptFfmpegAudioFallback(
+ FfmpegAudioFallbackRequest(
+ requestedMode = DecoderMode.AUTO,
+ extensionAvailable = false,
+ supportedMimeTypes = listOf("audio/ac3"),
+ fallbackMode = DecoderMode.SOFTWARE
+ )
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `fallback is skipped for explicit software and compatibility modes`() {
+ val software = shouldAttemptFfmpegAudioFallback(
+ FfmpegAudioFallbackRequest(
+ requestedMode = DecoderMode.SOFTWARE,
+ extensionAvailable = true,
+ supportedMimeTypes = listOf("audio/ac3"),
+ fallbackMode = DecoderMode.SOFTWARE
+ )
+ )
+ val compatibility = shouldAttemptFfmpegAudioFallback(
+ FfmpegAudioFallbackRequest(
+ requestedMode = DecoderMode.COMPATIBILITY,
+ extensionAvailable = true,
+ supportedMimeTypes = listOf("audio/ac3"),
+ fallbackMode = DecoderMode.SOFTWARE
+ )
+ )
+
+ assertThat(software).isFalse()
+ assertThat(compatibility).isFalse()
+ }
+
+ @Test
+ fun `fallback is skipped when no supported mime types remain`() {
+ assertThat(
+ shouldAttemptFfmpegAudioFallback(
+ FfmpegAudioFallbackRequest(
+ requestedMode = DecoderMode.AUTO,
+ extensionAvailable = true,
+ supportedMimeTypes = emptyList(),
+ fallbackMode = DecoderMode.SOFTWARE
+ )
+ )
+ ).isFalse()
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/FfmpegExtensionSupportTest.kt b/player/src/test/java/com/streamvault/player/playback/FfmpegExtensionSupportTest.kt
new file mode 100644
index 00000000..e0637747
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/FfmpegExtensionSupportTest.kt
@@ -0,0 +1,53 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class FfmpegExtensionSupportTest {
+
+ @Test
+ fun `availability is unavailable when ffmpeg class is missing`() {
+ val library = ReflectiveFfmpegLibrary(libraryClassProvider = { null })
+
+ assertThat(library.availability()).isEqualTo(FfmpegExtensionAvailability(false, null))
+ }
+
+ @Test
+ fun `availability reports version when ffmpeg library is available`() {
+ FakeFfmpegLibrary.available = true
+ FakeFfmpegLibrary.reportedVersion = "6.0-test"
+
+ val library = ReflectiveFfmpegLibrary(libraryClassProvider = { FakeFfmpegLibrary::class.java })
+
+ assertThat(library.availability()).isEqualTo(FfmpegExtensionAvailability(true, "6.0-test"))
+ }
+
+ @Test
+ fun `supports format delegates reflectively`() {
+ FakeFfmpegLibrary.available = true
+ FakeFfmpegLibrary.supportedMimeTypes = mutableSetOf("audio/ac3", "audio/eac3")
+ val support = FfmpegExtensionSupport(
+ ReflectiveFfmpegLibrary(libraryClassProvider = { FakeFfmpegLibrary::class.java })
+ )
+
+ assertThat(support.supportsFormat("audio/ac3")).isTrue()
+ assertThat(support.supportsFormat("audio/mp4a-latm")).isFalse()
+ assertThat(support.supportedAudioMimeTypes(listOf("audio/eac3", "audio/eac3", " ")))
+ .containsExactly("audio/eac3")
+ }
+
+ object FakeFfmpegLibrary {
+ @JvmStatic var available: Boolean = false
+ @JvmStatic var reportedVersion: String? = null
+ @JvmStatic var supportedMimeTypes: MutableSet<String> = mutableSetOf()
+
+ @JvmStatic
+ fun isAvailable(): Boolean = available
+
+ @JvmStatic
+ fun getVersion(): String? = reportedVersion
+
+ @JvmStatic
+ fun supportsFormat(mimeType: String): Boolean = available && mimeType in supportedMimeTypes
+ }
+}