Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.siloserver.silo.common.player

import androidx.annotation.OptIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.media3.common.util.UnstableApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import org.siloserver.silo.common.player.backend.VideoPlaybackBackend

private const val REMOUNT_RETRY_MS = 1_000L

/**
* Mounts the stream again while it keeps bitstreaming audio that the chosen
* speed needs decoded (see [PlaybackSpeedAudioPolicy.needsRemount]).
*
* [presetsApplied]: presets asking for decoded audio are in force, so the sink
* already refuses the bitstream and only the mounted stream still carries it.
* [remount] returns whether it started a remount. The player refuses one while
* a load, a recovery, or another mount is under way, so this tries again until
* the stream decodes or the speed is back at 1x. Re-checks whenever a new
* AudioTrack starts.
*/
@OptIn(UnstableApi::class)
@Composable
fun DecodedAudioRemountEffect(
backend: VideoPlaybackBackend?,
presetsApplied: Boolean,
audioOutput: StateFlow<AudioOutput?>,
remount: () -> Boolean,
) {
val output by audioOutput.collectAsState()
val currentRemount by rememberUpdatedState(remount)
LaunchedEffect(backend, presetsApplied, output) {
if (backend == null || !presetsApplied) return@LaunchedEffect
while (backend.needsRemountForDecodedAudio()) {
if (currentRemount()) return@LaunchedEffect
delay(REMOUNT_RETRY_MS)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,20 @@ class PlaybackAnalyticsListener : AnalyticsListener {
* again once audio is disabled or the player is released.
*/
val audioOutputPath: StateFlow<AudioOutputPath?> = _audioOutputPath.asStateFlow()

private val _audioOutput = MutableStateFlow<AudioOutput?>(null)

/**
* [audioOutputPath] plus whether that AudioTrack is tunneled; null at the
* same times. Each new AudioTrack emits, even one configured like the last.
*/
val audioOutput: StateFlow<AudioOutput?> = _audioOutput.asStateFlow()
private var audioTracksInitialized = 0L

/** The audio format the renderer was last given, or null while audio is disabled. */
@Volatile
var audioInputFormat: Format? = null
private set
private var diagnosticsStats = PlayerStatsSnapshot()
private val diagnosticsCadence = DiagnosticsStatsCadence()
private var playWhenReady = true
Expand Down Expand Up @@ -149,18 +163,26 @@ class PlaybackAnalyticsListener : AnalyticsListener {
eventTime: AnalyticsListener.EventTime,
audioTrackConfig: AudioSink.AudioTrackConfig,
) {
_audioOutputPath.value = audioOutputPathOf(audioTrackConfig)
val path = audioOutputPathOf(audioTrackConfig)
_audioOutputPath.value = path
_audioOutput.value = AudioOutput(path, audioTrackConfig.tunneling, trackNumber = ++audioTracksInitialized)
}

// onAudioTrackReleased is deliberately ignored: DefaultAudioSink releases
// the old track asynchronously, so the release can land after the
// replacement track's initialization and would clear a current value.
override fun onAudioDisabled(eventTime: AnalyticsListener.EventTime, decoderCounters: DecoderCounters) {
_audioOutputPath.value = null
clearAudioOutput()
}

override fun onPlayerReleased(eventTime: AnalyticsListener.EventTime) {
clearAudioOutput()
}

private fun clearAudioOutput() {
_audioOutputPath.value = null
_audioOutput.value = null
audioInputFormat = null
}

override fun onVideoInputFormatChanged(
Expand All @@ -186,6 +208,7 @@ class PlaybackAnalyticsListener : AnalyticsListener {
format: Format,
decoderReuseEvaluation: androidx.media3.exoplayer.DecoderReuseEvaluation?,
) {
audioInputFormat = format
DiagnosticsPlaybackLogger.audioFormatChanged(format.sampleMimeType)
emit(Event.AudioFormatChanged(format))
}
Expand Down Expand Up @@ -272,6 +295,13 @@ enum class AudioOutputPath {
Offload,
}

/**
* The current AudioTrack; see [PlaybackAnalyticsListener.audioOutput].
* [trackNumber] counts the AudioTracks a listener has seen, so a replacement
* never equals the track it replaces.
*/
data class AudioOutput(val path: AudioOutputPath, val tunneled: Boolean, val trackNumber: Long = 0L)

@UnstableApi
private fun audioOutputPathOf(config: AudioSink.AudioTrackConfig): AudioOutputPath = when {
config.offload -> AudioOutputPath.Offload
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package org.siloserver.silo.common.player

import androidx.annotation.OptIn
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import kotlin.math.abs

/**
* What the audio path needs for a playback speed other than 1x to take effect.
*
* Media3 changes speed only on decoded, untunneled PCM. Its DefaultAudioSink
* holds a bitstream (HDMI passthrough, offload) and tunneled audio at 1x, and
* because the audio renderer is the playback clock the video falls back to 1x
* with it. A TV that sends Dolby to a receiver, or one that tunnels, therefore
* ignored every speed change (silo-android#1089).
*
* So while the viewer picks another speed, the sink refuses a bitstream it can
* decode locally and the TV presets turn tunneling off; at 1x both return.
* Audio no local decoder can handle stays a bitstream at 1x, as before.
*/
object PlaybackSpeedAudioPolicy {
/** Whether playing at [speed] needs decoded, untunneled audio. */
fun needsDecodedAudio(speed: Double): Boolean =
speed.isFinite() && abs(speed - 1.0) > SPEED_TOLERANCE

/** Whether the sink should refuse [format] as a bitstream so the renderer decodes it. */
fun shouldDecode(
format: Format,
decodedAudioNeeded: Boolean,
canDecodeLocally: (Format) -> Boolean,
): Boolean = decodedAudioNeeded && isBitstream(format) && canDecodeLocally(format)

/**
* Whether the mounted stream must mount again before decoded audio takes
* over. Turning tunneling off makes Media3 reset the audio renderer, which
* then asks the sink again; an untunneled bitstream gets no such reset, so
* its renderer keeps passing [inputFormat] through until the next mount.
*/
fun needsRemount(
output: AudioOutput?,
inputFormat: Format?,
canDecodeLocally: (Format) -> Boolean,
): Boolean {
if (output == null || output.path == AudioOutputPath.Pcm || output.tunneled) return false
val format = inputFormat ?: return false
return isBitstream(format) && canDecodeLocally(format)
}

@OptIn(UnstableApi::class)
private fun isBitstream(format: Format): Boolean {
val mime = format.sampleMimeType ?: return false
return MimeTypes.isAudio(mime) && mime != MimeTypes.AUDIO_RAW
}

private const val SPEED_TOLERANCE = 0.001
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.content.Context
import android.os.Handler
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.Format
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.Player
Expand All @@ -17,6 +18,7 @@ import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
import androidx.media3.exoplayer.mediacodec.MediaCodecUtil
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
import androidx.media3.exoplayer.video.VideoRendererEventListener
import androidx.media3.exoplayer.audio.AudioSink
Expand Down Expand Up @@ -138,6 +140,13 @@ class SiloPlayerFactory(
)

@Volatile private var mediaRouteScope: MediaRouteScope? = null

/** Set while solo video plays at a speed other than 1x; see [PlaybackSpeedAudioPolicy]. */
@Volatile private var decodedAudioForSpeed: Boolean = false

/** Whether the last player built carries the FFmpeg audio renderer. */
@Volatile private var ffmpegAudioEnabled: Boolean = false
private val ffmpegAudioMimeTypes: Set<String> by lazy { FfmpegAudioSupport.supportedMimeTypes() }
@Volatile private var resumableDirectPlayUri: android.net.Uri? = null
private val nextMountInstanceId = AtomicLong(0L)
private val playerMismatchLock = Any()
Expand Down Expand Up @@ -261,6 +270,8 @@ class SiloPlayerFactory(
DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF
}

ffmpegAudioEnabled = preferFfmpegAudio

// Build a single-processor chain that hosts the per-profile audio
// delay processor. The chain is owned by the factory and shared
// across players because Koin gives us a single DelayAudioProcessor
Expand All @@ -273,8 +284,10 @@ class SiloPlayerFactory(
)
.build(),
forceDecode = { format ->
preferFfmpegAudio &&
val decodeDtsWithFfmpeg = preferFfmpegAudio &&
HdmiSinkDtsSupport.shouldDecodeWithFfmpeg(context, format.sampleMimeType)
decodeDtsWithFfmpeg ||
PlaybackSpeedAudioPolicy.shouldDecode(format, decodedAudioForSpeed, ::canDecodeAudioLocally)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
)

Expand Down Expand Up @@ -517,7 +530,11 @@ class SiloPlayerFactory(
preferredAudioLanguage: String? = null,
preferredTextLanguage: String? = null,
hdrEnabled: Boolean = true,
decodedAudioForSpeed: Boolean = false,
): Boolean {
// Set even when the reselection below is skipped: the sink reads it
// whenever it is next asked about a format, including the next mount.
this.decodedAudioForSpeed = decodedAudioForSpeed
// ExoPlayer resolves a track reselection by seeking the current media
// period. With no media period — idle, empty timeline, or torn down
// while this was in flight — that path dereferences a null holder and
Expand Down Expand Up @@ -546,6 +563,7 @@ class SiloPlayerFactory(
displayHdr = displayHdr,
preferredAudioLanguage = preferredAudioLanguage,
allowHdr = hdrEnabled,
decodedAudioForSpeed = decodedAudioForSpeed,
)
} else {
TrackSelectionPresets.buildPhoneParameters(
Expand All @@ -561,6 +579,37 @@ class SiloPlayerFactory(
return true
}

/**
* Whether the mounted stream has to mount again before the speed set with
* `decodedAudioForSpeed` can apply; see [PlaybackSpeedAudioPolicy.needsRemount].
*/
fun needsRemountForDecodedAudio(): Boolean =
decodedAudioForSpeed &&
PlaybackSpeedAudioPolicy.needsRemount(
output = playbackAnalytics.audioOutput.value,
inputFormat = playbackAnalytics.audioInputFormat,
canDecodeLocally = ::canDecodeAudioLocally,
)

/**
* Whether a platform decoder or the FFmpeg renderer can turn [format] into
* PCM. A platform decoder must handle the stream's profile, sample rate,
* and channel count, the test MediaCodecAudioRenderer applies; a decoder
* that only matches the MIME type could fail where passthrough played.
*/
private fun canDecodeAudioLocally(format: Format): Boolean {
val mimeType = format.sampleMimeType ?: return false
if (ffmpegAudioEnabled && mimeType in ffmpegAudioMimeTypes) return true
return runCatching {
MediaCodecUtil.getDecoderInfosSoftMatch(
MediaCodecSelector.DEFAULT,
format,
/* requiresSecureDecoder = */ false,
/* requiresTunnelingDecoder = */ false,
).any { it.isFormatSupported(context, format) }
}.getOrDefault(false)
}

/**
* Build a [MediaItem] the player can consume directly via `setMediaItem`.
* The MIME type hint on the item is what lets [DefaultMediaSourceFactory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,15 @@ object TrackSelectionPresets {
preferredAudioLanguage: String?,
allowHdr: Boolean = true,
ffmpegAvailable: Boolean = FfmpegAudioSupport.isAvailable(),
decodedAudioForSpeed: Boolean = false,
): DefaultTrackSelector.Parameters {
val audioMimes = buildTvAudioMimePreferences(audioCaps, ffmpegAvailable)
val videoMimes = buildTvVideoMimePreferences(displayHdr, allowHdr)
val tunnelingEnabled = TvPlaybackOutputPolicy.shouldEnableTunneling(
manufacturer = Build.MANUFACTURER,
model = Build.MODEL,
device = Build.DEVICE,
decodedAudioForSpeed = decodedAudioForSpeed,
)

val builder = base.toDefaultBuilder(context)
Expand Down Expand Up @@ -472,11 +474,17 @@ internal object TvPlaybackOutputPolicy {
display: HdrCapabilities,
): HdrCapabilities = DisplayHdrProbe.intersect(codec, display)

/**
* [decodedAudioForSpeed]: tunneled audio plays only at 1x, so a speed
* other than 1x turns tunneling off (see [PlaybackSpeedAudioPolicy]).
*/
fun shouldEnableTunneling(
manufacturer: String?,
model: String?,
device: String?,
decodedAudioForSpeed: Boolean = false,
): Boolean {
if (decodedAudioForSpeed) return false
val normalizedManufacturer = manufacturer.orEmpty().trim().lowercase()
val normalizedModel = model.orEmpty().trim().lowercase()
val normalizedDevice = device.orEmpty().trim().lowercase()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.siloserver.silo.common.player

import android.os.SystemClock

/**
* Paces the player screens' track-selection presets effect.
*
* A reselection seeks the current media period, and while an audio route
* change rebuilds the sink there is none, so a change to the route or another
* selection input waits [settleMs] for the reports to stop. A playback speed
* change moves no route and applies at once, but it still waits out a settle
* that another change started: the effect restarts on every key change, and
* the restart must not cut that wait short.
*/
class TrackSelectionSettle(
private val settleMs: Long,
private val nowMs: () -> Long = SystemClock::elapsedRealtime,
) {
private var settledAtMs = 0L
private var lastRouteInputs: Any? = null

/**
* How long to wait before applying presets. [routeInputs] holds every key
* of the effect except the speed requirement. Until presets have been
* [applied] once, nothing waits, because startup track selection must not
* be deferred.
*/
fun waitMs(routeInputs: Any, applied: Boolean): Long {
val now = nowMs()
if (applied && routeInputs != lastRouteInputs) settledAtMs = now + settleMs
lastRouteInputs = routeInputs
return (settledAtMs - now).coerceAtLeast(0L)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ class Media3VideoPlaybackBackend(
preferredAudioLanguage: String?,
preferredTextLanguage: String?,
hdrEnabled: Boolean,
decodedAudioForSpeed: Boolean,
): Boolean =
playerFactory.applyTrackSelectionPresets(
player = player,
Expand All @@ -108,8 +109,11 @@ class Media3VideoPlaybackBackend(
preferredAudioLanguage = preferredAudioLanguage,
preferredTextLanguage = preferredTextLanguage,
hdrEnabled = hdrEnabled,
decodedAudioForSpeed = decodedAudioForSpeed,
)

override fun needsRemountForDecodedAudio(): Boolean = playerFactory.needsRemountForDecodedAudio()

override fun release() {
currentMountInstanceId = null
playerFactory.releasePlayer(player)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,25 @@ interface VideoPlaybackBackend {

fun selectAudioTrack(track: VideoPlayerTrackEntry)

/** Returns whether presets were actually assigned; false = skipped. */
/**
* Returns whether presets were actually assigned; false = skipped.
* [decodedAudioForSpeed]: solo playback runs at a speed other than 1x
* (see [org.siloserver.silo.common.player.PlaybackSpeedAudioPolicy]).
*/
fun applyTrackSelection(
audioCaps: AudioPassthroughCapabilities,
displayHdr: HdrCapabilities = HdrCapabilities(),
preferredAudioLanguage: String? = null,
preferredTextLanguage: String? = null,
hdrEnabled: Boolean = true,
decodedAudioForSpeed: Boolean = false,
): Boolean

/**
* After [applyTrackSelection] with `decodedAudioForSpeed`: whether the
* mounted stream keeps bitstreaming its audio until it mounts again.
*/
fun needsRemountForDecodedAudio(): Boolean = false

fun release()
}
Loading
Loading