Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
996d1ce
fix(player): poll the phone's native subtitle mount deadline
Quick104 Oct 31, 2026
27fad7b
feat(playback): accept HLS subtitle renditions on copy remuxes
Quick104 Oct 29, 2026
38085f2
feat(playback): draw embedded MKV bitmap subtitles from the stream
Quick104 Oct 31, 2026
024532f
fix(player): stop retrying slow subtitle sidecars like media
Quick104 Oct 31, 2026
05aedd5
feat(player): switch subtitles on the playing stream without a remount
Quick104 Oct 31, 2026
807c7b1
fix(player): keep a negative subtitle offset on bitmap cues read from…
Quick104 Oct 31, 2026
db56cc7
test(tv): build the rendition switch rows the way the session project…
Quick104 Oct 31, 2026
593e0f8
fix(player): keep negative subtitle offsets on sample-relative embedd…
Quick104 Oct 31, 2026
db26b83
fix(player): send a phone audio pick as an audio track change
Quick104 Oct 31, 2026
e2cd7d3
fix(player): count a sidecar body cut off by a reset against its extr…
Quick104 Oct 31, 2026
17b3a5b
fix(tv): roll back an in-place subtitle switch over the mounted plan
Quick104 Oct 31, 2026
f9818dd
docs(tv): put commitLocallyMountableSelection's KDoc back on it
Quick104 Oct 31, 2026
9b2638d
fix(player): keep sidecars when the player rebuilds an item from itself
Quick104 Nov 1, 2026
8c6dd9c
fix(tv): restore the subtitle being mounted when a stalled transport …
Quick104 Nov 1, 2026
cf1bf4a
fix(tv): give a subtitle mount a whole window once tracks appear
Quick104 Nov 1, 2026
951475c
chore(player): log why a subtitle pick's answer is not adopted in place
Quick104 Nov 1, 2026
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
Expand Up @@ -128,6 +128,7 @@ val playerInfraModule = module {
libassBridge = get(),
playbackAnalytics = get(),
throughputMeter = get(),
sidecarSubtitleHttpDataSourceFactory = get(PLAYER_SIDECAR_SUBTITLE_HTTP_DATA_SOURCE_FACTORY_QUALIFIER),
)
}
// Video starts send the bandwidth probe's estimate, and plan summaries the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import org.siloserver.silo.common.player.PlaybackNetworkMonitor
import org.siloserver.silo.common.player.audio.DelayAudioProcessor
import org.siloserver.silo.common.player.buildPlayerOkHttpClient
import org.siloserver.silo.common.player.buildPlayerRefreshOkHttpClient
import org.siloserver.silo.common.player.withSidecarSubtitleTimeouts
import org.siloserver.silo.common.player.subtitle.SubtitleOffsetHolder
import org.siloserver.silo.libass.LibassBridge
import okhttp3.OkHttpClient
Expand All @@ -28,6 +29,7 @@ import org.koin.dsl.module
val PLAYER_OKHTTP_QUALIFIER = named("player-okhttp")
val PLAYER_TRANSPORT_OKHTTP_QUALIFIER = named("player-transport-okhttp")
val PLAYER_HTTP_DATA_SOURCE_FACTORY_QUALIFIER = named("player-http-data-source-factory")
val PLAYER_SIDECAR_SUBTITLE_HTTP_DATA_SOURCE_FACTORY_QUALIFIER = named("player-sidecar-subtitle-http-data-source-factory")
val AUDIOBOOK_PLAYBACK_SESSION_MANAGER_QUALIFIER = named("audiobook-playback-session-manager")
val AUDIOBOOK_PLAYBACK_SESSION_LIFECYCLE_QUALIFIER = named("audiobook-playback-session-lifecycle")

Expand Down Expand Up @@ -65,6 +67,16 @@ val playerModule = module {
OkHttpDataSource.Factory(org.siloserver.silo.common.player.auxiliaryAwareCallFactory(get<OkHttpClient>(PLAYER_TRANSPORT_OKHTTP_QUALIFIER)))
}

// Same pool and interceptors; only the per-read wait differs (#458).
@OptIn(UnstableApi::class)
single<HttpDataSource.Factory>(PLAYER_SIDECAR_SUBTITLE_HTTP_DATA_SOURCE_FACTORY_QUALIFIER) {
OkHttpDataSource.Factory(
org.siloserver.silo.common.player.auxiliaryAwareCallFactory(
get<OkHttpClient>(PLAYER_TRANSPORT_OKHTTP_QUALIFIER).withSidecarSubtitleTimeouts(),
),
)
}

@OptIn(UnstableApi::class)
single { DefaultBandwidthMeter.Builder(androidContext()).build() }

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package org.siloserver.silo.common.player

import androidx.media3.common.MediaItem
import androidx.media3.common.Timeline
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.TimelineWithUpdatedMediaItem
import androidx.media3.exoplayer.source.WrappingMediaSource

/**
* Reports [mediaItem], sidecars included, for a source built from a copy of
* it.
*
* The media source factory builds an item's content from a copy with its
* subtitle configurations removed and merges each sidecar beside it.
* `MergingMediaSource` reports its first child's item, so the player's
* timeline, and `Player.getMediaItemAt`, would name the copy. Anything that
* rebuilds the playlist from the player, such as the subtitle sync reprepare,
* then drops the sidecars. That also changes the merged track layout a text
* selection points at, so the selection is lost too.
*/
@UnstableApi
internal class FullMediaItemSource(
child: MediaSource,
private val mediaItem: MediaItem,
) : WrappingMediaSource(child) {

override fun getMediaItem(): MediaItem = mediaItem

/** An update would reach the children with the full item; let the player rebuild the source instead. */
override fun canUpdateMediaItem(mediaItem: MediaItem): Boolean = false

override fun onChildSourceInfoRefreshed(newTimeline: Timeline) {
refreshSourceInfo(TimelineWithUpdatedMediaItem.create(newTimeline, mediaItem))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package org.siloserver.silo.common.player

import org.siloserver.silo.model.playback.PlaybackDelivery
import org.siloserver.silo.model.playback.PlaybackExecutionPlan
import org.siloserver.silo.model.playback.PlaybackTimeline
import org.siloserver.silo.model.playback.PlayerSubtitleInfo
import org.siloserver.silo.model.playback.SubtitleIdentity
import org.siloserver.silo.model.playback.SubtitleValidationClaims
import org.siloserver.silo.model.playback.activeOriginalHttpClaims
import org.siloserver.silo.model.playback.carriesHlsSubtitleRendition

/**
* Whether the player may show [target] on the stream it is playing before the
* server answers the pick, instead of waiting for a replan and a remount.
*
* True for a track the media already carries and the server said the player
* may switch to: a native track of an `original_http` stream
* ([PlayerSubtitleInfo.nativeContainerTrackId] on a row other than the
* selected one), or a rendition of an HLS stream that lists every embedded
* text track ([PlayerSubtitleInfo.hlsRendition] with an index). Off qualifies
* on the same streams. The pick still goes to the server as a track change;
* its answer is applied in place when it keeps the transport
* ([org.siloserver.silo.common.player.VideoSessionStartV3.Ready.inPlace]).
*
* Phone and TV both ask this before taking the local-first path, and then
* whether Media3 lists the track.
*/
fun canSwitchSubtitleInPlace(
plan: PlaybackExecutionPlan?,
rows: List<PlayerSubtitleInfo>,
committed: SubtitleIdentity,
target: SubtitleIdentity,
): Boolean {
if (plan == null || target == committed || committed is SubtitleIdentity.ServerBurnIn) return false
return when (target) {
SubtitleIdentity.Off -> when {
plan.delivery == PlaybackDelivery.ORIGINAL_HTTP -> true
plan.delivery.carriesHlsSubtitleRendition() -> rows.any { it.hlsRendition?.index != null }
else -> false
}
is SubtitleIdentity.Embedded -> {
val row = rows.singleOrNull { it.index == target.serverIndex && it.serverTrackId != null }
?: return false
val nativeTrackId = target.containerTrackId
val rendition = target.hlsRendition
when {
nativeTrackId != null -> plan.delivery == PlaybackDelivery.ORIGINAL_HTTP &&
row.nativeContainerTrackId == nativeTrackId
rendition != null -> plan.delivery.carriesHlsSubtitleRendition() &&
rendition.index != null &&
row.hlsRendition == rendition
else -> false
}
}
is SubtitleIdentity.ServerSidecar,
is SubtitleIdentity.ServerBurnIn,
is SubtitleIdentity.Downloaded,
is SubtitleIdentity.LocalMedia3,
-> false
}
}

/**
* The part of [this] plan a mounted MediaItem is built from. A plan applied in
* place differs from the playing one only in its subtitle decision, its plan
* identity and its replan-time position, so it has the same key and leaves
* the mounted item alone. Every other plan change also comes with a new mount
* token, so keying a mount on this rather than on the whole plan only ever
* skips an in-place adoption.
*/
fun PlaybackExecutionPlan.mediaMountKey(): PlaybackExecutionPlan = copy(
planId = "",
timeline = PlaybackTimeline(
streamOriginSeconds = timeline.streamOriginSeconds,
timelineOffsetSeconds = timeline.timelineOffsetSeconds,
),
selectedTracks = selectedTracks.copy(subtitleIndex = null),
source = source.copy(subtitleCodec = null),
claims = claims.copy(subtitles = SubtitleValidationClaims()),
// Compared as sets, like the server's own same-route check.
transformations = transformations.sortedBy { "${it.executor}:${it.name}:${it.recipeVersion}" },
appliedQuirks = appliedQuirks.sortedBy { it.id },
runtimeCorrections = runtimeCorrections.sorted(),
availableQualities = emptyList(),
degradationWarnings = emptyList(),
// Only the claim a decision reason names reaches the renderer.
decisionTrace = activeOriginalHttpClaims(),
bandwidthLimit = null,
activeQuality = null,
activeQualityReported = false,
)

/**
* The plan to show once [adopted], a plan applied in place, replaces this
* mounted one: [adopted]'s subtitle decision, plan identity and menus over
* everything the MediaItem was built from. That keeps what the client changed
* on the mount itself (a PCM retry's audio claims and decision trace, the
* mount's timeline), so the media mount key and the stall detectors' key stay
* the same and nothing remounts.
*/
fun PlaybackExecutionPlan.withInPlaceAdoption(adopted: PlaybackExecutionPlan): PlaybackExecutionPlan = copy(
planId = adopted.planId,
selectedTracks = selectedTracks.copy(subtitleIndex = adopted.selectedTracks.subtitleIndex),
source = source.copy(subtitleCodec = adopted.source.subtitleCodec),
claims = claims.copy(subtitles = adopted.claims.subtitles),
availableQualities = adopted.availableQualities,
degradationWarnings = adopted.degradationWarnings,
bandwidthLimit = adopted.bandwidthLimit,
activeQuality = adopted.activeQuality,
activeQualityReported = adopted.activeQualityReported,
)

/**
* The stall detectors' key for one mounted MediaItem. It leaves out the plan
* id, which a plan applied in place changes while the same item keeps
* playing; [mountToken] changes with every remount.
*/
fun mountedPlaybackKey(
sessionId: String?,
streamUrl: String?,
plan: PlaybackExecutionPlan?,
mountToken: Long,
): String = "$sessionId:$streamUrl:${plan?.decisionTrace?.size ?: 0}:$mountToken"
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicReference
import okhttp3.internal.http2.ConnectionShutdownException
import okhttp3.internal.http2.StreamResetException

Expand Down Expand Up @@ -131,6 +132,189 @@ internal class SiloMediaLoadErrorHandlingPolicy(
}
}

/**
* Retries for sidecar subtitle loads, kept apart from the media policy above
* (#458).
*
* A sidecar request that times out or is cut off mid-body has made the server
* extract the track, which on a cold network mount means reading the whole
* source file, and its retry starts that read again. The media policy's
* open-ended retries inside [MEDIA_LOAD_RETRY_WINDOW_MS] turned one slow
* extraction into five or six concurrent whole-file reads. Here a sidecar
* retries at most [SIDECAR_SUBTITLE_MAX_EXTRACTION_RETRIES] such failures, of
* which at most [SIDECAR_SUBTITLE_MAX_TIMEOUT_RETRIES] timeouts. A slow first
* byte is not a failure at all: sidecar requests wait
* [SIDECAR_SUBTITLE_READ_TIMEOUT_SECONDS] for data
* ([withSidecarSubtitleTimeouts]) where media waits 30 s.
*
* Failures that cost no extraction keep the media policy and its window, so a
* subtitle rides out a server restart or a network drop as the video does: an
* error status, a refused connection, and a timeout before the connection
* opened (a connect or TLS handshake timeout, when no request reached the
* server).
*
* One policy serves one sidecar, and the budget is counted here rather than
* taken from `errorCount`, which Media3 resets after an attempt that extracted
* samples: a sidecar that keeps stalling after its first cues would otherwise
* retry without end. Nor is it kept per load task. For a response of unknown
* length Media3 declines the retry and restarts the stream from byte zero
* once the queued cues run out (a deferred retry), under a new load task, and
* that restart costs the server an extraction like any other. Only the
* sidecar's period knows when a load starts over on purpose: a seek, a new
* selection or a new start calls [startFresh].
*
* Once the budget is spent the load fails and only the subtitle is lost: the
* sidecar's period reports itself prepared from its known track
* ([org.siloserver.silo.common.player.subtitle.NonGatingSidecarPeriod]), so the
* failure reaches the text renderer, and Media3 disables the text track while
* the video keeps playing.
*/
@UnstableApi
internal class SidecarSubtitleLoadErrorHandlingPolicy(
private val nowMs: () -> Long = { android.os.SystemClock.elapsedRealtime() },
) : DefaultLoadErrorHandlingPolicy() {
private val budget = SidecarSubtitleRetryBudget()
private val attemptBytesTracker = MediaLoadAttemptBytesTracker()
private val firstErrorAtByLoadTask = ConcurrentHashMap<Long, Long>()

override fun getRetryDelayMsFor(loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo): Long {
val loadTaskId = loadErrorInfo.loadEventInfo.loadTaskId
val error = loadErrorInfo.exception
val invalidResponse = error as? HttpDataSource.InvalidResponseCodeException
val firstErrorAt = firstErrorAtByLoadTask.computeIfAbsent(loadTaskId) { nowMs() }
val bytesLoaded = attemptBytesTracker.bytesLoadedForAttempt(
loadTaskId = loadTaskId,
cumulativeBytesLoaded = loadErrorInfo.loadEventInfo.bytesLoaded,
)
val failures = budget.record(error, bytesLoaded)
val delayMs = sidecarSubtitleRetryDelayMs(
responseCode = invalidResponse?.responseCode,
retryAfterHeaders = invalidResponse?.retryAfterHeaders().orEmpty(),
cause = error,
failures = failures,
bytesLoaded = bytesLoaded,
observedElapsedMs = (nowMs() - firstErrorAt).coerceAtLeast(0L),
)
val description = "error=${generateSequence<Throwable>(error) { it.cause }.last().javaClass.simpleName} " +
"status=${invalidResponse?.responseCode} failures=${failures.count} " +
"timeouts=${failures.timeouts} cut_offs=${failures.cutOffs}"
if (delayMs == C.TIME_UNSET) {
SiloLog.w(DiagnosticsLogCategory.PLAYBACK, TAG, "sidecar subtitle load gave up $description")
} else {
SiloLog.i(DiagnosticsLogCategory.PLAYBACK, TAG, "sidecar subtitle load retry $description retry_delay_ms=$delayMs")
}
return delayMs
}

override fun onLoadTaskConcluded(loadTaskId: Long) {
attemptBytesTracker.onLoadTaskConcluded(loadTaskId)
firstErrorAtByLoadTask.remove(loadTaskId)
super.onLoadTaskConcluded(loadTaskId)
}

/** The sidecar's load starts over on purpose (a seek, a new selection or a new start): a fresh budget. */
fun startFresh() = budget.reset()

/** Failures that are still being retried never surface; a spent budget does, as a fatal load error. */
override fun getMinimumLoadableRetryCount(dataType: Int): Int =
Int.MAX_VALUE

private companion object {
const val TAG = "SidecarSubtitleRetry"
}
}

/**
* What one sidecar has failed with since it last started fresh, this failure included.
* [timeouts] and [cutOffs] are the failures that each cost the server an
* extraction.
*/
internal data class SidecarSubtitleFailures(
val count: Int,
val timeouts: Int = 0,
val cutOffs: Int = 0,
) {
val extractions: Int get() = timeouts + cutOffs
}

internal class SidecarSubtitleRetryBudget {
private val failures = AtomicReference(SidecarSubtitleFailures(count = 0))

/** [bytesLoaded] is what this attempt read before it failed. */
fun record(error: Throwable?, bytesLoaded: Long = 0L): SidecarSubtitleFailures {
val chain = generateSequence(error) { it.cause }.toList()
val timedOut = chain.any { it is SocketTimeoutException && !it.isBeforeRequest() }
// A response that stopped once its body had started: a short body, or
// a connection reset or closed under it. The server was extracting.
val cutOff = !timedOut && chain.any {
(it is ProtocolException && it.isUnexpectedEndOfStream()) ||
(bytesLoaded > 0L && (it is SocketException || it.isResumableTransportFailure()))
}
return failures.updateAndGet { before ->
SidecarSubtitleFailures(
count = before.count + 1,
timeouts = before.timeouts + if (timedOut) 1 else 0,
cutOffs = before.cutOffs + if (cutOff) 1 else 0,
)
}
}

fun reset() = failures.set(SidecarSubtitleFailures(count = 0))
}

/**
* A timeout while the connection was still being set up: no request reached
* the server, so no extraction started. Android reports a connect timeout as
* "failed to connect to … after 20000ms", the JVM as "connect timed out", and a
* stalled TLS handshake as "SSL handshake timed out".
*/
private fun SocketTimeoutException.isBeforeRequest(): Boolean {
val text = message?.lowercase() ?: return false
return "failed to connect" in text || "connect timed out" in text || "handshake" in text
}

internal fun sidecarSubtitleRetryDelayMs(
responseCode: Int? = null,
retryAfterHeaders: List<String> = emptyList(),
cause: Throwable? = null,
failures: SidecarSubtitleFailures,
bytesLoaded: Long = 0L,
observedElapsedMs: Long = 0L,
): Long {
if (failures.timeouts > SIDECAR_SUBTITLE_MAX_TIMEOUT_RETRIES) return C.TIME_UNSET
if (failures.extractions > SIDECAR_SUBTITLE_MAX_EXTRACTION_RETRIES) return C.TIME_UNSET
return siloMediaLoadRetryDelayMs(
responseCode = responseCode,
retryAfterHeaders = retryAfterHeaders,
cause = cause,
errorCount = failures.count,
// A body cut off by a stream reset or a closed connection is retried
// like one cut short, within the extraction budget above.
isResumableProgressiveDirectPlay = true,
bytesLoaded = bytesLoaded,
observedElapsedMs = observedElapsedMs,
)
}

/** Retries a sidecar load task gets after failures that each cost the server an extraction. */
internal const val SIDECAR_SUBTITLE_MAX_EXTRACTION_RETRIES = 2

/** Of those, retries after a request that timed out waiting for data. */
internal const val SIDECAR_SUBTITLE_MAX_TIMEOUT_RETRIES = 1

/**
* How long a sidecar request waits for its next bytes. A cold extraction sends
* the WebVTT header and then nothing until it reaches the first cue, which on a
* network mount can take minutes for a sparse track.
*/
internal const val SIDECAR_SUBTITLE_READ_TIMEOUT_SECONDS = 180L

/** The player transport, waiting [SIDECAR_SUBTITLE_READ_TIMEOUT_SECONDS] for each read. */
internal fun okhttp3.OkHttpClient.withSidecarSubtitleTimeouts(): okhttp3.OkHttpClient =
newBuilder()
.readTimeout(SIDECAR_SUBTITLE_READ_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
.build()

internal class MediaLoadAttemptBytesTracker {
private val cumulativeBytesByLoadTask = ConcurrentHashMap<Long, Long>()

Expand Down
Loading
Loading