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
@@ -1,17 +1,10 @@
package org.siloserver.silo.common.player

enum class PlaybackBufferMode(val wireValue: String, val label: String) {
QuickStart("quick_start", "Quick start"),
Balanced("balanced", "Balanced"),
SmoothPlayback("smooth_playback", "Smooth playback");

companion object {
fun fromWire(value: String?): PlaybackBufferMode = entries.firstOrNull {
it.wireValue == value
} ?: SmoothPlayback
}
}

/**
* Buffering policy derived from what the player can observe. There is no user
* setting and no server-supplied mode: the numbers follow from the device and
* the stream.
*/
data class PlaybackBufferPolicy(
val minBufferMs: Int,
val maxBufferMs: Int,
Expand All @@ -20,50 +13,159 @@ data class PlaybackBufferPolicy(
val targetBufferBytes: Int,
val prioritizeTimeOverSizeThresholds: Boolean,
) {
init {
require(maxBufferMs - minBufferMs == MAX_LOAD_IDLE_MS) {
"idle window must be exactly MAX_LOAD_IDLE_MS; maxBufferMs is derived, never written by hand"
}
}

companion object {
fun forMode(
mode: PlaybackBufferMode,
/**
* How long the load control may stop reading the socket, in MEDIA
* time.
*
* DefaultLoadControl fills to maxBufferMs, then requests nothing until
* the buffer drains below minBufferMs — so the gap between them is
* literally how long the connection sits idle, in the player's media
* clock. Upstream proxies close an idle response body based on WALL
* CLOCK time: nginx's send_timeout defaults to 60s. The old
* hand-written 50s/120s pair left a 70s gap and dropped the connection
* every time the buffer filled on a long direct-play file.
*
* Those two clocks only agree at 1.0x. DefaultLoadControl scales
* minBufferUs for speeds ABOVE 1.0, but not below it, and the UI
* offers rates down to [SLOWEST_PLAYBACK_SPEED] (0.5x, see
* SPEED_PRESETS in TvAudiobookSpeedPanel.kt and the clamp in
* AudiobookSpeedSheet.kt) for audiobooks, which share this load
* control. At 0.5x, one media-time second of idle window takes two
* wall-clock seconds to elapse — so a naive 30s media-time window
* becomes 60s of wall clock, exactly nginx's default send_timeout,
* with zero margin.
*
* 15_000 is that same 30s wall-clock budget scaled down by the
* slowest rate (30_000 * SLOWEST_PLAYBACK_SPEED = 15_000): at 0.5x it
* stretches back out to 30s of wall clock, half of
* ASSUMED_PROXY_SEND_TIMEOUT_MS, so the window holds at every speed
* the UI offers, not just 1.0x.
*
* maxBufferMs is therefore never written by hand; it is always
* minBufferMs + this. Depth can grow without ever widening the window.
*/
const val MAX_LOAD_IDLE_MS = 15_000

/**
* The slowest rate the UI lets a viewer select (see SPEED_PRESETS in
* TvAudiobookSpeedPanel.kt and the 0.5f..3.0f clamp in
* AudiobookSpeedSheet.kt). Named so the derivation of
* MAX_LOAD_IDLE_MS above isn't a bare magic number.
*/
const val SLOWEST_PLAYBACK_SPEED = 0.5

/** The timeout MAX_LOAD_IDLE_MS is chosen to stay clear of. */
const val ASSUMED_PROXY_SEND_TIMEOUT_MS = 60_000

/** Never buffer less than this, however constrained the device. */
const val MIN_DEPTH_MS = 20_000

/**
* Never buffer more than this even when memory allows. Past a few
* minutes we are mostly prefetching content the viewer may seek away
* from — wasted bandwidth, and wasted allowance on mobile data.
*/
const val MAX_DEPTH_MS = 180_000

private const val START_MS = 2_000

/**
* After a stall the viewer is watching a spinner, so the cushion we
* rebuild before resuming is deliberately small.
*/
private const val REBUFFER_MS = 5_000

fun forConditions(
deviceProfile: PlaybackBufferDeviceProfile = PlaybackBufferDeviceProfile.Unknown,
): PlaybackBufferPolicy = when (mode) {
PlaybackBufferMode.QuickStart -> PlaybackBufferPolicy(
minBufferMs = 30_000,
maxBufferMs = 60_000,
bufferForPlaybackMs = 2_000,
bufferForPlaybackAfterRebufferMs = 6_000,
targetBufferBytes = targetBufferBytes(deviceProfile, low = 32, medium = 64, roomy = 128),
prioritizeTimeOverSizeThresholds = false,
)
PlaybackBufferMode.Balanced -> PlaybackBufferPolicy(
minBufferMs = 50_000,
maxBufferMs = 120_000,
bufferForPlaybackMs = 3_000,
bufferForPlaybackAfterRebufferMs = 10_000,
targetBufferBytes = targetBufferBytes(deviceProfile, low = 48, medium = 96, roomy = 160),
prioritizeTimeOverSizeThresholds = false,
)
PlaybackBufferMode.SmoothPlayback -> PlaybackBufferPolicy(
minBufferMs = 90_000,
maxBufferMs = 180_000,
bufferForPlaybackMs = 5_000,
bufferForPlaybackAfterRebufferMs = 15_000,
targetBufferBytes = targetBufferBytes(deviceProfile, low = 64, medium = 128, roomy = 192),
): PlaybackBufferPolicy {
val depthMs = MAX_DEPTH_MS
return PlaybackBufferPolicy(
minBufferMs = depthMs,
maxBufferMs = depthMs + MAX_LOAD_IDLE_MS,
bufferForPlaybackMs = START_MS,
bufferForPlaybackAfterRebufferMs = REBUFFER_MS,
targetBufferBytes = memoryBudgetBytes(deviceProfile),
prioritizeTimeOverSizeThresholds = false,
)
}

private fun targetBufferBytes(
deviceProfile: PlaybackBufferDeviceProfile,
low: Int,
medium: Int,
roomy: Int,
): Int = when {
deviceProfile.isLowRamDevice || deviceProfile.memoryClassMb in 1 until 192 -> low * MIB
deviceProfile.memoryClassMb <= 0 -> low * MIB
deviceProfile.memoryClassMb in 192 until 384 -> medium * MIB
else -> roomy * MIB
/**
* The byte ceiling this device can afford. SiloLoadControl sizes the
* real target from the stream's bitrate and clamps it to this.
*
* This is a fraction of the app's own heap rather than a pick from
* fixed tiers. A fixed tier either starves a small-heap device (a
* flat 48 MiB floor is half of a 96 MB heap — a real OOM risk) or
* leaves a large-heap device's headroom unused (a flat 160 MiB
* ceiling caps a 1 GB heap the same as a 384 MB one). Scaling with
* memoryClassMb keeps the budget proportionate at both ends without
* hand-picking where the tier boundaries should sit.
*
* The fraction is half the heap, not a quarter. Measured hardware:
* the NVIDIA Shield reports memoryClass=192MB and the Google TV
* Streamer reports memoryClass=384MB, and neither is flagged
* low-RAM. A quarter-heap rule gives the Shield 48 MiB and the
* Streamer 96 MiB — LESS buffer than each device shipped with before
* this policy existed (96 MiB and 160 MiB respectively), the exact
* opposite of scaling correctly from small-memory devices to large
* ones. Half the heap gives the Shield 96 MiB and the Streamer
* 192 MiB (at the cap), both at or above their prior fixed values.
*/
internal fun memoryBudgetBytes(deviceProfile: PlaybackBufferDeviceProfile): Int {
val proportionalBytes =
if (deviceProfile.memoryClassMb > 0) {
deviceProfile.memoryClassMb.toLong() * MIB / MEMORY_BUDGET_HEAP_DIVISOR
} else {
null
}

if (deviceProfile.isLowRamDevice || deviceProfile.memoryClassMb <= 0) {
// A flat 24 MiB is the conservative fallback for a heap size
// we don't trust at all (unknown, or explicitly flagged
// low-RAM). But when memoryClassMb IS known, even on a
// low-RAM device, ignoring it can hand out MORE than the
// proportional share would — a low-RAM stick reporting 48MB
// would get 24 MiB verbatim, half its heap, exactly the flaw
// the proportional rule exists to remove. Take the smaller
// of the two so the flat fallback only ever tightens the
// budget, never loosens it.
return proportionalBytes
?.coerceAtMost(LOW_RAM_MEMORY_BUDGET_BYTES.toLong())
?.toInt()
?: LOW_RAM_MEMORY_BUDGET_BYTES
}
return checkNotNull(proportionalBytes)
.coerceIn(MIN_MEMORY_BUDGET_BYTES.toLong(), MAX_MEMORY_BUDGET_BYTES.toLong())
.toInt()
}

private const val MIB = 1024 * 1024

/** The budget is this fraction (1/2) of the app heap — see [memoryBudgetBytes]. */
private const val MEMORY_BUDGET_HEAP_DIVISOR = 2L

/** Never budget less than this, however small the heap. */
private const val MIN_MEMORY_BUDGET_BYTES = 16 * MIB

/** Never budget more than this even on a very large heap. */
private const val MAX_MEMORY_BUDGET_BYTES = 192 * MIB

/**
* Fixed fallback for devices that report no usable heap size, or that
* flag themselves as low-RAM outright — conservative rather than
* proportional, since half of an unknown heap is not a number worth
* trusting. When memoryClassMb is known, this is only a ceiling on
* the proportional share (see [memoryBudgetBytes]), not a value
* handed out regardless of what the device actually reports.
*/
private const val LOW_RAM_MEMORY_BUDGET_BYTES = 24 * MIB
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ class SiloLoadControl(
0,
false,
) {
@Volatile private var depthMs: Int = policy.minBufferMs

/** The forward buffer the memory budget currently affords, in ms. */
internal fun currentDepthMs(): Int = depthMs

override fun calculateTargetBufferBytes(
parameters: LoadControl.Parameters,
trackSelections: Array<out ExoTrackSelection?>,
Expand All @@ -51,13 +56,17 @@ class SiloLoadControl(
},
)
val fallback = super.calculateTargetBufferBytes(parameters, trackSelections)
return calculateBitrateTargetBufferBytes(
selectedBitrateBps = selectedBitrateBps,
desiredForwardBufferMs = policy.minBufferMs,
minimumBytes = MIN_TARGET_BUFFER_BYTES,
maximumBytes = policy.targetBufferBytes,
unknownBitrateFallbackBytes = fallback,
)
val result =
computeBufferSizing(
selectedBitrateBps = selectedBitrateBps,
desiredDepthMs = policy.minBufferMs,
minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS,
budgetBytes = policy.targetBufferBytes,
minimumBytes = MIN_TARGET_BUFFER_BYTES,
unknownBitrateFallbackBytes = fallback,
)
depthMs = result.depth.ms
return result.target.bytes
}

companion object {
Expand Down Expand Up @@ -89,6 +98,102 @@ internal fun selectBufferSizingBitrateBps(
?.takeIf { it > 0L }
}

/**
* The forward buffer this device can actually hold at this bitrate.
*
* Memory is finite, so a high-bitrate stream genuinely cannot be buffered as
* deeply as a low-bitrate one. Computing that reduction here — rather than
* letting the byte clamp truncate the buffer wherever it happens to land —
* means the resulting depth is a number the code chose and can be reasoned
* about, and it keeps maxBufferMs one idle window above a depth that is real.
*
* The budget is authoritative: when it affords less than [minimumDepthMs],
* that shortfall is reported honestly rather than padded up to a floor the
* loader cannot actually hold — a false-but-round number is worse than an
* honest one `currentDepthMs()` can be trusted to reflect. [minimumDepthMs]
* only bounds the *unknown-bitrate* branch below, where there is no bitrate
* to derive a number from at all.
*
* The division by 115/100 mirrors the same overhead margin
* [calculateBitrateTargetBufferBytes] multiplies back in when it turns a
* depth into bytes. Without it, a budget-derived depth still produces a byte
* figure that overshoots the budget once that margin is applied, silently
* clamps back down to the ceiling, and erases the depth's effect on the byte
* target — the two must agree, or reducing the depth changes nothing.
*/
internal fun affordableDepthMs(
desiredDepthMs: Int,
selectedBitrateBps: Long?,
budgetBytes: Int,
minimumDepthMs: Int,
): Int {
val bitrate = selectedBitrateBps?.takeIf { it > 0L }
?: return desiredDepthMs.coerceAtLeast(minimumDepthMs)
val affordableMs = budgetBytes.toLong() * 8L * 1_000L * 100L / (bitrate * 115L)
return affordableMs.coerceAtMost(desiredDepthMs.toLong()).toInt()
}

/** A forward-buffer depth, in milliseconds. Wrapped so it cannot be confused with [BufferTargetBytes]. */
@JvmInline
internal value class BufferDepthMs(val ms: Int)

/** A load-control byte target. Wrapped so it cannot be confused with [BufferDepthMs]. */
@JvmInline
internal value class BufferTargetBytes(val bytes: Int)

/**
* The composed result of sizing the buffer: the depth chosen and the bytes it
* maps to. Both are wrapped value classes rather than bare `Int`s so that
* assigning the wrong one to the wrong destination — e.g. storing the byte
* target where the depth belongs — is a compile error, not a bug only a test
* exercising the Media3 override could catch.
*/
internal data class BufferSizingResult(val depth: BufferDepthMs, val target: BufferTargetBytes)

/**
* Composes [affordableDepthMs] and [calculateBitrateTargetBufferBytes] into the
* single decision `calculateTargetBufferBytes` needs: how deep a buffer the
* budget affords, and how many bytes that depth costs at this bitrate.
*
* Kept separate from the Media3 override so it can be tested directly without
* constructing track selections — the override is a thin adapter over this.
*/
internal fun computeBufferSizing(
selectedBitrateBps: Long?,
desiredDepthMs: Int,
minimumDepthMs: Int,
budgetBytes: Int,
minimumBytes: Int,
unknownBitrateFallbackBytes: Int,
): BufferSizingResult {
val depthMs =
affordableDepthMs(
desiredDepthMs = desiredDepthMs,
selectedBitrateBps = selectedBitrateBps,
budgetBytes = budgetBytes,
minimumDepthMs = minimumDepthMs,
)
val targetBytes =
calculateBitrateTargetBufferBytes(
selectedBitrateBps = selectedBitrateBps,
desiredForwardBufferMs = depthMs,
// calculateBitrateTargetBufferBytes requires maximumBytes >=
// minimumBytes. That holds today only because
// MIN_MEMORY_BUDGET_BYTES and MIN_TARGET_BUFFER_BYTES are both
// exactly 16 MiB — a coincidence a future change to either
// constant could break, throwing IllegalArgumentException on the
// playback thread during track selection. The relation is
// restored by lowering the floor rather than raising the ceiling,
// so the memory budget stays the binding limit: a device whose
// budget is under the nominal floor gets a smaller buffer, never
// one that overruns the heap it was allowed.
minimumBytes = minimumBytes.coerceIn(1, budgetBytes.coerceAtLeast(1)),
maximumBytes = budgetBytes.coerceAtLeast(1),
unknownBitrateFallbackBytes = unknownBitrateFallbackBytes,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
return BufferSizingResult(depth = BufferDepthMs(depthMs), target = BufferTargetBytes(targetBytes))
}

internal fun calculateBitrateTargetBufferBytes(
selectedBitrateBps: Long?,
desiredForwardBufferMs: Int,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,15 +311,11 @@ class SiloPlayerFactory(
loadErrorHandlingPolicy = mediaLoadErrorHandlingPolicy,
)

// Staged buffer: start once a modest cushion is ready, wait longer
// after an actual stall, and let playback grow a deeper forward
// buffer in the background. A finite byte cap lets low-bitrate
// streams grow toward the time limit while preventing high-bitrate
// remuxes from filling the app heap on memory-constrained TVs.
val bufferPolicy = PlaybackBufferPolicy.forMode(
PlaybackBufferMode.Balanced,
playbackBufferDeviceProfile(),
)
// Start on a small cushion and keep filling in the background. Depth is
// bounded by the device's memory budget in SiloLoadControl; the gap
// between min and max is fixed so the connection is never idle long
// enough for an upstream proxy to close it.
val bufferPolicy = PlaybackBufferPolicy.forConditions(playbackBufferDeviceProfile())
val loadControl = SiloLoadControl(bufferPolicy)

val builder = ExoPlayer.Builder(context, renderersFactory)
Expand Down
Loading